Helper to compile protobuf files
12524
def _compile_proto(full_path, dest):
    ''
    proto_path = os.path.dirname(full_path)
    protoc_args = [find_protoc(),
                   '--python_out={}'.format(dest),
                   '--proto_path={}'.format(proto_path),
                   full_path]
    proc = subprocess.Popen(protoc_args, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    try:
        outs, errs = proc.communicate(timeout=5)
    except subprocess.TimeoutExpired:
        proc.kill()
        outs, errs = proc.communicate()
        return False

    if proc.returncode != 0:
        msg = 'Failed compiling "{}": \n\nstderr: {}\nstdout: {}'.format(
            full_path, errs.decode('utf-8'), outs.decode('utf-8'))
        raise BadProtobuf(msg)

    return True
756172
function compile( bundleData, bundleFile, config, callback ) {
	var baseDir = config['path'] || path.dirname(bundleFile);
	var encoder, profileEncoder = [], profileLoader = [], bundleLoader;

	// Compile stages
	var openBundle = function( cb ) {
		return function() {

			// Create encoder
			encoder = new BinaryEncoder(
					bundleFile,
					{
						'name' 			: bundleData['name'],
						'base_dir' 		: baseDir,
						'log'			: config['log'] || 0x00,
						'sparse'		: config['sparse'],
					}
				);

			// Add profiles
			for (var i=0; i<profileEncoder.length; i++) {
				encoder.addProfile( profileEncoder[i] );
			}

			// We are ready
			cb();
		}
	}

	var loadBundles = function( cb ) {
		return function() {
			// Load a bundle by specs
			bundleLoader.addBySpecs( bundleData );
			// Solve dependencies and load resources
			bundleLoader.load( cb );
		}
	}

	var compileExports = function( cb ) {
		return function() {
			// Get the bundle to encode
			var bundle = bundleLoader.bundles[ bundleData['name'] ];

			// Encode resources
			for (var k in bundle.resources) {
				encoder.encode( bundle.resources[k], k );
			}

			// Embed blobs
			for (var k in bundle.blobs) {
				encoder.embedBlob( bundle.blobs[k][0], k, bundle.blobs[k][1] );
			}

			// We are done
			cb();
		}
	}

	var closeBundle = function( cb ) {
		return function() {
			// Close & Complete
			encoder.close();
			cb();
		}
	}

	// Check for profileTable/profileLoader
	if (config['profileEncoder'] || config['profileLoader']) {

		// Check for missing arguments
		if (!config['profileEncoder']) {
			callback( "Got 'profileLoader' but missing 'profileEncoder' in the arguments" );
			return;
		}
		if (!config['profileLoader']) {
			callback( "Got 'profileEncoder' but missing 'profileLoader' in the arguments" );
			return;
		}

		// Fetch
		profileEncoder = config['profileEncoder'];
		profileLoader = config['profileLoader'];

		// Make sure it's array
		if (!(profileEncoder instanceof Array))
			profileEncoder = [ profileEncoder ];
		if (!(profileLoader instanceof Array))
			profileLoader = [ profileLoader ];

	} else {

		// Identify some important information
		var profile = config['profile'] || bundleData['profile'];
		if (!profile) {
			callback( "No jbb profile was specified!");
			return;
		}

		// Make sure it's array
		if (typeof profile === 'string')
			profile = [ profile ];

		// Require
		for (var i=0; i<profile.length; i++) {
			var pname = profile[i];
			if (pname[0] == ".") {
				profileEncoder.push( require( path.join(process.cwd(), pname, '/profile-encode') ) );
				profileLoader.push( require( path.join(process.cwd(), pname, "/profile-loader") ) );
			} else {
				profileEncoder.push( require('jbb-profile-'+pname+'/profile-encode') );
				profileLoader.push( require('jbb-profile-'+pname+"/profile-loader") );
			}
		}

	}

	// Load profile table and compiler helper
	bundleLoader = new BundlesLoader( baseDir );
	for (var i=0; i<profileLoader.length; i++) {
		bundleLoader.addProfileLoader( profileLoader[i] );
	}

	// Chained initialization of profile loaders
	var context = { 'remaining': profileLoader.length }
	var init_callback = (function() {
		if (--this.remaining == 0) {
			openBundle(
				loadBundles(
					compileExports(
						closeBundle( callback || function(){} )
						) 
					) 
			)();
		}
	}).bind(context);

	// Initialize profile compiler with the specs file
	for (var i=0; i<profileLoader.length; i++) {
		if (!profileLoader[i].initialize) {
			init_callback();
		} else {
			profileLoader[i].initialize( init_callback, bundleData );
		}
	}

}
1319731
function(values, var_args) {
                    ProtoBuf.Builder.Message.call(this);

                    // Create virtual oneof properties
                    for (var i=0, k=oneofs.length; i<k; ++i)
                        this[oneofs[i].name] = null;
                    // Create fields and set default values
                    for (i=0, k=fields.length; i<k; ++i) {
                        var field = fields[i];
                        this[field.name] =
                            field.repeated ? [] :
                            (field.map ? new ProtoBuf.Map(field) : null);
                        if ((field.required || T.syntax === 'proto3') &&
                            field.defaultValue !== null)
                            this[field.name] = field.defaultValue;
                    }

                    if (arguments.length > 0) {
                        var value;
                        // Set field values from a values object
                        if (arguments.length === 1 && values !== null && typeof values === 'object' &&
                            /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
                            /* not a repeated field */ !Array.isArray(values) &&
                            /* not a Map */ !(values instanceof ProtoBuf.Map) &&
                            /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
                            /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
                            /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
                            this.$set(values);
                        } else // Set field values from arguments, in declaration order
                            for (i=0, k=arguments.length; i<k; ++i)
                                if (typeof (value = arguments[i]) !== 'undefined')
                                    this.$set(fields[i].name, value); // May throw
                    }
                }
1244018
def _compiled(self):
        """"""
        # Dev Notes:
        # Because of fast locals in functions in both CPython and PyPy, getting a
        # function to execute makes the code a few times faster than
        # just executing it in the global exec scope.
        prog = [self._prog_start]

        simple_func = {  # OPS
            'w': lambda x: x,
            'r': lambda x: x,
            '~': lambda x: '(~' + x + ')',
            '&': lambda l, r: '(' + l + '&' + r + ')',
            '|': lambda l, r: '(' + l + '|' + r + ')',
            '^': lambda l, r: '(' + l + '^' + r + ')',
            'n': lambda l, r: '(~(' + l + '&' + r + '))',
            '+': lambda l, r: '(' + l + '+' + r + ')',
            '-': lambda l, r: '(' + l + '-' + r + ')',
            '*': lambda l, r: '(' + l + '*' + r + ')',
            '<': lambda l, r: 'int(' + l + '<' + r + ')',
            '>': lambda l, r: 'int(' + l + '>' + r + ')',
            '=': lambda l, r: 'int(' + l + '==' + r + ')',
            'x': lambda sel, f, t: '({}) if ({}==0) else ({})'.format(f, sel, t),
        }

        def shift(value, direction, shift_amt):
            if shift_amt == 0:
                return value
            else:
                return '(%s %s %d)' % (value, direction, shift_amt)

        def make_split():
            if split_start_bit == 0:
                bit = '(%d & %s)' % ((1 << split_length) - 1, source)
            elif len(net.args[0]) - split_start_bit == split_length:
                bit = '(%s >> %d)' % (source, split_start_bit)
            else:
                bit = '(%d & (%s >> %d))' % ((1 << split_length) - 1, source, split_start_bit)
            return shift(bit, '<<', split_res_start_bit)

        for net in self.block:
            if net.op in simple_func:
                argvals = (self._arg_varname(arg) for arg in net.args)
                expr = simple_func[net.op](*argvals)
            elif net.op == 'c':
                expr = ''
                for i in range(len(net.args)):
                    if expr is not '':
                        expr += ' | '
                    shiftby = sum(len(j) for j in net.args[i+1:])
                    expr += shift(self._arg_varname(net.args[i]), '<<', shiftby)
            elif net.op == 's':
                source = self._arg_varname(net.args[0])
                expr = ''
                split_length = 0
                split_start_bit = -2
                split_res_start_bit = -1

                for i, b in enumerate(net.op_param):
                    if b != split_start_bit + split_length:
                        if split_start_bit >= 0:
                            # create a wire
                            expr += make_split() + '|'
                        split_length = 1
                        split_start_bit = b
                        split_res_start_bit = i
                    else:
                        split_length += 1
                expr += make_split()
            elif net.op == 'm':
                read_addr = self._arg_varname(net.args[0])
                mem = net.op_param[1]
                if isinstance(net.op_param[1], RomBlock):
                    expr = 'd["%s"]._get_read_data(%s)' % (self._mem_varname(mem), read_addr)
                else:  # memories act async for reads
                    expr = 'd["%s"].get(%s, %s)' % (self._mem_varname(mem),
                                                    read_addr, self.default_value)
            elif net.op == '@':
                mem = self._mem_varname(net.op_param[1])
                write_addr, write_val, write_enable = (self._arg_varname(a) for a in net.args)
                prog.append('    if {}:'.format(write_enable))
                prog.append('        mem_ws.append(("{}", {}, {}))'
                            .format(mem, write_addr, write_val))
                continue  # memwrites are special
            else:
                raise PyrtlError('FastSimulation cannot handle primitive "%s"' % net.op)

            # prog.append('    #  ' + str(net))
            result = self._dest_varname(net.dests[0])
            if len(net.dests[0]) == self._no_mask_bitwidth[net.op](net):
                prog.append("    %s = %s" % (result, expr))
            else:
                mask = str(net.dests[0].bitmask)
                prog.append('    %s = %s & %s' % (result, mask, expr))

        # add traced wires to dict
        if self.tracer is not None:
            for wire_name in self.tracer.trace:
                wire = self.block.wirevector_by_name[wire_name]
                if not isinstance(wire, (Input, Const, Register, Output)):
                    v_wire_name = self._varname(wire)
                    prog.append('    outs["%s"] = %s' % (wire_name, v_wire_name))

        prog.append("    return regs, outs, mem_ws")
        return '\n'.join(prog)
329181
def to_protobuf(self) -> LinkItemProto:
        
        result = LinkItemProto()
        result.name = self._name
        result.time.CopyFrom(datetime_to_timestamp(self._time))
        return result
795561
function _getNodeCompiler(
  nodeFileDir,
  nodeConfigureArgs,
  nodeMakeArgs,
  nodeVCBuildArgs,
  complete,
  type,
) {
  var dir = _getFirstDirectory(nodeFileDir);

  // standard
  var executable = 'node.exe';
  var binary = 'node';

  // iojs specifics.
  if (framework === 'iojs') {
    executable = 'iojs.exe';
    binary = 'iojs';
  }

  if (dir) {
    if (isWin) {
      complete(null, {
        dir: dir,
        version: path.basename(nodeFileDir),
        releasePath: path.join(dir, 'Release', executable),
        make: function(next) {
          // create a new env with minimal impact on old one
          var newEnv = process.env;

          if (isPy !== 'python') {
            // add the dir of the suposed python exe to path
            newEnv.path = process.env.PATH + ';' + path.dirname(isPy);
          }

          if (!nodeVCBuildArgs || !nodeVCBuildArgs.length) {
            nodeVCBuildArgs = ['nosign']; // "release" is already the default config value in VCBuild.bat
          }

          // spawn a vcbuild process with our custom enviroment.
          var vcbuild = spawn('vcbuild.bat', nodeVCBuildArgs, {
            cwd: dir,
            env: newEnv,
          });
          vcbuild.stdout.pipe(process.stdout);
          vcbuild.stderr.pipe(process.stderr);
          vcbuild.on('close', function() {
            next();
          });
        },
      });
    } else {
      complete(null, {
        dir: dir,
        version: path.basename(nodeFileDir),
        releasePath: path.join(dir, 'out', 'Release', binary),
        make: function(next) {
          var cfg = './configure',
            configure;

          var conf = [cfg];

          /* add all nodeConfigureArgs to the ./configure argument array */
          conf = [conf].concat(nodeConfigureArgs);

          // should work for all use cases now.
          configure = spawn(isPy, conf, {
            cwd: dir.toString('ascii'),
          });

          // local function, move to top eventually
          function _loop(dir) {
            /* eventually try every python file */
            var pdir = fs.readdirSync(dir);

            pdir.forEach(function(v, i) {
              var stat = fs.statSync(dir + '/' + v);
              if (stat.isFile()) {
                // only process Makefiles and .mk targets.
                if (v !== 'Makefile' && path.extname(v) !== '.mk') {
                  return;
                }

                _log('patching ' + v);

                /* patch the file */
                var py = fs.readFileSync(dir + '/' + v, {
                  encoding: 'utf8',
                });
                py = py.replace(/([a-z]|\/)*python(\w|)/gm, isPy); // this is definently needed
                fs.writeFileSync(dir + '/' + v, py, {
                  encoding: 'utf8',
                }); // write to file
              } else if (stat.isDirectory()) {
                // must be dir?
                // skip tests because we don't need them here
                if (v !== 'test') {
                  _loop(dir + '/' + v);
                }
              }
            });
          }

          configure.stdout.pipe(process.stdout);
          configure.stderr.pipe(process.stderr);

          // on error
          configure.on('error', function(err) {
            console.log('Error:', err);
            console.log('');
            console.log('Details:');
            console.log('command =', isPy, cfg, conf_args || '');
            console.log('cwd =', dir);

            var configure_path = path.join(dir, 'configure');
            var contains_configure = fs.existsSync(configure_path);

            console.log(
              'cwd contains configure,',
              contains_configure ? colors.green('yes') : colors.red('no'),
            );

            var configure_size = fs.statSync(configure_path).size;

            console.log(
              'configure is non-zero size,',
              configure_size > 0 ? colors.green('yes') : colors.red('no'),
            );

            _log('error', 'failed to launch configure.');
            process.exit(1);
          });

          // when it's finished
          configure.on('close', function() {
            if (isPy !== 'python') {
              /**
               * Originally I thought this only applied to io.js,
               * however I soon found out this affects node.js,
               * so it is now mainstream.
               */
              _log('preparing python');

              // loop over depends
              _loop(dir);
            }

            if (nodeMakeArgs === undefined) {
              nodeMakeArgs = [];
            }

            var platformMake = 'make';
            if (os.platform().match(/bsd$/) != null) {
              platformMake = 'gmake';
            }

            var make = spawn(platformMake, nodeMakeArgs, {
              cwd: dir,
            });
            make.stdout.pipe(process.stdout);
            make.stderr.pipe(process.stderr);
            make.on('error', function(err) {
              console.log(err);
              _log('error', 'failed to run make.');
              process.exit(1);
            });
            make.on('close', function() {
              next();
            });
          });
        },
      });
    }
    return true;
  }

  return false;
}
716071
def _parse_proto(prototxt_fname):
    
    proto = caffe_parser.read_prototxt(prototxt_fname)

    # process data layer
    input_name, input_dim, layers = _get_input(proto)
    # only support single input, so always use `data` as the input data
    mapping = {input_name: 'data'}
    need_flatten = {input_name: False}
    symbol_string = "import mxnet as mx\ndata = mx.symbol.Variable(name='data')\n"

    flatten_count = 0
    output_name = ""
    prev_name = None
    _output_name = {}

    # convert reset layers one by one
    for i, layer in enumerate(layers):
        type_string = ''
        param_string = ''
        skip_layer = False
        name = re.sub('[-/]', '_', layer.name)
        for k in range(len(layer.bottom)):
            if layer.bottom[k] in _output_name:
                _output_name[layer.bottom[k]]['count'] = _output_name[layer.bottom[k]]['count']+1
            else:
                _output_name[layer.bottom[k]] = {'count':0}
        for k in range(len(layer.top)):
            if layer.top[k] in _output_name:
                _output_name[layer.top[k]]['count'] = _output_name[layer.top[k]]['count']+1
            else:
                _output_name[layer.top[k]] = {'count':0, 'name':name}
        if layer.type == 'Convolution' or layer.type == 4:
            type_string = 'mx.symbol.Convolution'
            param_string = _convert_conv_param(layer.convolution_param)
            need_flatten[name] = True
        if layer.type == 'Deconvolution' or layer.type == 39:
            type_string = 'mx.symbol.Deconvolution'
            param_string = _convert_conv_param(layer.convolution_param)
            need_flatten[name] = True
        if layer.type == 'Pooling' or layer.type == 17:
            type_string = 'mx.symbol.Pooling'
            param_string = _convert_pooling_param(layer.pooling_param)
            need_flatten[name] = True
        if layer.type == 'ReLU' or layer.type == 18:
            type_string = 'mx.symbol.Activation'
            param_string = "act_type='relu'"
            param = layer.relu_param
            if hasattr(param, 'negative_slope'):
                if param.negative_slope > 0:
                    type_string = 'mx.symbol.LeakyReLU'
                    param_string = "act_type='leaky', slope=%f" % param.negative_slope
            need_flatten[name] = need_flatten[mapping[layer.bottom[0]]]
        if layer.type == 'TanH' or layer.type == 23:
            type_string = 'mx.symbol.Activation'
            param_string = "act_type='tanh'"
            need_flatten[name] = need_flatten[mapping[layer.bottom[0]]]
        if layer.type == 'Sigmoid' or layer.type == 19:
            type_string = 'mx.symbol.Activation'
            param_string = "act_type='sigmoid'"
            need_flatten[name] = need_flatten[mapping[layer.bottom[0]]]
        if layer.type == 'LRN' or layer.type == 15:
            type_string = 'mx.symbol.LRN'
            param = layer.lrn_param
            param_string = "alpha=%f, beta=%f, knorm=%f, nsize=%d" % (
                param.alpha, param.beta, param.k, param.local_size)
            need_flatten[name] = True
        if layer.type == 'InnerProduct' or layer.type == 14:
            type_string = 'mx.symbol.FullyConnected'
            param = layer.inner_product_param
            param_string = "num_hidden=%d, no_bias=%s" % (
                param.num_output, not param.bias_term)
            need_flatten[name] = False
        if layer.type == 'Dropout' or layer.type == 6:
            type_string = 'mx.symbol.Dropout'
            param = layer.dropout_param
            param_string = "p=%f" % param.dropout_ratio
            need_flatten[name] = need_flatten[mapping[layer.bottom[0]]]
        if layer.type == 'Softmax' or layer.type == 20:
            type_string = 'mx.symbol.SoftmaxOutput'
        if layer.type == 'Flatten' or layer.type == 8:
            type_string = 'mx.symbol.Flatten'
            need_flatten[name] = False
        if layer.type == 'Split' or layer.type == 22:
            type_string = 'split'  # will process later
        if layer.type == 'Concat' or layer.type == 3:
            type_string = 'mx.symbol.Concat'
            need_flatten[name] = True
        if layer.type == 'Crop':
            type_string = 'mx.symbol.Crop'
            need_flatten[name] = True
            param_string = 'center_crop=True'
        if layer.type == 'BatchNorm':
            type_string = 'mx.symbol.BatchNorm'
            param = layer.batch_norm_param
            # CuDNN requires eps to be greater than 1e-05
            # We compensate for this change in convert_model
            epsilon = param.eps
            if (epsilon <= 1e-05):
                epsilon = 1e-04
            # if next layer is scale, don't fix gamma
            fix_gamma = layers[i+1].type != 'Scale'
            param_string = 'use_global_stats=%s, fix_gamma=%s, eps=%f' % (
                param.use_global_stats, fix_gamma, epsilon)
            need_flatten[name] = need_flatten[mapping[layer.bottom[0]]]
        if layer.type == 'Scale':
            assert layers[i-1].type == 'BatchNorm'
            need_flatten[name] = need_flatten[mapping[layer.bottom[0]]]
            skip_layer = True
            prev_name = re.sub('[-/]', '_', layers[i-1].name)
        if layer.type == 'PReLU':
            type_string = 'mx.symbol.LeakyReLU'
            param = layer.prelu_param
            param_string = "act_type='prelu', slope=%f" % param.filler.value
            need_flatten[name] = need_flatten[mapping[layer.bottom[0]]]
        if layer.type == 'Eltwise':
            type_string = 'mx.symbol.broadcast_add'
            param = layer.eltwise_param
            param_string = ""
            need_flatten[name] = False
        if layer.type == 'Reshape':
            type_string = 'mx.symbol.Reshape'
            need_flatten[name] = False
            param = layer.reshape_param
            param_string = "shape=(%s)" % (','.join(param.shape.dim),)
        if layer.type == 'AbsVal':
            type_string = 'mx.symbol.abs'
            need_flatten[name] = need_flatten[mapping[layer.bottom[0]]]

        if skip_layer:
            assert len(layer.bottom) == 1
            symbol_string += "%s = %s\n" % (name, prev_name)
        elif type_string == '':
            raise ValueError('Unknown layer %s!' % layer.type)
        elif type_string != 'split':
            bottom = layer.bottom
            if param_string != "":
                param_string = ", " + param_string
            if len(bottom) == 1:
                if need_flatten[mapping[bottom[0]]] and type_string == 'mx.symbol.FullyConnected':
                    flatten_name = "flatten_%d" % flatten_count
                    symbol_string += "%s=mx.symbol.Flatten(name='%s', data=%s)\n" % (
                        flatten_name, flatten_name, mapping[bottom[0]])
                    flatten_count += 1
                    need_flatten[flatten_name] = False
                    bottom[0] = flatten_name
                    mapping[bottom[0]] = bottom[0]
                symbol_string += "%s = %s(name='%s', data=%s %s)\n" % (
                    name, type_string, name, mapping[bottom[0]], param_string)
            else:
                if layer.type == 'Eltwise' and param.operation == 1 and len(param.coeff) > 0:
                    symbol_string += "%s = " % name
                    symbol_string += " + ".join(["%s * %s" % (
                        mapping[bottom[i]], param.coeff[i]) for i in range(len(param.coeff))])
                    symbol_string += "\n"
                else:
                    symbol_string += "%s = %s(name='%s', *[%s] %s)\n" % (
                        name, type_string, name, ','.join(
                            [mapping[x] for x in bottom]), param_string)
        for j in range(len(layer.top)):
            mapping[layer.top[j]] = name
        output_name = name
    output_name = []
    for i in _output_name:
        if 'name' in _output_name[i] and _output_name[i]['count'] == 0:
            output_name.append(_output_name[i]['name'])

    return symbol_string, output_name, input_dim
1072636
def compile_cc(build_context, compiler_config, buildenv, sources,
               workspace_dir, buildenv_workspace, cmd_env):
    
    objects = []
    for src in sources:
        obj_rel_path = '{}.o'.format(splitext(src)[0])
        obj_file = join(buildenv_workspace, obj_rel_path)
        include_paths = [buildenv_workspace] + compiler_config.include_path
        compile_cmd = (
            [compiler_config.compiler, '-o', obj_file, '-c'] +
            compiler_config.compile_flags +
            ['-I{}'.format(path) for path in include_paths] +
            [join(buildenv_workspace, src)])
        # TODO: capture and transform error messages from compiler so file
        # paths match host paths for smooth(er) editor / IDE integration
        build_context.run_in_buildenv(buildenv, compile_cmd, cmd_env)
        objects.append(
            join(relpath(workspace_dir, build_context.conf.project_root),
                 obj_rel_path))
    return objects
431922
public void compile(ModuleConfiguration configuration) {
        LOGGER.debug("Compiling module {}", configuration);
        FileReaderFactory fileReaderFactory = injector.getInstance(FileReaderFactory.class);
        Importer importer = injector.getInstance(Importer.class);
        CompilerRegistry registry = injector.getInstance(CompilerRegistry.class);
        ProtoCompiler compiler = registry.findCompiler(configuration.getGenerator());
        if (compiler == null) {
            throw new GeneratorException("Unknown template: %s | %s", configuration.getGenerator(), registry.availableCompilers());
        }
        FileReader fileReader = fileReaderFactory.create(configuration.getIncludePaths());
        Map<String, Proto> importedFiles = new HashMap<>();
        for (String path : configuration.getProtoFiles()) {
            LOGGER.info("Parse {}", path);
            ProtoContext context = importer.importFile(fileReader, path);
            Proto proto = context.getProto();
            importedFiles.put(path, proto);
        }
        ImmutableModule.Builder builder = ImmutableModule.builder();
        builder.name(configuration.getName());
        builder.output(configuration.getOutput());
        builder.options(configuration.getOptions());
        for (Proto proto : importedFiles.values()) {
            builder.addProtos(proto);
        }
        UsageIndex index = UsageIndex.build(importedFiles.values());
        builder.usageIndex(index);
        ImmutableModule module = builder.build();
        for (Proto proto : importedFiles.values()) {
            proto.setModule(module);
        }
        compiler.compile(module);
    }
825208
def protoc_arguments():
    '''
    
    '''
    proto_include = resource_filename('grpc_tools', '_proto')
    return [
        protoc.__file__, '-I', GARUDA_DIR, f'--python_out={GARUDA_DIR}',
        f'--grpc_python_out={GARUDA_DIR}', GARUDA_PROTO_PATH,
        f'-I{proto_include}']
1267687
function compile(fileNames, options, verbose) {
  const program = ts.createProgram(fileNames, options)
  const emitResult = program.emit()

  /* istanbul ignore next */
  if (verbose) {
    const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics)

    allDiagnostics.forEach((diagnostic) => {
      if (diagnostic.file) {
        const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(
          diagnostic.start
        )
        const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
        console.log(
          `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`
        )
      } else {
        console.log(`${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`)
      }
    })
  }
}
615965
def parse_protobuf(self, proto_type):
        """"""
        if 'protobuf' not in self.environ.get('CONTENT_TYPE', ''):
            raise BadRequest('Not a Protobuf request')

        obj = proto_type()
        try:
            obj.ParseFromString(self.data)
        except Exception:
            raise BadRequest("Unable to parse Protobuf request")

        # Fail if not all required fields are set
        if self.protobuf_check_initialization and not obj.IsInitialized():
            raise BadRequest("Partial Protobuf request")

        return obj
585221
def GenerateDPKGFiles(self, template_path):
    """"""

    # Rename the generated binaries to the correct name.
    template_binary_dir = os.path.join(template_path, "dist/debian/grr-client")
    package_name = config.CONFIG.Get(
        "ClientBuilder.package_name", context=self.context)
    target_binary_dir = os.path.join(
        template_path, "dist/debian/%s%s" %
        (package_name,
         config.CONFIG.Get("ClientBuilder.target_dir", context=self.context)))
    if package_name == "grr-client":
      # Need to rename the template path or the move will fail.
      shutil.move(template_binary_dir, "%s-template" % template_binary_dir)
      template_binary_dir = "%s-template" % template_binary_dir

    utils.EnsureDirExists(os.path.dirname(target_binary_dir))
    shutil.move(template_binary_dir, target_binary_dir)

    shutil.move(
        os.path.join(target_binary_dir, "grr-client"),
        os.path.join(
            target_binary_dir,
            config.CONFIG.Get("Client.binary_name", context=self.context)))

    deb_in_dir = os.path.join(template_path, "dist/debian/debian.in/")

    self.GenerateDirectory(deb_in_dir, os.path.join(
        template_path, "dist/debian"), [("grr-client", package_name)])

    # Generate directories for the /usr/sbin link.
    utils.EnsureDirExists(
        os.path.join(template_path, "dist/debian/%s/usr/sbin" % package_name))

    if config.CONFIG.Get("Client.fleetspeak_enabled", context=self.context):
      self._GenerateFleetspeakConfig(template_path)
      shutil.rmtree(deb_in_dir)
      shutil.rmtree(os.path.join(template_path, "dist", "fleetspeak"))
      return

    # Generate the nanny template. This only exists from client version 3.1.2.5
    # onwards.
    if config.CONFIG["Template.version_numeric"] >= 3125:
      self.GenerateFile(
          os.path.join(target_binary_dir, "nanny.sh.in"),
          os.path.join(target_binary_dir, "nanny.sh"))

    # Generate the upstart template.
    self.GenerateFile(
        os.path.join(template_path, "dist/debian/upstart.in/grr-client.conf"),
        os.path.join(template_path, "dist/debian/%s.upstart" % package_name))

    # Generate the initd template. The init will not run if it detects upstart
    # is present.
    self.GenerateFile(
        os.path.join(template_path, "dist/debian/initd.in/grr-client"),
        os.path.join(template_path, "dist/debian/%s.init" % package_name))

    # Generate the systemd unit file.
    self.GenerateFile(
        os.path.join(template_path,
                     "dist/debian/systemd.in/grr-client.service"),
        os.path.join(template_path, "dist/debian/%s.service" % package_name))

    # Clean up the template dirs.
    shutil.rmtree(deb_in_dir)
    shutil.rmtree(os.path.join(template_path, "dist/debian/upstart.in"))
    shutil.rmtree(os.path.join(template_path, "dist/debian/initd.in"))
    shutil.rmtree(os.path.join(template_path, "dist/debian/systemd.in"))
1252304
def Clean():
  """"""
  # Find all the compiled proto files and unlink them.
  for (root, _, files) in os.walk(ROOT):
    for filename in files:
      full_filename = os.path.join(root, filename)
      if full_filename.endswith("_pb2.py") or full_filename.endswith(
          "_pb2.pyc"):
        os.unlink(full_filename)
926530
function compile(path, callback) {
  if (/\.luax/.test(path)) {
    // Load already compiled bytecode
    loadBytecode(path);
  }
  if (/\.lua$/.test(path)) {
    luaToBytecode(path, function (err, newpath) {
      if (err) return callback(err);
      loadBytecode(newpath);
    });
  }
  function loadBytecode(path) {
    readFile(path, function (err, buffer) {
      if (err) return callback(err);
      generate(buffer);
    });
  }
  function generate(buffer) {
    var program;
    try {
      program = parse(buffer);
    }
    catch (err) {
      return callback(err);
    }
    callback(null, program);
  }
}
865066
def from_protobuf(cls, msg):
        """"""
        if not isinstance(msg, cls._protobuf_cls):
            raise TypeError("Expected message of type "
                            "%r" % cls._protobuf_cls.__name__)
        kwargs = {k: getattr(msg, k) for k in cls._get_params()}
        return cls(**kwargs)
1328199
function compilePackage(p) {
      compileForType(p);
      p.path = getPackagePath(p);
      p.compiledBody = compact([
        STRICT,
        getRequires(p),
        getDirectRequires(p),
        getAssigns(p),
        p.body,
        getPostAssigns(p),
        getExports(p)
      ]).join('\n\n');
    }