INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return a new Streamlet by left join_streamlet with this streamlet | def outer_left_join(self, join_streamlet, window_config, join_function):
"""Return a new Streamlet by left join_streamlet with this streamlet
"""
from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt
join_streamlet_result = JoinStreamlet(JoinBolt.OUTER_LEFT, window_config,
... |
Return a new Streamlet by outer join_streamlet with this streamlet | def outer_join(self, join_streamlet, window_config, join_function):
"""Return a new Streamlet by outer join_streamlet with this streamlet
"""
from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt
join_streamlet_result = JoinStreamlet(JoinBolt.OUTER, window_config,
... |
Return a new Streamlet in which each ( key value ) pair of this Streamlet are collected over the time_window and then reduced using the reduce_function | def reduce_by_key_and_window(self, window_config, reduce_function):
"""Return a new Streamlet in which each (key, value) pair of this Streamlet are collected
over the time_window and then reduced using the reduce_function
"""
from heronpy.streamlet.impl.reducebykeyandwindowbolt import ReduceByKeyAndW... |
This is the method that s implemented by the operators to get the name of the Streamlet: return: The name of the operator | def _default_stage_name_calculator(self, prefix, existing_stage_names):
"""This is the method that's implemented by the operators to get the name of the Streamlet
:return: The name of the operator
"""
index = 1
calculated_name = ""
while True:
calculated_name = prefix + "-" + str(index)
... |
get method | def get(self):
""" get method """
clusters = self.get_arguments(constants.PARAM_CLUSTER)
environs = self.get_arguments(constants.PARAM_ENVIRON)
topology_names = self.get_arguments(constants.PARAM_TOPOLOGY)
ret = {}
if len(topology_names) > 1:
if not clusters:
message = "Missing a... |
Stream and handle the output of a process: param process: the process to stream the output for: param stream_fn: the function that applies handler to process: param handler: a function that will be called for each log line: return: None | def _async_stream_process_output(process, stream_fn, handler):
""" Stream and handle the output of a process
:param process: the process to stream the output for
:param stream_fn: the function that applies handler to process
:param handler: a function that will be called for each log line
:return: None
"""
... |
Get the topology jars: param dirname:: param pattern:: return: | def pick(dirname, pattern):
'''
Get the topology jars
:param dirname:
:param pattern:
:return:
'''
file_list = fnmatch.filter(os.listdir(dirname), pattern)
return file_list[0] if file_list else None |
get method | def get(self):
""" get method """
try:
cluster = self.get_argument_cluster()
role = self.get_argument_role()
environ = self.get_argument_environ()
topology_name = self.get_argument_topology()
component = self.get_argument_component()
metric_names = self.get_required_arguments... |
create parser | def create_parser():
""" create parser """
help_epilog = '''Getting more help:
heron-explorer help <command> Disply help and options for <command>\n
For detailed documentation, go to http://heronstreaming.io'''
parser = argparse.ArgumentParser(
prog='heron-explorer',
epilog=help_epilog,
... |
run command | def run(command, *args):
""" run command """
# show all clusters
if command == 'clusters':
return clusters.run(command, *args)
# show topologies
elif command == 'topologies':
return topologies.run(command, *args)
# physical plan
elif command == 'containers':
return physicalplan.run_container... |
extract common args | def extract_common_args(command, parser, cl_args):
""" extract common args """
try:
# do not pop like cli because ``topologies`` subcommand still needs it
cluster_role_env = cl_args['cluster/[role]/[env]']
config_path = cl_args['config_path']
except KeyError:
# if some of the arguments are not fou... |
main | def main(args):
""" main """
# create the argument parser
parser = create_parser()
# if no argument is provided, print help and exit
if not args:
parser.print_help()
return 0
# insert the boolean values for some of the options
all_args = parse.insert_bool_values(args)
# parse the args
args,... |
Parses command strings and returns a Popen - ready list. | def expand_args(command):
"""Parses command strings and returns a Popen-ready list."""
# Prepare arguments.
if isinstance(command, (str, unicode)):
splitter = shlex.shlex(command.encode('utf-8'))
splitter.whitespace = '|'
splitter.whitespace_split = True
command = []
... |
Executes a given commmand and returns Response. | def run(command, data=None, timeout=None, kill_timeout=None, env=None, cwd=None):
"""Executes a given commmand and returns Response.
Blocks until process is complete, or timeout is reached.
"""
command = expand_args(command)
history = []
for c in command:
if len(history):
... |
Spawns a new process from the given command. | def connect(command, data=None, env=None, cwd=None):
"""Spawns a new process from the given command."""
# TODO: support piped commands
command_str = expand_args(command).pop()
environ = dict(os.environ)
environ.update(env or {})
process = subprocess.Popen(command_str,
universal_newline... |
Sends a line to std_in. | def send(self, str, end='\n'):
"""Sends a line to std_in."""
return self._process.stdin.write(str+end) |
DOES NOT RETURN EMPTY STRINGS ( can only return empty bracket content if strip = True ) | def bracket_split(source, brackets=('()', '{}', '[]'), strip=False):
"""DOES NOT RETURN EMPTY STRINGS (can only return empty bracket content if strip=True)"""
starts = [e[0] for e in brackets]
in_bracket = 0
n = 0
last = 0
while n < len(source):
e = source[n]
if not in_bracket an... |
Converts Py type to PyJs type | def Js(val, Clamped=False):
'''Converts Py type to PyJs type'''
if isinstance(val, PyJs):
return val
elif val is None:
return undefined
elif isinstance(val, basestring):
return PyJsString(val, StringPrototype)
elif isinstance(val, bool):
return true if val else false
... |
a === b | def PyJsStrictEq(a, b):
'''a===b'''
tx, ty = Type(a), Type(b)
if tx != ty:
return false
if tx == 'Undefined' or tx == 'Null':
return true
if a.is_primitive(): #string bool and number case
return Js(a.value == b.value)
if a.Class == b.Class == 'PyObjectWrapper':
r... |
Just like in js: self. prop op = val for example when op is + it will be self. prop + = val op can be either None for simple assignment or one of: */ % + - << >> & ^ | | def put(self, prop, val, op=None): #external use!
'''Just like in js: self.prop op= val
for example when op is '+' it will be self.prop+=val
op can be either None for simple assignment or one of:
* / % + - << >> & ^ |'''
if self.Class == 'Undefined' or self.Class == 'Nu... |
self<other if self_first else other<self. Returns the result of the question: is self smaller than other? in case self_first is false it returns the answer of: is other smaller than self. result is PyJs type: bool or undefined | def abstract_relational_comparison(self, other, self_first=True):
''' self<other if self_first else other<self.
Returns the result of the question: is self smaller than other?
in case self_first is false it returns the answer of:
is other smal... |
returns the result of JS == compare. result is PyJs type: bool | def abstract_equality_comparison(self, other):
''' returns the result of JS == compare.
result is PyJs type: bool'''
tx, ty = self.TYPE, other.TYPE
if tx == ty:
if tx == 'Undefined' or tx == 'Null':
return true
if tx == 'Number' or tx == 'String... |
Call a property prop as a method ( this will be self ). | def callprop(self, prop, *args):
'''Call a property prop as a method (this will be self).
NOTE: dont pass this and arguments here, these will be added
automatically!'''
if not isinstance(prop, basestring):
prop = prop.to_string().value
cand = self.get(prop)
i... |
name is py type | def _set_name(self, name):
'''name is py type'''
if self.own.get('name'):
self.func_name = name
self.own['name']['value'] = Js(name) |
Calls this function and returns a result ( converted to PyJs type so func can return python types ) | def call(self, this, args=()):
'''Calls this function and returns a result
(converted to PyJs type so func can return python types)
this must be a PyJs object and args must be a python tuple of PyJs objects.
arguments object is passed automatically and will be equal to Js(args)
... |
removes functions and returns new source and 2 dicts. first dict with removed hoisted ( global ) functions and second with replaced inline functions | def remove_functions(source, all_inline=False):
"""removes functions and returns new source, and 2 dicts.
first dict with removed hoisted(global) functions and second with replaced inline functions"""
global INLINE_COUNT
inline = {}
hoisted = {}
n = 0
limit = len(source) - 9 # 8 is leng... |
note py_arr elems are NOT converted to PyJs types! | def ConstructArray(self, py_arr):
''' note py_arr elems are NOT converted to PyJs types!'''
arr = self.NewArray(len(py_arr))
arr._init(py_arr)
return arr |
note py_obj items are NOT converted to PyJs types! | def ConstructObject(self, py_obj):
''' note py_obj items are NOT converted to PyJs types! '''
obj = self.NewObject()
for k, v in py_obj.items():
obj.put(unicode(k), v)
return obj |
Adds op_code with specified args to tape | def emit(self, op_code, *args):
''' Adds op_code with specified args to tape '''
self.tape.append(OP_CODES[op_code](*args)) |
Records locations of labels and compiles the code | def compile(self, start_loc=0):
''' Records locations of labels and compiles the code '''
self.label_locs = {} if self.label_locs is None else self.label_locs
loc = start_loc
while loc < len(self.tape):
if type(self.tape[loc]) == LABEL:
self.label_locs[self.ta... |
Calls a bytecode function func NOTE: use !ONLY! when calling functions from native methods! | def _call(self, func, this, args):
''' Calls a bytecode function func
NOTE: use !ONLY! when calling functions from native methods! '''
assert not func.is_native
# fake call - the the runner to return to the end of the file
old_contexts = self.contexts
old_return_locs... |
just like run but returns if moved outside of the specified fragment # 4 different exectution results # 0 = normal 1 = return 2 = jump_outside 3 = errors # execute_fragment_under_context returns: # ( return_value typ return_value/ jump_loc/ py_error ) # IMPARTANT: It is guaranteed that the length of the ctx. stack is u... | def execute_fragment_under_context(self, ctx, start_label, end_label):
''' just like run but returns if moved outside of the specified fragment
# 4 different exectution results
# 0=normal, 1=return, 2=jump_outside, 3=errors
# execute_fragment_under_context returns:
... |
returns n digit string representation of the num | def pad(num, n=2, sign=False):
'''returns n digit string representation of the num'''
s = unicode(abs(num))
if len(s) < n:
s = '0' * (n - len(s)) + s
if not sign:
return s
if num >= 0:
return '+' + s
else:
return '-' + s |
Takes the replacement template and some info about the match and returns filled template | def replacement_template(rep, source, span, npar):
"""Takes the replacement template and some info about the match and returns filled template
"""
n = 0
res = ''
while n < len(rep) - 1:
char = rep[n]
if char == '$':
if rep[n + 1] == '$':
res += '$'
... |
Use this function when unsure whether func takes this and arguments as its last 2 args. It will append 2 args if it does not. | def fix_js_args(func):
'''Use this function when unsure whether func takes this and arguments as its last 2 args.
It will append 2 args if it does not.'''
fcode = six.get_function_code(func)
fargs = fcode.co_varnames[fcode.co_argcount - 2:fcode.co_argcount]
if fargs == ('this', 'arguments') or fa... |
what can be either name of the op or node or a list of statements. | def emit(self, what, *args):
''' what can be either name of the op, or node, or a list of statements.'''
if isinstance(what, basestring):
return self.exe.emit(what, *args)
elif isinstance(what, list):
self._emit_statement_list(what)
else:
return getatt... |
returns string representation of this object | def to_key(literal_or_identifier):
''' returns string representation of this object'''
if literal_or_identifier['type'] == 'Identifier':
return literal_or_identifier['name']
elif literal_or_identifier['type'] == 'Literal':
k = literal_or_identifier['value']
if isinstance(k, float):
... |
Translates esprima syntax tree to python by delegating to appropriate translating node | def trans(ele, standard=False):
"""Translates esprima syntax tree to python by delegating to appropriate translating node"""
try:
node = globals().get(ele['type'])
if not node:
raise NotImplementedError('%s is not supported!' % ele['type'])
if standard:
node = nod... |
Decorator limiting resulting line length in order to avoid python parser stack overflow - If expression longer than LINE_LEN_LIMIT characters then it will be moved to upper line USE ONLY ON EXPRESSIONS!!! | def limited(func):
'''Decorator limiting resulting line length in order to avoid python parser stack overflow -
If expression longer than LINE_LEN_LIMIT characters then it will be moved to upper line
USE ONLY ON EXPRESSIONS!!! '''
def f(standard=False, **args):
insert_pos = len(
... |
Does not chceck whether t is not resticted or internal | def is_lval(t):
"""Does not chceck whether t is not resticted or internal"""
if not t:
return False
i = iter(t)
if i.next() not in IDENTIFIER_START:
return False
return all(e in IDENTIFIER_PART for e in i) |
Checks whether t is valid JS identifier name ( no keyword like var function if etc ) Also returns false on internal | def is_valid_lval(t):
"""Checks whether t is valid JS identifier name (no keyword like var, function, if etc)
Also returns false on internal"""
if not is_internal(t) and is_lval(t) and t not in RESERVED_NAMES:
return True
return False |
js has to be a javascript source code. returns equivalent python code. | def translate_js(js, HEADER=DEFAULT_HEADER, use_compilation_plan=False):
"""js has to be a javascript source code.
returns equivalent python code."""
if use_compilation_plan and not '//' in js and not '/*' in js:
return translate_js_with_compilation_plan(js, HEADER=HEADER)
parser = pyjsparser... |
js has to be a javascript source code. returns equivalent python code. | def translate_js_with_compilation_plan(js, HEADER=DEFAULT_HEADER):
"""js has to be a javascript source code.
returns equivalent python code.
compile plans only work with the following restrictions:
- only enabled for oneliner expressions
- when there are comments in the js code string s... |
Imports from javascript source file. globals is your globals () | def import_js(path, lib_name, globals):
"""Imports from javascript source file.
globals is your globals()"""
with codecs.open(path_as_local(path), "r", "utf-8") as f:
js = f.read()
e = EvalJs()
e.execute(js)
var = e.context['var']
globals[lib_name] = var.to_python() |
Translates input JS file to python and saves the it to the output path. It appends some convenience code at the end so that it is easy to import JS objects. | def translate_file(input_path, output_path):
'''
Translates input JS file to python and saves the it to the output path.
It appends some convenience code at the end so that it is easy to import JS objects.
For example we have a file 'example.js' with: var a = function(x) {return x}
translate_file... |
Context must be EvalJS object. Runs given path as a JS program. Returns ( eval_value context ). | def run_file(path_or_file, context=None):
''' Context must be EvalJS object. Runs given path as a JS program. Returns (eval_value, context).
'''
if context is None:
context = EvalJs()
if not isinstance(context, EvalJs):
raise TypeError('context must be the instance of EvalJs')
eval_v... |
executes javascript js in current context | def execute(self, js=None, use_compilation_plan=False):
"""executes javascript js in current context
During initial execute() the converted js is cached for re-use. That means next time you
run the same javascript snippet you save many instructions needed to parse and convert the
js cod... |
evaluates expression in current context and returns its value | def eval(self, expression, use_compilation_plan=False):
"""evaluates expression in current context and returns its value"""
code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression)
self.execute(code, use_compilation_plan=use_compilation_plan)
return self['PyJsEvalResult'] |
executes javascript js in current context as opposed to the ( faster ) self. execute method you can use your regular debugger to set breakpoints and inspect the generated python code | def execute_debug(self, js):
"""executes javascript js in current context
as opposed to the (faster) self.execute method, you can use your regular debugger
to set breakpoints and inspect the generated python code
"""
code = translate_js(js, '')
# make sure you have a temp... |
evaluates expression in current context and returns its value as opposed to the ( faster ) self. execute method you can use your regular debugger to set breakpoints and inspect the generated python code | def eval_debug(self, expression):
"""evaluates expression in current context and returns its value
as opposed to the (faster) self.execute method, you can use your regular debugger
to set breakpoints and inspect the generated python code
"""
code = 'PyJsEvalResult = eval(%s)' % j... |
starts to interact ( starts interactive console ) Something like code. InteractiveConsole | def console(self):
"""starts to interact (starts interactive console) Something like code.InteractiveConsole"""
while True:
if six.PY2:
code = raw_input('>>> ')
else:
code = input('>>>')
try:
print(self.eval(code))
... |
returns string representation of this object | def to_key(literal_or_identifier):
''' returns string representation of this object'''
if literal_or_identifier['type'] == 'Identifier':
return literal_or_identifier['name']
elif literal_or_identifier['type'] == 'Literal':
k = literal_or_identifier['value']
if isinstance(k, float):
... |
js has to be a javascript source code. returns equivalent python code. | def translate_js(js, top=TOP_GLOBAL):
"""js has to be a javascript source code.
returns equivalent python code."""
# Remove constant literals
no_const, constants = remove_constants(js)
#print 'const count', len(constants)
# Remove object literals
no_obj, objects, obj_count = remove_object... |
Translates functions and all nested functions to Python code. name - name of that function ( global functions will be available under var while inline will be available directly under this name ) block - code of the function ( * with * brackets {} ) args - arguments that this function takes | def translate_func(name, block, args):
"""Translates functions and all nested functions to Python code.
name - name of that function (global functions will be available under var while
inline will be available directly under this name )
block - code of the function (*with* brackets {} )
... |
Returns content of brackets with brackets and first pos after brackets if source [ start ] is followed by some optional white space and brackets. Otherwise None | def pass_bracket(source, start, bracket='()'):
"""Returns content of brackets with brackets and first pos after brackets
if source[start] is followed by some optional white space and brackets.
Otherwise None"""
e = bracket_split(source[start:], [bracket], False)
try:
cand = e.next()
ex... |
Token can be only a single char. Returns position after token if found. Otherwise raises syntax error if throw otherwise returns None | def except_token(source, start, token, throw=True):
"""Token can be only a single char. Returns position after token if found. Otherwise raises syntax error if throw
otherwise returns None"""
start = pass_white(source, start)
if start < len(source) and source[start] == token:
return start + 1
... |
Returns position after keyword if found else None Note: skips white space | def except_keyword(source, start, keyword):
""" Returns position after keyword if found else None
Note: skips white space"""
start = pass_white(source, start)
kl = len(keyword) #keyword len
if kl + start > len(source):
return None
if source[start:start + kl] != keyword:
retu... |
passes white space from start and returns first identifier if identifier invalid and throw raises SyntaxError otherwise returns None | def parse_identifier(source, start, throw=True):
"""passes white space from start and returns first identifier,
if identifier invalid and throw raises SyntaxError otherwise returns None"""
start = pass_white(source, start)
end = start
if not end < len(source):
if throw:
raise ... |
used to split JS args ( it is not that simple as it seems because sep can be inside brackets ). | def argsplit(args, sep=','):
"""used to split JS args (it is not that simple as it seems because
sep can be inside brackets).
pass args *without* brackets!
Used also to parse array and object elements, and more"""
parsed_len = 0
last = 0
splits = []
for e in bracket_split(args... |
Specialized function splitting text at add/ sub operators. Operands are * not * translated. Example result [ op1 + op2 - op3 ] | def split_add_ops(text):
"""Specialized function splitting text at add/sub operators.
Operands are *not* translated. Example result ['op1', '+', 'op2', '-', 'op3']"""
n = 0
text = text.replace('++', '##').replace(
'--', '@@') #text does not normally contain any of these
spotted = False # s... |
doc | def split_at_any(text,
lis,
translate=False,
not_before=[],
not_after=[],
validitate=None):
""" doc """
lis.sort(key=lambda x: len(x), reverse=True)
last = 0
n = 0
text_len = len(text)
while n < text_len:
... |
Works like text. split ( sep ) but separated fragments cant end with not_before or start with not_after | def split_at_single(text, sep, not_before=[], not_after=[]):
"""Works like text.split(sep) but separated fragments
cant end with not_before or start with not_after"""
n = 0
lt, s = len(text), len(sep)
last = 0
while n < lt:
if not s + n > lt:
if sep == text[n:n + s]:
... |
Returns Python array from Js array | def to_arr(this):
"""Returns Python array from Js array"""
return [this.get(str(e)) for e in xrange(len(this))] |
Transforms this ?: crap into if else python syntax | def transform_crap(code): #needs some more tests
"""Transforms this ?: crap into if else python syntax"""
ind = code.rfind('?')
if ind == -1:
return code
sep = code.find(':', ind)
if sep == -1:
raise SyntaxError('Invalid ?: syntax (probably missing ":" )')
beg = max(code.rfind('... |
performs this operation on a list from * right to left * op must take 2 args a b c = > op ( a op ( b c )) | def rl(self, lis, op):
"""performs this operation on a list from *right to left*
op must take 2 args
a,b,c => op(a, op(b, c))"""
it = reversed(lis)
res = trans(it.next())
for e in it:
e = trans(e)
res = op(e, res)
return res |
performs this operation on a list from * left to right * op must take 2 args a b c = > op ( op ( a b ) c ) | def lr(self, lis, op):
"""performs this operation on a list from *left to right*
op must take 2 args
a,b,c => op(op(a, b), c)"""
it = iter(lis)
res = trans(it.next())
for e in it:
e = trans(e)
res = op(res, e)
return res |
Translates outer operation and calls translate on inner operation. Returns fully translated code. | def translate(self):
"""Translates outer operation and calls translate on inner operation.
Returns fully translated code."""
if not self.code:
return ''
new = bracket_replace(self.code)
#Check comma operator:
cand = new.split(',') #every comma in new must ... |
returns none if not found other functions that begin with do_ raise also this do_ type function passes white space | def do_statement(source, start):
"""returns none if not found other functions that begin with 'do_' raise
also this do_ type function passes white space"""
start = pass_white(source, start)
# start is the fist position after initial start that is not a white space or \n
if not start < len(source): ... |
string is of course a py string | def match(self, string, pos):
'''string is of course a py string'''
return self.pat.match(string, int(pos)) |
Dont use this method from inside bytecode to call other bytecode. | def call(self, this, args=()):
''' Dont use this method from inside bytecode to call other bytecode. '''
if self.is_native:
_args = SpaceTuple(
args
) # we have to do that unfortunately to pass all the necessary info to the funcs
_args.space = self.sp... |
n may be the inside of block or object | def is_empty_object(n, last):
"""n may be the inside of block or object"""
if n.strip():
return False
# seems to be but can be empty code
last = last.strip()
markers = {
')',
';',
}
if not last or last[-1] in markers:
return False
return True |
n may be the inside of block or object. last is the code before object | def is_object(n, last):
"""n may be the inside of block or object.
last is the code before object"""
if is_empty_object(n, last):
return True
if not n.strip():
return False
#Object contains lines of code so it cant be an object
if len(argsplit(n, ';')) > 1:
return Fals... |
This function replaces objects with OBJECTS_LVALS returns new code replacement dict and count. count arg is the number that should be added to the LVAL of the first replaced object | def remove_objects(code, count=1):
""" This function replaces objects with OBJECTS_LVALS, returns new code, replacement dict and count.
count arg is the number that should be added to the LVAL of the first replaced object
"""
replacements = {} #replacement dict
br = bracket_split(code, ['{}', '... |
removes arrays and replaces them with ARRAY_LVALS returns new code and replacement dict * NOTE * has to be called AFTER remove objects | def remove_arrays(code, count=1):
"""removes arrays and replaces them with ARRAY_LVALS
returns new code and replacement dict
*NOTE* has to be called AFTER remove objects"""
res = ''
last = ''
replacements = {}
for e in bracket_split(code, ['[]']):
if e[0] == '[':
if... |
array has to be any js array for example [ 1 2 3 ] lval has to be name of this array. Returns python code that adds lval to the PY scope it should be put before lval | def translate_array(array, lval, obj_count=1, arr_count=1):
"""array has to be any js array for example [1,2,3]
lval has to be name of this array.
Returns python code that adds lval to the PY scope it should be put before lval"""
array = array[1:-1]
array, obj_rep, obj_count = remove_objects(a... |
returns True if regexp starts at n else returns False checks whether it is not a division | def _ensure_regexp(source, n): #<- this function has to be improved
'''returns True if regexp starts at n else returns False
checks whether it is not a division '''
markers = '(+~"\'=[%:?!*^|&-,;/\\'
k = 0
while True:
k += 1
if n - k < 0:
return True
char = sou... |
Returns a first index > = start of chat not in charset | def parse_num(source, start, charset):
"""Returns a first index>=start of chat not in charset"""
while start < len(source) and source[start] in charset:
start += 1
return start |
returns end of exponential raises SyntaxError if failed | def parse_exponent(source, start):
"""returns end of exponential, raises SyntaxError if failed"""
if not source[start] in {'e', 'E'}:
if source[start] in IDENTIFIER_PART:
raise SyntaxError('Invalid number literal!')
return start
start += 1
if source[start] in {'-', '+'}:
... |
Replaces Strings and Regexp literals in the source code with identifiers and * removes comments *. Identifier is of the format: | def remove_constants(source):
'''Replaces Strings and Regexp literals in the source code with
identifiers and *removes comments*. Identifier is of the format:
PyJsStringConst(String const number)_ - for Strings
PyJsRegExpConst(RegExp const number)_ - for RegExps
Returns dict which rela... |
Converts identifiers representing Js constants to the PyJs constants PyJsNumberConst_1_ which has the true value of 5 will be converted to PyJsNumber ( 5 ) | def recover_constants(py_source,
replacements): #now has n^2 complexity. improve to n
'''Converts identifiers representing Js constants to the PyJs constants
PyJsNumberConst_1_ which has the true value of 5 will be converted to PyJsNumber(5)'''
for identifier, value in replacements.it... |
this function parses the string just like javascript for example literal \ d in JavaScript would be interpreted as d - backslash would be ignored and in Pyhon this would be interpreted as \\ d This function fixes this problem. | def unify_string_literals(js_string):
"""this function parses the string just like javascript
for example literal '\d' in JavaScript would be interpreted
as 'd' - backslash would be ignored and in Pyhon this
would be interpreted as '\\d' This function fixes this problem."""
n = 0
res = ... |
Its actually quite complicated to cover every case: ) http:// www. javascriptkit. com/ jsref/ escapesequence. shtml | def do_escape(source, n):
"""Its actually quite complicated to cover every case :)
http://www.javascriptkit.com/jsref/escapesequence.shtml"""
if not n + 1 < len(source):
return '' # not possible here but can be possible in general case.
if source[n + 1] in LINE_TERMINATOR:
if source[... |
self<other if self_first else other<self. Returns the result of the question: is self smaller than other? in case self_first is false it returns the answer of: is other smaller than self. result is PyJs type: bool or undefined | def abstract_relational_comparison(self, other,
self_first=True): # todo speed up!
''' self<other if self_first else other<self.
Returns the result of the question: is self smaller than other?
in case self_first is false it returns the answer of:
... |
returns the result of JS == compare. result is PyJs type: bool | def abstract_equality_op(self, other):
''' returns the result of JS == compare.
result is PyJs type: bool'''
tx, ty = Type(self), Type(other)
if tx == ty:
if tx == 'Undefined' or tx == 'Null':
return True
if tx == 'Number' or tx == 'String' or tx == 'Boolean':
... |
checks if self is in other | def in_op(self, other):
'''checks if self is in other'''
if not is_object(other):
raise MakeError(
'TypeError',
"You can\'t use 'in' operator to search in non-objects")
return other.has_property(to_string(self)) |
Download and extract processed data and embeddings. | def maybe_download_and_extract():
"""Download and extract processed data and embeddings."""
dest_directory = '.'
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> ... |
Make a network graph represented as of nodes and a set of edges. The nodes are represented as tuples: ( name: string input_dim: Dim label: string output_dim: Dim children: set [ name ] features: string ) # The edges are represented as dict of children to sets of parents: ( child: string ) - > [ ( parent: string feature... | def make_network_graph(compact, expression_names, lookup_names):
"""
Make a network graph, represented as of nodes and a set of edges.
The nodes are represented as tuples: (name: string, input_dim: Dim, label: string, output_dim: Dim, children: set[name], features: string)
# The edges are represented as dict ... |
returns the list of state pairs ( stateF stateB ) obtained by adding inputs to both forward ( stateF ) and backward ( stateB ) RNNs. | def add_inputs(self, es):
"""
returns the list of state pairs (stateF, stateB) obtained by adding
inputs to both forward (stateF) and backward (stateB) RNNs.
@param es: a list of Expression
see also transduce(xs)
.transduce(xs) is different from .add_inputs(xs) in t... |
returns the list of output Expressions obtained by adding the given inputs to the current state one by one to both the forward and backward RNNs and concatenating. @param es: a list of Expression | def transduce(self, es):
"""
returns the list of output Expressions obtained by adding the given inputs
to the current state, one by one, to both the forward and backward RNNs,
and concatenating.
@param es: a list of Expression
see also add_inputs(xs)
... |
returns the list of states obtained by adding the given inputs to the current state one by one. | def add_inputs(self, xs):
"""
returns the list of states obtained by adding the given inputs
to the current state, one by one.
"""
states = []
cur = self
for x in xs:
cur = cur.add_input(x)
states.append(cur)
return states |
wget - O - http:// yann. lecun. com/ exdb/ mnist/ train - images - idx3 - ubyte. gz | gunzip > train - images - idx3 - ubyte wget - O - http:// yann. lecun. com/ exdb/ mnist/ train - labels - idx1 - ubyte. gz | gunzip > train - labels - idx1 - ubyte wget - O - http:// yann. lecun. com/ exdb/ mnist/ t10k - images - idx3... | def load_mnist(dataset, path):
"""
wget -O - http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz | gunzip > train-images-idx3-ubyte
wget -O - http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz | gunzip > train-labels-idx1-ubyte
wget -O - http://yann.lecun.com/exdb/mnist/t10k-images-idx3... |
Make a grid of images via numpy. | def make_grid(tensor, nrow=8, padding=2, pad_value=0):
"""Make a grid of images, via numpy.
Args:
tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)
or a list of images all of the same size.
nrow (int, optional): Number of images displayed in each row of the grid... |
Save a given Tensor into an image file. | def save_image(tensor, filename, nrow=8, padding=2, pad_value=0):
"""Save a given Tensor into an image file.
Args:
tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,
saves the tensor as a grid of images by calling ``make_grid``.
**kwargs: Other arguments are d... |
Remove types from function arguments in cython | def pythonize_arguments(arg_str):
"""
Remove types from function arguments in cython
"""
out_args = []
# If there aren't any arguments return the empty string
if arg_str is None:
return out_str
args = arg_str.split(',')
for arg in args:
components = arg.split('=')
... |
Communicate with the child process without closing stdin. | def correspond(text):
"""Communicate with the child process without closing stdin."""
if text:
subproc.stdin.write(text)
subproc.stdin.flush()
return get_lines() |
Convert a byte - like value into a canonical byte ( a value of type bytes of len 1 ) | def _normalize(c):
"""
Convert a byte-like value into a canonical byte (a value of type 'bytes' of len 1)
:param c:
:return:
"""
if isinstance(c, int):
return bytes([c])
elif isinstance(c, str):
return bytes([ord(c)])
else:
return c |
Sets the access permissions of the map. | def _set_perms(self, perms):
"""
Sets the access permissions of the map.
:param perms: the new permissions.
"""
assert isinstance(perms, str) and len(perms) <= 3 and perms.strip() in ['', 'r', 'w', 'x', 'rw', 'r x', 'rx', 'rwx', 'wx', ]
self._perms = perms |
Check if there is enough permissions for access | def access_ok(self, access):
""" Check if there is enough permissions for access """
for c in access:
if c not in self.perms:
return False
return True |
Returns True if index is in range | def _in_range(self, index):
""" Returns True if index is in range """
if isinstance(index, slice):
in_range = index.start < index.stop and \
index.start >= self.start and \
index.stop <= self.end
else:
in_range = index >= self.start and \
... |
Translates the index to the internal offsets. | def _get_offset(self, index):
"""
Translates the index to the internal offsets.
self.start -> 0
self.start+1 -> 1
...
self.end -> len(self)
"""
if not self._in_range(index):
raise IndexError('Map index out of range')
if isinstanc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.