_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q3400 | Artifact.fetch | train | def fetch(self):
"""
Method for getting artifact's content.
Could only be applicable for file type.
:return: content of the artifact.
"""
if self.data.type == self._manager.FOLDER_TYPE:
raise YagocdException("Can't fetch folder <{}>, only file!".format(self._... | python | {
"resource": ""
} |
q3401 | LTILaunchValidator.validate_launch_request | train | 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: dict... | python | {
"resource": ""
} |
q3402 | Lightning.enable_ipython | train | 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.
"""
# ... | python | {
"resource": ""
} |
q3403 | Lightning.disable_ipython | train | 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.
"""
from IPython.core.getipython import get_ipython
self.ipython_enabled = F... | python | {
"resource": ""
} |
q3404 | Lightning.create_session | train | 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.
"""
self.session = Session.create(self, name=name)
return self.... | python | {
"resource": ""
} |
q3405 | Lightning.use_session | train | 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.
"""
self.session = Session(lgn=self, id=session_id)
return self.se... | python | {
"resource": ""
} |
q3406 | Lightning.set_basic_auth | train | def set_basic_auth(self, username, password):
"""
Set authenatication.
"""
from requests.auth import HTTPBasicAuth
self.auth = HTTPBasicAuth(username, password)
return self | python | {
"resource": ""
} |
q3407 | Lightning.set_host | train | 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.
"""
if host[-1] == '/':
host =... | python | {
"resource": ""
} |
q3408 | Lightning.check_status | train | def check_status(self):
"""
Check the server for status
"""
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 serv... | python | {
"resource": ""
} |
q3409 | Base._clean_data | train | 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). Oth... | python | {
"resource": ""
} |
q3410 | Base._baseplot | train | 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 pl... | python | {
"resource": ""
} |
q3411 | Base.update | train | def update(self, *args, **kwargs):
"""
Base method for updating data.
Applies a plot-type specific cleaning operation, then
updates the data in the visualization.
"""
data = self._clean_data(*args, **kwargs)
if 'images' in data:
images = data['images... | python | {
"resource": ""
} |
q3412 | Base.append | train | def append(self, *args, **kwargs):
"""
Base method for appending data.
Applies a plot-type specific cleaning operation, then
appends data to the visualization.
"""
data = self._clean_data(*args, **kwargs)
if 'images' in data:
images = data['images']
... | python | {
"resource": ""
} |
q3413 | Base._get_user_data | train | def _get_user_data(self):
"""
Base method for retrieving user data from a viz.
"""
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... | python | {
"resource": ""
} |
q3414 | check_property | train | def check_property(prop, name, **kwargs):
"""
Check and parse a property with either a specific checking function
or a generic parser
"""
checkers = {
'color': check_color,
'alpha': check_alpha,
'size': check_size,
'thickness': check_thickness,
'index': check... | python | {
"resource": ""
} |
q3415 | check_colormap | train | def check_colormap(cmap):
"""
Check if cmap is one of the colorbrewer maps
"""
names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu',
'PuBuGn', 'PuRd', '... | python | {
"resource": ""
} |
q3416 | polygon_to_mask | train | 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
"""
bounds = array(coords).astype('int')
path = Path(bounds)
grid = meshgrid(range(dims[1]), range(dims[0]))
... | python | {
"resource": ""
} |
q3417 | polygon_to_points | train | 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
"""
bounds = array(coords).astype('int')
bmax = bounds.max(0)
bmin = bounds.min(0)
path = Path(bounds)
grid = meshgrid(range(bmin[0],... | python | {
"resource": ""
} |
q3418 | VisualizationLocal.save_html | train | def save_html(self, filename=None, overwrite=False):
"""
Save self-contained html to a file.
Parameters
----------
filename : str
The filename to save to
"""
if filename is None:
raise ValueError('Please provide a filename, e.g. viz.save_... | python | {
"resource": ""
} |
q3419 | temporary_unavailable | train | 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 request... | python | {
"resource": ""
} |
q3420 | simplify_specifiers | train | def simplify_specifiers(spec):
"""Try to simplify a SpecifierSet by combining redundant specifiers."""
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:
... | python | {
"resource": ""
} |
q3421 | SymbolFUNCTION.reset | train | def reset(self, lineno=None, offset=None, type_=None):
""" This is called when we need to reinitialize the instance state
"""
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 el... | python | {
"resource": ""
} |
q3422 | check_type | train | def check_type(*args, **kwargs):
''' 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
... | python | {
"resource": ""
} |
q3423 | TranslatorVisitor.norm_attr | train | def norm_attr(self):
""" Normalize attr state
"""
if not self.HAS_ATTR:
return
self.HAS_ATTR = False
self.emit('call', 'COPY_ATTR', 0)
backend.REQUIRES.add('copy_attr.asm') | python | {
"resource": ""
} |
q3424 | TranslatorVisitor.traverse_const | train | def traverse_const(node):
""" Traverses a constant and returns an string
with the arithmetic expression
"""
if node.token == 'NUMBER':
return node.t
if node.token == 'UNARY':
mid = node.operator
if mid == 'MINUS':
result = ' -'... | python | {
"resource": ""
} |
q3425 | TranslatorVisitor.check_attr | train | def check_attr(node, n):
""" Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code.
"""
if len(node.children) > n:
return node.children[n] | python | {
"resource": ""
} |
q3426 | Translator.loop_exit_label | train | 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'
"""
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][1]
... | python | {
"resource": ""
} |
q3427 | Translator.loop_cont_label | train | 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'
"""
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][... | python | {
"resource": ""
} |
q3428 | Translator.has_control_chars | train | def has_control_chars(i):
""" Returns true if the passed token is an unknown string
or a constant string having control chars (inverse, etc
"""
if not hasattr(i, 'type_'):
return False
if i.type_ != Type.string:
return False
if i.token in ('VAR',... | python | {
"resource": ""
} |
q3429 | BuiltinTranslator.visit_USR | train | def visit_USR(self, node):
""" Machine code call from basic
"""
self.emit('fparam' + self.TSUFFIX(gl.PTR_TYPE), node.children[0].t)
self.emit('call', 'USR', node.type_.size)
backend.REQUIRES.add('usr.asm') | python | {
"resource": ""
} |
q3430 | DefinesTable.define | train | 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.
"""
if fname is None:
if CURRENT_FILE:
fname = CURRENT_FILE[-1]
else: # If no files opened yet, use... | python | {
"resource": ""
} |
q3431 | DefinesTable.set | train | def set(self, id_, lineno, value='', fname=None, args=None):
""" Like the above, but issues no warning on duplicate macro
definitions.
"""
if fname is None:
if CURRENT_FILE:
fname = CURRENT_FILE[-1]
else: # If no files opened yet, use owns pro... | python | {
"resource": ""
} |
q3432 | SymbolPARAMLIST.appendChild | train | def appendChild(self, param):
''' Overrides base class.
'''
Symbol.appendChild(self, param)
if param.offset is None:
param.offset = self.size
self.size += param.size | python | {
"resource": ""
} |
q3433 | SymbolTable.get_entry | train | 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.
"""
if id_[-1] in DEPRECATED_SUFFIXES:
id_ = id_[:-1] # Remove it
... | python | {
"resource": ""
} |
q3434 | SymbolTable.check_is_declared | train | 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... | python | {
"resource": ""
} |
q3435 | SymbolTable.check_is_undeclared | train | 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.
"""
result = self.get_entry(id_, s... | python | {
"resource": ""
} |
q3436 | SymbolTable.check_class | train | 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 cl... | python | {
"resource": ""
} |
q3437 | SymbolTable.enter_scope | train | 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).
"""
old_mangle = self.mangle
self.mangle = '%s%s%s' % (self.mangle, global_.M... | python | {
"resource": ""
} |
q3438 | SymbolTable.leave_scope | train | def leave_scope(self):
""" Ends a function body and pops current scope out of the symbol table.
"""
def entry_size(entry):
""" For local variables and params, returns the real variable or
local array size in bytes
"""
if entry.scope == SCOPE.global... | python | {
"resource": ""
} |
q3439 | SymbolTable.move_to_global_scope | train | 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.
"""
# In the current scope and more than 1 scope?
if id_ in self.table[self.curr... | python | {
"resource": ""
} |
q3440 | SymbolTable.access_id | train | 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... | python | {
"resource": ""
} |
q3441 | SymbolTable.access_array | train | 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.
"""
if not self.check_i... | python | {
"resource": ""
} |
q3442 | SymbolTable.declare_variable | train | 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.
"""
assert isinstance(type_, symbols.TYPEREF)
if... | python | {
"resource": ""
} |
q3443 | SymbolTable.declare_type | train | 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.
"""
assert isinstance(type_, symbols.TYPE)
# Checks it's not a basic ty... | python | {
"resource": ""
} |
q3444 | SymbolTable.declare_const | train | def declare_const(self, id_, lineno, type_, default_value):
""" Similar to the above. But declares a Constant.
"""
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:
... | python | {
"resource": ""
} |
q3445 | SymbolTable.declare_param | train | def declare_param(self, id_, lineno, type_=None):
""" Declares a parameter
Check if entry.declared is False. Otherwise raises an error.
"""
if not self.check_is_undeclared(id_, lineno, classname='parameter',
scope=self.current_scope, show_error=Tru... | python | {
"resource": ""
} |
q3446 | SymbolTable.check_labels | train | def check_labels(self):
""" Checks if all the labels has been declared
"""
for entry in self.labels:
self.check_is_declared(entry.name, entry.lineno, CLASS.label) | python | {
"resource": ""
} |
q3447 | SymbolTable.check_classes | train | 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.
"""
for entry in self[scope].values():
if entry.class_ is None:
syntax_error(entry... | python | {
"resource": ""
} |
q3448 | SymbolTable.vars_ | train | def vars_(self):
""" Returns symbol instances corresponding to variables
of the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var] | python | {
"resource": ""
} |
q3449 | SymbolTable.labels | train | def labels(self):
""" Returns symbol instances corresponding to labels
in the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label] | python | {
"resource": ""
} |
q3450 | SymbolTable.types | train | def types(self):
""" Returns symbol instances corresponding to type declarations
within the current scope.
"""
return [x for x in self[self.current_scope].values() if isinstance(x, symbols.TYPE)] | python | {
"resource": ""
} |
q3451 | SymbolTable.arrays | train | def arrays(self):
""" Returns symbol instances corresponding to arrays
of the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array] | python | {
"resource": ""
} |
q3452 | SymbolTable.functions | train | def functions(self):
""" Returns symbol instances corresponding to functions
of the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ in
(CLASS.function, CLASS.sub)] | python | {
"resource": ""
} |
q3453 | SymbolTable.aliases | train | def aliases(self):
""" Returns symbol instances corresponding to aliased vars.
"""
return [x for x in self[self.current_scope].values() if x.is_aliased] | python | {
"resource": ""
} |
q3454 | check_type | train | def check_type(lineno, type_list, arg):
""" Check arg's type is one in type_list, otherwise,
raises an error.
"""
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 expre... | python | {
"resource": ""
} |
q3455 | check_call_arguments | train | 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.
"""
if not global_.SYMBOL_TABLE.check_is_declared(id_, lineno, 'function'):
return False
if not glo... | python | {
"resource": ""
} |
q3456 | check_pending_calls | train | def check_pending_calls():
""" Calls the above function for each pending call of the current scope
level
"""
result = True
# Check for functions defined after calls (parametres, etc)
for id_, params, lineno in global_.FUNCTION_CALLS:
result = result and check_call_arguments(lineno, id_,... | python | {
"resource": ""
} |
q3457 | check_pending_labels | train | def check_pending_labels(ast):
""" Iteratively traverses the node looking for ID with no class set,
marks them as labels, and check they've been declared.
This way we avoid stack overflow for high line-numbered listings.
"""
result = True
visited = set()
pending = [ast]
while pending:
... | python | {
"resource": ""
} |
q3458 | is_null | train | def is_null(*symbols):
""" True if no nodes or all the given nodes are either
None, NOP or empty blocks. For blocks this applies recursively
"""
from symbols.symbol_ import Symbol
for sym in symbols:
if sym is None:
continue
if not isinstance(sym, Symbol):
re... | python | {
"resource": ""
} |
q3459 | is_const | train | def is_const(*p):
""" A constant in the program, like CONST a = 5
"""
return is_SYMBOL('VAR', *p) and all(x.class_ == CLASS.const for x in p) | python | {
"resource": ""
} |
q3460 | is_number | train | def is_number(*p):
""" Returns True if ALL of the arguments are AST nodes
containing NUMBER or numeric CONSTANTS
"""
try:
for i in p:
if i.token != 'NUMBER' and (i.token != 'ID' or i.class_ != CLASS.const):
return False
return True
except:
pass
... | python | {
"resource": ""
} |
q3461 | is_unsigned | train | def is_unsigned(*p):
""" Returns false unless all types in p are unsigned
"""
from symbols.type_ import Type
try:
for i in p:
if not i.type_.is_basic or not Type.is_unsigned(i.type_):
return False
return True
except:
pass
return False | python | {
"resource": ""
} |
q3462 | is_type | train | def is_type(type_, *p):
""" True if all args have the same type
"""
try:
for i in p:
if i.type_ != type_:
return False
return True
except:
pass
return False | python | {
"resource": ""
} |
q3463 | is_block_accessed | train | def is_block_accessed(block):
""" Returns True if a block is "accessed". A block of code is accessed if
it has a LABEL and it is used in a GOTO, GO SUB or @address access
:param block: A block of code (AST node)
:return: True / False depending if it has labels accessed or not
"""
if is_LABEL(blo... | python | {
"resource": ""
} |
q3464 | common_type | train | def common_type(a, b):
""" Returns a type which is common for both a and b types.
Returns None if no common types allowed.
"""
from symbols.type_ import SymbolBASICTYPE as BASICTYPE
from symbols.type_ import Type as TYPE
from symbols.type_ import SymbolTYPE
if a is None or b is None:
... | python | {
"resource": ""
} |
q3465 | _sub16 | train | def _sub16(ins):
''' Pops last 2 words from the stack and subtract them.
Then push the result onto the stack. Top of the stack is
subtracted Top -1
Optimizations:
* If 2nd op is ZERO,
then do NOTHING: A - 0 = A
* If any of the operands is < 4, then
DEC is used
* If a... | python | {
"resource": ""
} |
q3466 | _mul16 | train | def _mul16(ins):
''' Multiplies tow last 16bit values on top of the stack and
and returns the value on top of the stack
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A
*... | python | {
"resource": ""
} |
q3467 | _divu16 | train | def _divu16(ins):
''' Divides 2 16bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd op is 1 then
do nothing
* If 2nd op is 2 then
Shift Right Logical
'''
op1, op2 = tuple(ins.quad[2:])
if is_int(op1) and int(op1) == 0: # 0 / A = 0
... | python | {
"resource": ""
} |
q3468 | _modu16 | train | def _modu16(ins):
''' Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 1 => Return 0
* If 2nd operand = 2^n => do AND (2^n - 1)
'''
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int16(op2)
... | python | {
"resource": ""
} |
q3469 | _shru16 | train | def _shru16(ins):
''' Logical right shift 16bit unsigned integer.
The result is pushed onto the stack.
Optimizations:
* If 2nd op is 0 then
do nothing
* If 2nd op is 1
Shift Right Arithmetic
'''
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op = int16(op2)
... | python | {
"resource": ""
} |
q3470 | read_txt_file | train | def read_txt_file(fname):
"""Reads a txt file, regardless of its encoding
"""
encodings = ['utf-8-sig', 'cp1252']
with open(fname, 'rb') as f:
content = bytes(f.read())
for i in encodings:
try:
result = content.decode(i)
if six.PY2:
result = r... | python | {
"resource": ""
} |
q3471 | TZX.out | train | def out(self, l):
""" Adds a list of bytes to the output string
"""
if not isinstance(l, list):
l = [l]
self.output.extend([int(i) & 0xFF for i in l]) | python | {
"resource": ""
} |
q3472 | TZX.standard_block | train | def standard_block(self, _bytes):
""" Adds a standard block of bytes
"""
self.out(self.BLOCK_STANDARD) # Standard block ID
self.out(self.LH(1000)) # 1000 ms standard pause
self.out(self.LH(len(_bytes) + 1)) # + 1 for CHECKSUM byte
checksum = 0
for i in _bytes:... | python | {
"resource": ""
} |
q3473 | TZX.dump | train | def dump(self, fname):
""" Saves TZX file to fname
"""
with open(fname, 'wb') as f:
f.write(self.output) | python | {
"resource": ""
} |
q3474 | TZX.standard_bytes_header | train | def standard_bytes_header(self, title, addr, length):
""" Generates a standard header block of CODE type
"""
self.save_header(self.HEADER_TYPE_CODE, title, length, param1=addr, param2=32768) | python | {
"resource": ""
} |
q3475 | TZX.standard_program_header | train | def standard_program_header(self, title, length, line=32768):
""" Generates a standard header block of PROGRAM type
"""
self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length) | python | {
"resource": ""
} |
q3476 | TZX.save_code | train | def save_code(self, title, addr, _bytes):
""" Saves the given bytes as code. If bytes are strings,
its chars will be converted to bytes
"""
self.standard_bytes_header(title, addr, len(_bytes))
_bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in _bytes] # & 0xFF truncates... | python | {
"resource": ""
} |
q3477 | TZX.save_program | train | def save_program(self, title, bytes, line=32768):
""" Saves the given bytes as a BASIC program.
"""
self.standard_program_header(title, len(bytes), line)
bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in bytes] # & 0xFF truncates to bytes
self.standard_block(bytes) | python | {
"resource": ""
} |
q3478 | SymbolSTRSLICE.make_node | train | def make_node(cls, lineno, s, lower, upper):
""" Creates a node for a string slice. S is the string expression Tree.
Lower and upper are the bounds, if lower & upper are constants, and
s is also constant, then a string constant is returned.
If lower > upper, an empty string is returned.... | python | {
"resource": ""
} |
q3479 | to_byte | train | def to_byte(stype):
""" Returns the instruction sequence for converting from
the given type to byte.
"""
output = []
if stype in ('i8', 'u8'):
return []
if is_int_type(stype):
output.append('ld a, l')
elif stype == 'f16':
output.append('ld a, e')
elif stype == '... | python | {
"resource": ""
} |
q3480 | _end | train | def _end(ins):
""" Outputs the ending sequence
"""
global FLAG_end_emitted
output = _16bit_oper(ins.quad[1])
output.append('ld b, h')
output.append('ld c, l')
if FLAG_end_emitted:
return output + ['jp %s' % END_LABEL]
FLAG_end_emitted = True
output.append('%s:' % END_LABEL... | python | {
"resource": ""
} |
q3481 | _var | train | def _var(ins):
""" Defines a memory variable.
"""
output = []
output.append('%s:' % ins.quad[1])
output.append('DEFB %s' % ((int(ins.quad[2]) - 1) * '00, ' + '00'))
return output | python | {
"resource": ""
} |
q3482 | _lvarx | train | def _lvarx(ins):
""" Defines a local variable. 1st param is offset of the local variable.
2nd param is the type a list of bytes in hexadecimal.
"""
output = []
l = eval(ins.quad[3]) # List of bytes to push
label = tmp_label()
offset = int(ins.quad[1])
tmp = list(ins.quad)
tmp[1] = ... | python | {
"resource": ""
} |
q3483 | _lvard | train | def _lvard(ins):
""" Defines a local variable. 1st param is offset of the local variable.
2nd param is a list of bytes in hexadecimal.
"""
output = []
l = eval(ins.quad[2]) # List of bytes to push
label = tmp_label()
offset = int(ins.quad[1])
tmp = list(ins.quad)
tmp[1] = label
... | python | {
"resource": ""
} |
q3484 | _out | train | def _out(ins):
""" Translates OUT to asm.
"""
output = _8bit_oper(ins.quad[2])
output.extend(_16bit_oper(ins.quad[1]))
output.append('ld b, h')
output.append('ld c, l')
output.append('out (c), a')
return output | python | {
"resource": ""
} |
q3485 | _in | train | def _in(ins):
""" Translates IN to asm.
"""
output = _16bit_oper(ins.quad[1])
output.append('ld b, h')
output.append('ld c, l')
output.append('in a, (c)')
output.append('push af')
return output | python | {
"resource": ""
} |
q3486 | _jzerostr | train | def _jzerostr(ins):
""" Jumps if top of the stack contains a NULL pointer
or its len is Zero
"""
output = []
disposable = False # True if string must be freed from memory
if ins.quad[1][0] == '_': # Variable?
output.append('ld hl, (%s)' % ins.quad[1][0])
else:
output.a... | python | {
"resource": ""
} |
q3487 | _param32 | train | def _param32(ins):
""" Pushes 32bit param into the stack
"""
output = _32bit_oper(ins.quad[1])
output.append('push de')
output.append('push hl')
return output | python | {
"resource": ""
} |
q3488 | _paramf16 | train | def _paramf16(ins):
""" Pushes 32bit fixed point param into the stack
"""
output = _f16_oper(ins.quad[1])
output.append('push de')
output.append('push hl')
return output | python | {
"resource": ""
} |
q3489 | _memcopy | train | def _memcopy(ins):
""" Copies a block of memory from param 2 addr
to param 1 addr.
"""
output = _16bit_oper(ins.quad[3])
output.append('ld b, h')
output.append('ld c, l')
output.extend(_16bit_oper(ins.quad[1], ins.quad[2], reversed=True))
output.append('ldir') # ***
return output | python | {
"resource": ""
} |
q3490 | Lexer.include_end | train | def include_end(self):
""" Performs and end of include.
"""
self.lex = self.filestack[-1][2]
self.input_data = self.filestack[-1][3]
self.filestack.pop()
if not self.filestack: # End of input?
return
self.filestack[-1][1] += 1 # Increment line coun... | python | {
"resource": ""
} |
q3491 | getDEHL | train | def getDEHL(duration, pitch):
"""Converts duration,pitch to a pair of unsigned 16 bit integers,
to be loaded in DE,HL, following the ROM listing.
Returns a t-uple with the DE, HL values.
"""
intPitch = int(pitch)
fractPitch = pitch - intPitch # Gets fractional part
tmp = 1 + 0.0577622606 * ... | python | {
"resource": ""
} |
q3492 | SymbolBLOCK.make_node | train | def make_node(cls, *args):
""" Creates a chain of code blocks.
"""
new_args = []
args = [x for x in args if not is_null(x)]
for x in args:
assert isinstance(x, Symbol)
if x.token == 'BLOCK':
new_args.extend(SymbolBLOCK.make_node(*x.childre... | python | {
"resource": ""
} |
q3493 | is_label | train | def is_label(token):
""" Return whether the token is a label (an integer number or id
at the beginning of a line.
To do so, we compute find_column() and moves back to the beginning
of the line if previous chars are spaces or tabs. If column 0 is
reached, it's a label.
"""
if not LABELS_ALLO... | python | {
"resource": ""
} |
q3494 | _get_val | train | def _get_val(other):
""" Given a Number, a Numeric Constant or a python number return its value
"""
assert isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST))
if isinstance(other, SymbolNUMBER):
return other.value
if isinstance(other, SymbolCONST):
return other.expr.value... | python | {
"resource": ""
} |
q3495 | ID.__dumptable | train | def __dumptable(self, table):
""" Dumps table on screen
for debugging purposes
"""
for x in table.table.keys():
sys.stdout.write("{0}\t<--- {1} {2}".format(x, table[x], type(table[x])))
if isinstance(table[x], ID):
sys.stdout(" {0}".format(table[x]... | python | {
"resource": ""
} |
q3496 | SymbolVARARRAY.count | train | def count(self):
""" Total number of array cells
"""
return functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds)) | python | {
"resource": ""
} |
q3497 | SymbolVARARRAY.memsize | train | def memsize(self):
""" Total array cell + indexes size
"""
return self.size + 1 + TYPE.size(gl.BOUND_TYPE) * len(self.bounds) | python | {
"resource": ""
} |
q3498 | SymbolTYPECAST.make_node | train | def make_node(cls, new_type, node, lineno):
""" Creates a node containing the type cast of
the given one. If new_type == node.type, then
nothing is done, and the same node is
returned.
Returns None on failure (and calls syntax_error)
"""
assert isinstance(new_typ... | python | {
"resource": ""
} |
q3499 | assemble | train | def assemble(input_):
""" Assembles input string, and leave the result in the
MEMORY global object
"""
global MEMORY
if MEMORY is None:
MEMORY = Memory()
parser.parse(input_, lexer=LEXER, debug=OPTIONS.Debug.value > 2)
if len(MEMORY.scopes):
error(MEMORY.scopes[-1], 'Missin... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.