def make_global_scope(self, initial_scope=None): if initial_scope is None: initial_scope = {} initial_scope['$_SERVER']=phparray.PHPArray( ('SCRIPT_NAME', self.filename) ) return scope(initial_scope, {'%executer':self}, phpbuiltins.builtins, name='global')
def call(args): scope = scope.scope(self.proto) for name, value in zip(self.args): scope.set(name, value) for line in self.lines: Eval(line)
def make_global_scope(self, initial_scope=None): if initial_scope is None: initial_scope = {} initial_scope['$_SERVER'] = phparray.PHPArray( ('SCRIPT_NAME', self.filename)) return scope(initial_scope, {'%executer': self}, phpbuiltins.builtins, name='global')
def __init__(self, options): gr.top_block.__init__(self) if options.freq is not None: u = usrp2.source(options) elif options.infile is not None: u = gr.file_source(gr.sizeof_gr_complex, options.infile) else: import sys sys.stderr.write("--freq or --infile must be specified\n") raise SystemExit self.scope = None if options.outfile is not None: rx = gr.file_sink(gr.sizeof_gr_complex, options.outfile) else: rx = qam_rxtx.RX(options) framebytes = rx.framebytes if options.rxdata is not None: if options.rxdata == '-': self.connect( rx, gr.file_descriptor_sink(gr.sizeof_char * framebytes, 1)) else: self.connect( rx, gr.file_sink(gr.sizeof_char * framebytes, options.rxdata)) if options.berdata is not None: # select one of the ber modes ber = qam_rxtx.BER(framebytes, 100, mode=options.bermode) data = qam_rxtx.make_data(framebytes) self.connect(rx, (ber, 0)) self.connect(data, (ber, 1)) if options.berdata == '-': # print it out msgq = gr.msg_queue(16) self.connect(ber, gr.message_sink(gr.sizeof_float, msgq, True)) self.watcher = ofdm_rxtx.queue_watcher(msgq) elif options.berdata == '.': import scope # scope it out self.scope = scope.scope(self, ber, 'Frame BER') else: self.connect( ber, gr.file_sink(gr.sizeof_float, options.berdata)) else: pass #self.connect(rx, gr.null_sink(symbol_size)) # XXX do we still need this? self.connect(u, rx)
def make_global_scope(self, initial_scope=None): if initial_scope is None: initial_scope = {} global_scope = { '$_SERVER' : phparray.PHPArray( ('SCRIPT_NAME', self.filename) ), '$_GET' : phparray.PHPArray(), '$_POST' : phparray.PHPArray(), '$_FILES' : phparray.PHPArray() } global_scope.update(initial_scope) return scope(global_scope, {'%executer':self}, phpbuiltins.builtins, name='global')
def exec_classdef(self, node, local): print "%"*100 cls_name, scls_name, body = node.children if scls_name and not scls_name[1] in local: raise ExecuteError("Undefined superclass %s"%scls_name[1]) class_context = scope({}, local, name=cls_name[1]) if body: body = self.visit(body, class_context) defined_class = phpclass.PHPClass(cls_name[1], local[scls_name[1]] if scls_name else None, body, class_context, filename=node.filename, line_num=node.line_num) #print "class %s defined"%defined_class #print "%"*100 self.globals[defined_class.name] = defined_class return defined_class
def __call__(self, *args, **kwargs): if 'context' in kwargs: context = kwargs['context'] else: context = self.context caller_filename = kwargs['filename'] if 'filename' in kwargs else None caller_line_num = kwargs['line_num'] if 'line_num' in kwargs else None # print "Calling %r with %r"%(self, args) call_context = scope({ '%func_args' : args, '__FUNCTION__' : self.name }, self.context, name='fncall') executer = call_context['%executer'] arglen = len(args) for i, par in enumerate(self.params): # print '\n\n==\n', par, '\n==\n' if i < arglen: val = args[i] elif len(par) > 2: val = par[2] else: val = None executer.report_error( constants.E_WARNING, "Missing argument %d for %s()%s defined in %s on line %d"%(i+1, self.name, ', called in %s on line %d and'%(caller_filename, caller_line_num) if caller_filename is not None and caller_line_num is not None else '', self.filename, self.line_num) # "Warning: Missing argument 2 for f(), called in /Users/giovanyvega/langdev/php/test/err_func_missing_arg.php on line 7 and defined in /Users/giovanyvega/langdev/php/test/err_func_missing_arg.php on line 3" ) # raise errors.ExecuteError("Missing required argument %d for %r"%(i, self)) call_context[par[1]] = val if self.name == 'library': print ('='*20 +'\n')*5 print self.body.prepr() print ('='*20 +'\n')*5 # print executer # print self.body # print call_context try: return executer.visit(self.body, call_context) except errors.ReturnError, rerr: return rerr.retval
def handle_sql(exp): """Function to handle one input S-expression. This prepares the expression, then prints the memo and expression tree. """ # Compile the expression. m = memo() m.root = analyze_select(m, scope(None), exp) # Print the results. print("memo after analysis:") print(m) print("expression tree:") print_tree(m)
def __init__(self, options): gr.top_block.__init__(self) if options.freq is not None: u = usrp2.source(options) elif options.infile is not None: u = gr.file_source(gr.sizeof_gr_complex, options.infile) else: import sys sys.stderr.write("--freq or --infile must be specified\n") raise SystemExit self.scope = None if options.outfile is not None: rx = gr.file_sink(gr.sizeof_gr_complex, options.outfile) else: rx = qam_rxtx.RX(options) framebytes = rx.framebytes if options.rxdata is not None: if options.rxdata == '-': self.connect(rx, gr.file_descriptor_sink(gr.sizeof_char * framebytes, 1)) else: self.connect(rx, gr.file_sink(gr.sizeof_char * framebytes, options.rxdata)) if options.berdata is not None: # select one of the ber modes ber = qam_rxtx.BER(framebytes, 100, mode=options.bermode) data = qam_rxtx.make_data(framebytes) self.connect(rx, (ber,0)) self.connect(data, (ber,1)) if options.berdata == '-': # print it out msgq = gr.msg_queue(16) self.connect(ber, gr.message_sink(gr.sizeof_float, msgq, True)) self.watcher = ofdm_rxtx.queue_watcher(msgq) elif options.berdata == '.': import scope # scope it out self.scope = scope.scope(self, ber, 'Frame BER') else: self.connect(ber, gr.file_sink(gr.sizeof_float, options.berdata)) else: pass #self.connect(rx, gr.null_sink(symbol_size)) # XXX do we still need this? self.connect(u, rx)
import os import torch from network import * from scope import scope from optim import Optim from torchvision import datasets, transforms with scope("Variables Definition"): batch_size = 100 traning_ratio = 1 device = torch.device('cuda:0' if torch.cuda.is_available() else "cpu") with scope("Data Loader"): loader = {} for stage in ("train", "test"): more = dict(num_workers=1, pin_memory=True) if torch.cuda.is_available() else {} mnist = datasets.MNIST(os.curdir, train=stage == "train", download=True, transform=transforms.ToTensor()) loader[stage] = torch.utils.data.DataLoader(mnist, batch_size=batch_size, shuffle=stage == "train", **more) with scope("Models Construction"): G = Generator() D = Discriminator() with scope("Optimizer Builder"):
class Commands: git_call = 'git' editor = 'vim' scope = scope() git_cmds = [ 'add', 'archive', 'branch', 'cat-file', 'checkout', 'clone', 'commit', 'config', 'diff', 'fetch', 'fsck', 'gc', 'grep', 'init', 'instaweb', 'log', 'ls-tree', 'merge', 'prune', 'pull', 'push', 'remote', 'reset', 'rm', 'show', 'stash', 'status', 'tag', ] def cd(self, line): system(self.git_call, 'checkout ' + line) def echo(self, line): print line def edit(self, line): system(editor, line) def git(self, line): system(self.git_call, line) def hist(self, line, history): print history.print_(line) def ls(self, line): system(self.git_call, 'status ' + line) def python(self, line, igitaInst): igitaInst.history.save() igitaInst.history.clear() code.interact(local={'igita': igitaInst}) igitaInst.history = init_history(igitaInst.history.handler) def set(self, line): match = line.strip().split() if len(match) % 2: print "Missing value for variable {}".format(match[-1]) return for i in range(0, len(match) - 1, 2): self.scope.set(match[i], match[i + 1]) def quit(self, history): history.save() quit()
def __init__(self, options): gr.top_block.__init__(self) if options.rx_freq is not None: u = uhd_receiver(options.args, options.bandwidth, options.rx_freq, options.rx_gain, options.spec, options.antenna, options.verbose) elif options.infile is not None: u = gr.file_source(gr.sizeof_gr_complex, options.infile) else: import sys sys.stderr.write("--freq or --infile must be specified\n") raise SystemExit self.scope = None if options.outfile is not None: rx = gr.file_sink(gr.sizeof_gr_complex, options.outfile) else: rx = ofdm_rxtx.RX(options) data_tones = rx.params.data_tones if options.rxdata is not None: if options.rxdata == '.': import scope # scope it out rxs = gr.vector_to_stream(gr.sizeof_gr_complex, data_tones) self.connect(rx, rxs) self.scope = scope.scope(self, rxs, 'Frame SNR', isComplex=True) else: if options.char > 0: # rail and scale self.connect( rx, gr.vector_to_stream(gr.sizeof_float, data_tones * 2), gr.multiply_const_ff(128.0 * (2**0.5) / options.char), gr.rail_ff(-128.0, 127.0), gr.float_to_char(), gr.file_sink(gr.sizeof_char, options.rxdata)) else: self.connect( rx, gr.file_sink(data_tones * gr.sizeof_gr_complex, options.rxdata)) if options.snrdata is not None: # select one of the snr modes snr = ofdm_rxtx.SNR(rx.params.data_tones, options.size, mode=options.snrmode) if options.char > 0: # NOTE: we use repeat, assuming the file is long enough or properly aligned data = gr.stream_to_vector(gr.sizeof_float, data_tones * 2) self.connect( gr.file_source(gr.sizeof_char, options.txdata, repeat=True), gr.char_to_float(), gr.multiply_const_ff(options.char * (2**-0.5) / 128.0), data) else: data = ofdm_rxtx.make_data(rx.params.data_tones, options.size, options.txdata) self.connect(rx, (snr, 0)) self.connect(data, (snr, 1)) if options.snrdata == '-': # print it out msgq = gr.msg_queue(16) self.connect(snr, gr.message_sink(gr.sizeof_float, msgq, True)) self.watcher = ofdm_rxtx.queue_watcher(msgq) elif options.snrdata == '.': import scope # scope it out self.scope = scope.scope(self, snr, 'Frame SNR') else: self.connect( snr, gr.file_sink(gr.sizeof_float, options.snrdata)) else: pass #self.connect(rx, gr.null_sink(symbol_size)) # XXX do we still need this? self.connect(u, rx)
def analyze_select(memo, env, exp): """Analyzes a SELECT relational expression and populates the memo accordingly. The argument are as follows: - memo: the memo to populate. - env: the current naming scope, used to resolve column references. - exp: the expression to analyze. Must have operator 'select'. The return value is the memo index of the top level node (class) that implements the expression. """ assert op(exp) == 'select' # Each SELECT clause starts a new naming scope: all the names # defined by the sources in its FROM clause do not leak in the # surrounding context -- only the names of the projected # expressions will be visible, as column labels in the resulting # memo class. here = scope(env) # The structure of a SELECT clause is always in the following order. # source in FROM clause -> WHERE (filter) -> grouping -> projection -> sorting -> limit. # Each stage is optional and has the previous one as child (source) in the tree. # Analyze FROM. if exp.args._from is not None: # Populate the memo with the data source(s). See below. srcidx = analyze_from(memo, here, exp.args._from) else: # No FROM clause: we need to use the unary pseudo-table. srcidx = add_rel_exp(memo, Exp('unary'), {'cols':[],'outs':Set(),'labels':[],'neededcols':Set()}) # Analyze WHERE. if exp.args._where is not None: # The WHERE clause is a scalar expression. fidx = analyze_scalar(memo, here, exp.args._where) # Make a filter node. The filter node propagates the result # columns and labels from the FROM source. # # The columns provided by the source are substracted from the # needed columns in the filter to determine the remaining # needed columns after the filter stage. srcidx = add_rel_exp(memo, Exp('filter', [srcidx, fidx]), {'cols': memo[srcidx].props.cols, 'outs': memo[srcidx].props.outs, 'labels': memo[srcidx].props.labels, 'neededcols':memo[fidx].props.neededcols.difference(memo[srcidx].props.cols), }) # XXX: we don't support GROUP BY here yet. # Analyze the projection targets. if exp.args._exprs is not None: exprs = exp.args._exprs # To facilitate testing, we provide some syntactic sugar so that # the user can omit the grouping braces when there is just one projection: # (select :exprs 123) == (select :exprs [123]) if not isinstance(exprs, list): exprs = [exprs] # A projection is defined by a scalar expression and a column label. # If the column label is not specified, we use a text representation # of the scalar expression as label. # # For example: # # (select :exprs [ (:a (* k 2)) (:b (+ v 3)) ]) # # == SELECT k*2 AS a, v+3 AS b # # Again we facilitate testing with syntactic sugar: the user # can omit the label, in which case it is computed automatically. labels, eexprs = [], [] for e in exprs: if not isinstance(e, Props): # Label omitted. labels.append(tocolname(e)) eexprs.append(e) else: # (:lbl <expr>) k = list(e.keys())[0] labels.append(k) eexprs.append(e[k]) # Analyze all the projection targets, and collect their memo indices. idxs = [analyze_scalar(memo, here, e) for e in eexprs] # The set of output columns for the projection is precisely the # set of projected expressions. outs = Set(idxs) # Small optimizations: if idxs == memo[srcidx].props.cols and labels == memo[srcidx].props.labels: # If are projecting exactly the columns of the source with the same names # and in the same order, we can omit the projection altogether. # # (select x as a from (select y as x from yt)) == (select y as a from yt) # pass elif outs == memo[srcidx].props.outs: # If we are projecting exactly the columns of the source but with # a different order and/or different columns, then *copy* the # original source node with the new order and labels. srcidx = add_rel_exp(memo, memo[srcidx].mexprs[0], {'cols':idxs,'outs':outs,'labels':labels, 'neededcols':memo[srcidx].props.neededcols}) else: # General case: add a projection node. # # Like for the filter node, the needed columns # (correlation dependencies) for the projection is the # union of needed columns for the projection expressions, # minus the columns provided by this SELECT clause. srcidx = add_rel_exp(memo, Exp('project', [srcidx]), {'cols':idxs, 'outs':outs, 'labels':labels, 'neededcols':memo[srcidx].props.neededcols.difference(outs), }) # XXX: we don't support ORDER BY here yet. # XXX: we don't support LIMIT here yet. # The result of the analysis is the memo index of the last node # constructed. return srcidx
def __init__(self, options): gr.top_block.__init__(self) if options.rx_freq is not None: u = uhd_receiver(options.args, options.bandwidth, options.rx_freq, options.rx_gain, options.spec, options.antenna, options.verbose) elif options.infile is not None: u = gr.file_source(gr.sizeof_gr_complex, options.infile) else: import sys sys.stderr.write("--freq or --infile must be specified\n") raise SystemExit self.scope = None if options.outfile is not None: rx = gr.file_sink(gr.sizeof_gr_complex, options.outfile) else: rx = ofdm_rxtx.RX(options) data_tones = rx.params.data_tones if options.rxdata is not None: if options.rxdata == '.': import scope # scope it out rxs = gr.vector_to_stream(gr.sizeof_gr_complex, data_tones) self.connect(rx, rxs) self.scope = scope.scope(self, rxs, 'Frame SNR', isComplex=True) else: if options.char > 0: # rail and scale self.connect(rx, gr.vector_to_stream(gr.sizeof_float, data_tones * 2), gr.multiply_const_ff(128.0 * (2**0.5)/ options.char), gr.rail_ff(-128.0, 127.0), gr.float_to_char(), gr.file_sink(gr.sizeof_char, options.rxdata)) else: self.connect(rx, gr.file_sink(data_tones * gr.sizeof_gr_complex, options.rxdata)) if options.snrdata is not None: # select one of the snr modes snr = ofdm_rxtx.SNR(rx.params.data_tones, options.size, mode=options.snrmode) if options.char > 0: # NOTE: we use repeat, assuming the file is long enough or properly aligned data = gr.stream_to_vector(gr.sizeof_float, data_tones * 2) self.connect(gr.file_source(gr.sizeof_char, options.txdata, repeat=True), gr.char_to_float(), gr.multiply_const_ff(options.char * (2**-0.5) / 128.0), data) else: data = ofdm_rxtx.make_data(rx.params.data_tones, options.size, options.txdata) self.connect(rx, (snr,0)) self.connect(data, (snr,1)) if options.snrdata == '-': # print it out msgq = gr.msg_queue(16) self.connect(snr, gr.message_sink(gr.sizeof_float, msgq, True)) self.watcher = ofdm_rxtx.queue_watcher(msgq) elif options.snrdata == '.': import scope # scope it out self.scope = scope.scope(self, snr, 'Frame SNR') else: self.connect(snr, gr.file_sink(gr.sizeof_float, options.snrdata)) else: pass #self.connect(rx, gr.null_sink(symbol_size)) # XXX do we still need this? self.connect(u, rx)
Declares a @builtin decorator class for tagging php built-in functions, as well as implements and exports most if not all php built-in functions. """ import scope import builtin import string import regex import constants import datetime import lang def gen_builtins(): modules=[constants, datetime, lang, string, regex] for module in modules: for member_name in dir(module): member = getattr(module, member_name) if member_name == 'CONSTANTS': for k,v in member: yield (k, v) elif isinstance(member, builtin.builtin): yield(member_name, member) builtins = scope.scope( dict(x for x in gen_builtins()), name='phpbuiltins' )