Parse a quil program and return a Program object
184788
def quil_to_program(quil: str) -> Program:
    """"""
    pyquil_instructions = pyquil.parser.parse(quil)
    return pyquil_to_program(pyquil_instructions)
37018
def parse():
    
    from fortpy.code import CodeParser
    c = CodeParser()
    
    if args["verbose"]:
        c.verbose = True

    f90files = {}
    c.scan_path(args["source"], f90files)
    for fname, fpath in f90files.items():
        if fname not in c._modulefiles:
            c._modulefiles[fname] = []
        c._parse_from_file(fpath, fname, args["recursive"], args["recursive"], False)

    return c
1108843
def parse(string):
  ""
  print string
  if string.strip().lower().startswith('create index'): return IndexX(string)
  return YACC.parse(string, lexer=LEXER.clone())
673724
def p_program_def(t):
    """"""
    print("Ignoring program {0:s} = {1:s}".format(t[2], t[8]))
    global name_dict
    id = t[2]
    value = t[8]
    lineno = t.lineno(1)
    if id_unique(id, 'program', lineno):
        name_dict[id] = const_info(id, value, lineno)
1157673
function _parse(type, obj, options)
{
    if (!obj) return _checkResult(type, lib.newError("empty " + type), obj, options);
    try {
        obj = _parseResult(type, obj, options);
    } catch(err) {
        obj = _checkResult(type, err, obj, options);
    }
    return obj;
}
43206
def parse_string(contents, name='tmp.cpp', **kwargs):
    
    idx = clang.cindex.Index.create()
    tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs)
    return _ensure_parse_valid(tu)
663372
def parse_executable_definition(lexer: Lexer) -> ExecutableDefinitionNode:
    """"""
    if peek(lexer, TokenKind.NAME):
        func = _parse_executable_definition_functions.get(cast(str, lexer.token.value))
        if func:
            return func(lexer)
    elif peek(lexer, TokenKind.BRACE_L):
        return parse_operation_definition(lexer)
    raise unexpected(lexer)
792124
def get_code(self, *args, **kwargs):
    
    # FIXME: Honestly should allow multiple commands
    callback = self._commands[args[0]]
    # TODO: syntax color would be nice
    source = _inspect.getsourcelines(callback)[0]
    """
    source_len = len(source)
    source = PygmentsLexer(CythonLexer).lex_document(source)()
    """
    # FIXME: formatting sucks
    return "\n" + "".join(source)
1281175
def parse (cls, line, lineno, log, cmddict):
    
    delay   = SeqDelay   .parse(line, lineno, log, cmddict)
    attrs   = SeqCmdAttrs.parse(line, lineno, log, cmddict)
    comment = SeqComment .parse(line, lineno, log, cmddict)
    stop    = len(line)

    if comment:
      stop = comment.pos.col.start - 1

    if attrs and attrs.pos.col.stop != -1:
      stop = attrs.pos.col.start - 1

    tokens = line[:stop].split()
    name   = tokens[1]
    args   = tokens[2:]
    start  = line.find(name)
    pos    = SeqPos(line, lineno, start + 1, stop)

    if name not in cmddict:
      log.error('Unrecognized command "%s".' % name, pos)
    elif cmddict[name].nargs != len(args):
      msg = 'Command argument size mismatch: expected %d, but encountered %d.'
      log.error(msg % (cmddict[name].nargs, len(args)), pos)

    args   = [ util.toNumber(a, a) for a in args ]
    cmd    = cmddict.create(name, *args)

    return cls(cmd, delay, attrs, comment, pos)
76591
def result(self):
        
        if not self.is_done():
            raise ValueError("Cannot get a result for a program that isn't completed.")

        if self._raw['status'] == 'CANCELLED':
            raise CancellationError(self._raw['result'])
        elif self._raw['status'] == 'ERROR':
            if self._machine == 'QVM':
                raise QVMError(self._raw['result'])
            elif self._machine == 'QPU':
                raise QPUError(self._raw['result'])
            elif self._machine == 'QUILC':
                raise QUILCError(self._raw['result'])
            else:
                raise UnknownApiError(self._raw['result'])

        if self._raw['program']['type'] == 'wavefunction':
            return Wavefunction.from_bit_packed_string(
                base64.b64decode(self._raw['result']), self._raw['program']['addresses'])
        elif self._raw['program']['type'] in ['multishot', 'multishot-measure', 'expectation']:
            return np.asarray(self._raw['result'])
        else:
            return self._raw['result']
1016343
def parse(self, line=None):
        """"""
        args = self.parser.parse_args(args=line)
        return args.func(args)
948577
def wavefunction_payload(quil_program, random_seed):
    """"""
    if not isinstance(quil_program, Program):
        raise TypeError("quil_program must be a Quil program object")

    payload = {'type': TYPE_WAVEFUNCTION,
               'compiled-quil': quil_program.out()}

    if random_seed is not None:
        payload['rng-seed'] = random_seed

    return payload
747917
def parse(url):
    
    result = urlparse.urlparse(nstr(url))

    path = result.scheme + '://' + result.netloc
    if result.path:
        path += result.path

    query = {}

    # extract the python information from the query
    if result.query:
        url_query = urlparse.parse_qs(result.query)
        for key, value in url_query.items():
            if type(value) == list and len(value) == 1:
                value = value[0]

            query[key] = value

    return path, query, result.fragment
678964
def parse (cls, line, lineno, log, cmddict=None):
    
    start  = line.find('%')
    pos    = SeqPos(line, lineno, start + 1, len(line))
    result = None

    if start >= 0:
      result = cls(line[start:], pos)

    return result
88459
def parse_type(defn, preprocess=True):
    
    if pycparser is None:
        raise ImportError("Please install pycparser in order to parse C definitions")

    defn = 'typedef ' + defn.strip('; \n\t\r') + ' QQQQ;'

    if preprocess:
        defn = do_preprocess(defn)

    node = pycparser.c_parser.CParser().parse(make_preamble()[0] + defn)
    if not isinstance(node, pycparser.c_ast.FileAST) or \
            not isinstance(node.ext[-1], pycparser.c_ast.Typedef):
        raise ValueError("Something went horribly wrong using pycparser")

    decl = node.ext[-1].type
    return _decl_to_type(decl)
1312139
def parse(self, f):
        '''
        '''
        self._listener.parse_start()

        while len(f):
            data = f.read(self._buffer_size).encode('utf-8')
            status = yajl.yajl_parse(self._handler, data, len(data))
            self._listener.parse_buf()
            if status != OK.value:
                if status == CLIENT_CANCELLED.value:
                    if self._exc_info:
                        exc_info = self._exc_info
                        raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
                    else:
                        raise YajlError("Client probably cancelled callback")
                else:
                    yajl.yajl_get_error.restype = c_char_p
                    error = yajl.yajl_get_error(self._handler, 1, data, len(data))
                    raise YajlError(error)
            if not data: return
915952
def run(self):
        

        super().run()

        if not isinstance(self._executable, Program):
            # This should really never happen
            # unless a user monkeys with `self.status` and `self._executable`.
            raise ValueError("Please `load` an appropriate executable.")

        quil_program = self._executable
        trials = quil_program.num_shots
        classical_addresses = get_classical_addresses_from_program(quil_program)

        if self.noise_model is not None:
            quil_program = apply_noise_model(quil_program, self.noise_model)

        quil_program = self.augment_program_with_memory_values(quil_program)
        try:
            self._bitstrings = self.connection._qvm_run(quil_program=quil_program,
                                                        classical_addresses=classical_addresses,
                                                        trials=trials,
                                                        measurement_noise=self.measurement_noise,
                                                        gate_noise=self.gate_noise,
                                                        random_seed=self.random_seed)['ro']
        except KeyError:
            warnings.warn("You are running a QVM program with no MEASURE instructions. "
                          "The result of this program will always be an empty array. Are "
                          "you sure you didn't mean to measure some of your qubits?")
            self._bitstrings = np.zeros((trials, 0), dtype=np.int64)

        return self