def map_memory_callback(self, address, size, perms, name, offset, result):

logger.info('<STR_LIT:U+0020>'.join(("<STR_LIT>",<EOL>hex(address) if type(address) is int else "<STR_LIT>",<EOL>hr_size(size), "<STR_LIT:->",<EOL>perms, "<STR_LIT:->",<EOL>f"<STR_LIT>", "<STR_LIT>",<EOL>hex(result))))<EOL>self._emu.mem_map(address, size, convert_permissions(perms))<EOL>self.copy_memory(address, size)<EOL>

Catches did_map_memory and copies the mapping into Manticore


def write_back_register(self, reg, val):

if self.write_backs_disabled:<EOL><INDENT>return<EOL><DEDENT>if issymbolic(val):<EOL><INDENT>logger.warning("<STR_LIT>")<EOL>return<EOL><DEDENT>if reg in self.flag_registers:<EOL><INDENT>self._emu.reg_write(self._to_unicorn_id('<STR_LIT>'), self._cpu.read_register('<STR_LIT>'))<EOL>return<EOL><DEDENT>self._emu.reg_write(self._to_unicorn_id(reg), val)<EOL>

Sync register state from Manticore -> Unicorn


@concretized_args(account='<STR_LIT>')<EOL><INDENT>def EXTCODECOPY(self, account, address, offset, size):<DEDENT>

extbytecode = self.world.get_code(account)<EOL>self._allocate(address + size)<EOL>for i in range(size):<EOL><INDENT>if offset + i < len(extbytecode):<EOL><INDENT>self._store(address + i, extbytecode[offset + i])<EOL><DEDENT>else:<EOL><INDENT>self._store(address + i, <NUM_LIT:0>)<EOL><DEDENT><DEDENT>


if len(self.stack) - n < <NUM_LIT:0>:<EOL><INDENT>raise StackUnderflow()<EOL><DEDENT>return self.stack[n - <NUM_LIT:1>]<EOL>

Read a value from the top of the stack without removing it


assert isinstance(value, int) or isinstance(value, BitVec) and value.size == <NUM_LIT><EOL>if len(self.stack) >= <NUM_LIT>:<EOL><INDENT>raise StackOverflow()<EOL><DEDENT>if isinstance(value, int):<EOL><INDENT>value = value & TT256M1<EOL><DEDENT>value = simplify(value)<EOL>if isinstance(value, Constant) and not value.taint:<EOL><INDENT>value = value.value<EOL><DEDENT>self.stack.append(value)<EOL>

Push into the stack

      ITEM0
      ITEM1
      ITEM2
sp->  {empty}


@transact<EOL><INDENT>def CREATE(self, value, offset, size):<DEDENT>

Create a new account with associated code


raise EndTx('<STR_LIT>')<EOL>


if istainted(self.pc):<EOL><INDENT>for taint in get_taints(self.pc):<EOL><INDENT>value = taint_with(value, taint)<EOL><DEDENT><DEDENT>self._allocate(address, <NUM_LIT:1>)<EOL>self._store(address, Operators.EXTRACT(value, <NUM_LIT:0>, <NUM_LIT:8>), <NUM_LIT:1>)<EOL>


return a ^ b<EOL>


return (self.__class__, (self.sort, self.address, self.price, self.data, self.caller, self.value, self.gas, self.depth, self.result, self.return_data))<EOL>


try:<EOL><INDENT>result = Operators.ITEBV(<NUM_LIT>, b == <NUM_LIT:0>, <NUM_LIT:0>, a % b)<EOL><DEDENT>except ZeroDivisionError:<EOL><INDENT>result = <NUM_LIT:0><EOL><DEDENT>return result<EOL>


offset = Operators.ITEBV(<NUM_LIT>, offset < <NUM_LIT:32>, (<NUM_LIT> - offset) * <NUM_LIT:8>, <NUM_LIT>)<EOL>return Operators.ZEXTEND(Operators.EXTRACT(value, offset, <NUM_LIT:8>), <NUM_LIT>)<EOL>


storage = self._world_state[address]['<STR_LIT>']<EOL>array = storage.array<EOL>while not isinstance(array, ArrayVariable):<EOL><INDENT>if isinstance(array, ArrayStore):<EOL><INDENT>return True<EOL><DEDENT>array = array.array<EOL><DEDENT>return False<EOL>

True if something has been written to the storage.
Note that if a slot has been erased from the storage this function may
lose any meaning.


def set_storage_data(self, storage_address, offset, value):

self._world_state[storage_address]['<STR_LIT>'][offset] = value<EOL>

Writes a value to a storage slot in specified account

:param storage_address: an account address
:param offset: the storage slot to use.
:type offset: int or BitVec
:param value: the value to write
:type value: int or BitVec


<EOL>return pow(base, exponent, TT256)<EOL>

Exponential operation
The zero-th power of zero 0^0 is defined to be one


for tx in reversed(self.transactions):<EOL><INDENT>if tx.depth == <NUM_LIT:0>:<EOL><INDENT>return tx<EOL><DEDENT><DEDENT>return None<EOL>


try:<EOL><INDENT>tx, _, _, _, _ = self._callstack[-<NUM_LIT:1>]<EOL>if tx.result is not None:<EOL><INDENT>return None<EOL><DEDENT>return tx<EOL><DEDENT>except IndexError:<EOL><INDENT>return None<EOL><DEDENT>


return Operators.ITEBV(<NUM_LIT>, Operators.UGT(a, b), <NUM_LIT:1>, <NUM_LIT:0>)<EOL>


a = operands[<NUM_LIT:0>]<EOL>b = operands[-<NUM_LIT:1>]<EOL>return (b,) + operands[<NUM_LIT:1>:-<NUM_LIT:1>] + (a,)<EOL>


return a + b<EOL>


self.pc = dest<EOL>self._set_check_jmpdest()<EOL>


last_pc, last_gas, last_instruction, last_arguments, fee, allocated = self._checkpoint_data<EOL>self._push_arguments(last_arguments)<EOL>self._gas = last_gas<EOL>self._pc = last_pc<EOL>self._allocated = allocated<EOL>self._checkpoint_data = None<EOL>

Revert the stack, gas, pc and memory allocation so it looks like before executing the instruction


storage_address = self.address<EOL>self._publish('<STR_LIT>', storage_address, offset, value)<EOL>if istainted(self.pc):<EOL><INDENT>for taint in get_taints(self.pc):<EOL><INDENT>value = taint_with(value, taint)<EOL><DEDENT><DEDENT>self.world.set_storage_data(storage_address, offset, value)<EOL>self._publish('<STR_LIT>', storage_address, offset, value)<EOL>


return self.world.block_coinbase()<EOL>


return self.world.block_difficulty()<EOL>


def _get_memfee(self, address, size=<NUM_LIT:1>):

if not issymbolic(size) and size == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>address = self.safe_add(address, size)<EOL>allocated = self.allocated<EOL>GMEMORY = <NUM_LIT:3><EOL>GQUADRATICMEMDENOM = <NUM_LIT>  <EOL>old_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(allocated, <NUM_LIT>), <NUM_LIT:32>), <NUM_LIT>)<EOL>new_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(address, <NUM_LIT>), <NUM_LIT:32>), <NUM_LIT>)<EOL>old_totalfee = self.safe_mul(old_size, GMEMORY) + Operators.UDIV(self.safe_mul(old_size, old_size), GQUADRATICMEMDENOM)<EOL>new_totalfee = self.safe_mul(new_size, GMEMORY) + Operators.UDIV(self.safe_mul(new_size, new_size), GQUADRATICMEMDENOM)<EOL>memfee = new_totalfee - old_totalfee<EOL>flag = Operators.UGT(new_totalfee, old_totalfee)<EOL>return Operators.ITEBV(<NUM_LIT>, size == <NUM_LIT:0>, <NUM_LIT:0>, Operators.ITEBV(<NUM_LIT>, flag, memfee, <NUM_LIT:0>))<EOL>

This calculates the amount of extra gas needed for accessing to
previously unused memory.

:param address: base memory offset
:param size: size of the memory access


def start_transaction(self, sort, address, price=None, data=None, caller=None, value=<NUM_LIT:0>, gas=<NUM_LIT>):

assert self._pending_transaction is None, "<STR_LIT>"<EOL>self._pending_transaction = PendingTransaction(sort, address, price, data, caller, value, gas)<EOL>

Initiate a transaction
:param sort: the type of transaction. CREATE or CALL or DELEGATECALL
:param address: the address of the account which owns the code that is executing.
:param price: the price of gas in the transaction that originated this execution.
:param data: the byte array that is the input data to this execution
:param caller: the address of the account which caused the code to be executing. A 160-bit code used for identifying Accounts
:param value: the value, in Wei, passed to this account as part of the same procedure as execution. One Ether is defined as being 10**18 Wei.
:param bytecode: the byte array that is the machine code to be executed.
:param gas: gas budget for this transaction.


<EOL>if self._checkpoint_data is None:<EOL><INDENT>if not self._published_pre_instruction_events:<EOL><INDENT>self._published_pre_instruction_events = True<EOL>self._publish('<STR_LIT>', self.pc)<EOL>self._publish('<STR_LIT>', self.pc, self.instruction)<EOL>self._publish('<STR_LIT>', self.instruction, self._top_arguments())<EOL><DEDENT>pc = self.pc<EOL>instruction = self.instruction<EOL>old_gas = self.gas<EOL>allocated = self._allocated<EOL>arguments = self._pop_arguments()<EOL>fee = self._calculate_gas(*arguments)<EOL>self._checkpoint_data = (pc, old_gas, instruction, arguments, fee, allocated)<EOL><DEDENT>return self._checkpoint_data<EOL>

Save and/or get a state checkpoint previous to current instruction


return (operands[-<NUM_LIT:1>],) + operands<EOL>


return value<EOL>


return a | b<EOL>


if istainted(self.pc):<EOL><INDENT>for taint in get_taints(self.pc):<EOL><INDENT>value = taint_with(value, taint)<EOL><DEDENT><DEDENT>self._allocate(address, <NUM_LIT:32>)<EOL>self._store(address, value, <NUM_LIT:32>)<EOL>


def dump(self, stream, state, mevm, conc_tx=None):

from ..ethereum import ABI  <EOL>from ..ethereum.manticore import flagged<EOL>is_something_symbolic = False<EOL>if conc_tx is None:<EOL><INDENT>conc_tx = self.concretize(state)<EOL><DEDENT>stream.write("<STR_LIT>" % (self.sort, self.depth))<EOL>caller_solution = conc_tx.caller<EOL>caller_name = mevm.account_name(caller_solution)<EOL>stream.write("<STR_LIT>" % (caller_name, caller_solution, flagged(issymbolic(self.caller))))<EOL>address_solution = conc_tx.address<EOL>address_name = mevm.account_name(address_solution)<EOL>stream.write("<STR_LIT>" % (address_name, address_solution, flagged(issymbolic(self.address))))<EOL>stream.write("<STR_LIT>" % (conc_tx.value, flagged(issymbolic(self.value))))<EOL>stream.write("<STR_LIT>" % (conc_tx.gas, flagged(issymbolic(self.gas))))<EOL>tx_data = conc_tx.data<EOL>stream.write("<STR_LIT>".format(binascii.hexlify(tx_data).decode(), flagged(issymbolic(self.data))))<EOL>if self.return_data is not None:<EOL><INDENT>return_data = conc_tx.return_data<EOL>stream.write("<STR_LIT>".format(binascii.hexlify(return_data).decode(), flagged(issymbolic(self.return_data))))<EOL><DEDENT>metadata = mevm.get_metadata(self.address)<EOL>if self.sort == '<STR_LIT>':<EOL><INDENT>if metadata is not None:<EOL><INDENT>conc_args_data = conc_tx.data[len(metadata._init_bytecode):]<EOL>arguments = ABI.deserialize(metadata.get_constructor_arguments(), conc_args_data)<EOL>is_argument_symbolic = any(map(issymbolic, arguments))  <EOL>stream.write('<STR_LIT>')<EOL>stream.write("<STR_LIT>")<EOL>stream.write('<STR_LIT:U+002C>'.join(map(repr, map(state.solve_one, arguments))))  <EOL>stream.write('<STR_LIT>' % (self.result, flagged(is_argument_symbolic)))<EOL><DEDENT><DEDENT>if self.sort == '<STR_LIT>':<EOL><INDENT>if metadata is not None:<EOL><INDENT>calldata = conc_tx.data<EOL>is_calldata_symbolic = issymbolic(self.data)<EOL>function_id = calldata[:<NUM_LIT:4>]  <EOL>signature = metadata.get_func_signature(function_id)<EOL>function_name = metadata.get_func_name(function_id)<EOL>if signature:<EOL><INDENT>_, arguments = ABI.deserialize(signature, calldata)<EOL><DEDENT>else:<EOL><INDENT>arguments = (calldata,)<EOL><DEDENT>return_data = None<EOL>if self.result == '<STR_LIT>':<EOL><INDENT>ret_types = metadata.get_func_return_types(function_id)<EOL>return_data = conc_tx.return_data<EOL>return_values = ABI.deserialize(ret_types, return_data)  <EOL><DEDENT>is_return_symbolic = issymbolic(self.return_data)<EOL>stream.write('<STR_LIT:\n>')<EOL>stream.write("<STR_LIT>")<EOL>stream.write("<STR_LIT>" % function_name)<EOL>stream.write('<STR_LIT:U+002C>'.join(map(repr, arguments)))<EOL>stream.write('<STR_LIT>' % (self.result, flagged(is_calldata_symbolic)))<EOL>if return_data is not None:<EOL><INDENT>if len(return_values) == <NUM_LIT:1>:<EOL><INDENT>return_values = return_values[<NUM_LIT:0>]<EOL><DEDENT>stream.write('<STR_LIT>' % (return_values, flagged(is_return_symbolic)))<EOL><DEDENT>is_something_symbolic = is_calldata_symbolic or is_return_symbolic<EOL><DEDENT><DEDENT>stream.write('<STR_LIT>')<EOL>return is_something_symbolic<EOL>

Concretize and write a human readable version of the transaction into the stream. Used during testcase
generation.

:param stream: Output stream to write to. Typically a file.
:param manticore.ethereum.State state: state that the tx exists in
:param manticore.ethereum.ManticoreEVM mevm: manticore instance
:return:


<EOL>s0, s1 = to_signed(a), to_signed(b)<EOL>return Operators.ITEBV(<NUM_LIT>, s0 < s1, <NUM_LIT:1>, <NUM_LIT:0>)<EOL>


def block_hash(self, block_number=None, force_recent=True):

if block_number is None:<EOL><INDENT>block_number = self.block_number() - <NUM_LIT:1><EOL><DEDENT>value = sha3.keccak_256((repr(block_number) + '<STR_LIT>').encode()).hexdigest()<EOL>value = int(value, <NUM_LIT:16>)<EOL>if force_recent:<EOL><INDENT>bnmax = Operators.ITEBV(<NUM_LIT>, self.block_number() > <NUM_LIT>, <NUM_LIT>, self.block_number())<EOL>value = Operators.ITEBV(<NUM_LIT>, Operators.OR(block_number >= self.block_number(), block_number < bnmax), <NUM_LIT:0>, value)<EOL><DEDENT>return value<EOL>

Calculates a block's hash
:param block_number: the block number for which to calculate the hash, defaulting to the most recent block
:param force_recent: if True (the default) return zero for any block that is in the future or older than 256 blocks
:return: the block hash


return len(self.world.get_code(account))<EOL>


self.pc = Operators.ITEBV(<NUM_LIT>, cond != <NUM_LIT:0>, dest, self.pc + self.instruction.size)<EOL>self._set_check_jmpdest(cond != <NUM_LIT:0>)<EOL>


EXP_SUPPLEMENTAL_GAS = <NUM_LIT:10>   <EOL>def nbytes(e):<EOL><INDENT>result = <NUM_LIT:0><EOL>for i in range(<NUM_LIT:32>):<EOL><INDENT>result = Operators.ITEBV(<NUM_LIT>, Operators.EXTRACT(e, i * <NUM_LIT:8>, <NUM_LIT:8>) != <NUM_LIT:0>, i + <NUM_LIT:1>, result)<EOL><DEDENT>return result<EOL><DEDENT>return EXP_SUPPLEMENTAL_GAS * nbytes(exponent)<EOL>


should_check_jumpdest = self._check_jumpdest<EOL>if issymbolic(should_check_jumpdest):<EOL><INDENT>should_check_jumpdest_solutions = solver.get_all_values(self.constraints, should_check_jumpdest)<EOL>if len(should_check_jumpdest_solutions) != <NUM_LIT:1>:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>should_check_jumpdest = should_check_jumpdest_solutions[<NUM_LIT:0>]<EOL><DEDENT>if should_check_jumpdest:<EOL><INDENT>self._check_jumpdest = False<EOL>pc = self.pc.value if isinstance(self.pc, Constant) else self.pc<EOL>if pc not in self._valid_jumpdests:<EOL><INDENT>raise InvalidOpcode()<EOL><DEDENT><DEDENT>

If the previous instruction was a JUMP/JUMPI and the conditional was
True, this checks that the current instruction must be a JUMPDEST.

Here, if symbolic, the conditional `self._check_jumpdest` would be
already constrained to a single concrete value.


if len(self.stack) == <NUM_LIT:0>:<EOL><INDENT>raise StackUnderflow()<EOL><DEDENT>return self.stack.pop()<EOL>


if len(self.transactions):<EOL><INDENT>return self.transactions[-<NUM_LIT:1>]<EOL><DEDENT>return None<EOL>


def read_code(self, address, size=<NUM_LIT:1>):

assert address < len(self.bytecode)<EOL>value = self.bytecode[address:address + size]<EOL>if len(value) < size:<EOL><INDENT>value += '<STR_LIT:\x00>' * (size - len(value))  <EOL><DEDENT>return value<EOL>

Read size byte from bytecode.
If less than size bytes are available result will be pad with \x00


return self.world.tx_gasprice()<EOL>


def new_address(self, sender=None, nonce=None):

if sender is not None and nonce is None:<EOL><INDENT>nonce = self.get_nonce(sender)<EOL><DEDENT>new_address = self.calculate_new_address(sender, nonce)<EOL>if sender is None and new_address in self:<EOL><INDENT>return self.new_address(sender, nonce)<EOL><DEDENT>return new_address<EOL>


return Operators.ZEXTEND(self.world.tx_origin(), <NUM_LIT>)<EOL>


self.files[fd] = None<EOL>

Closes a file descriptor
:rtype: int
:param fd: the file descriptor to close.
:return: C{0} on success.


connections = self.connections<EOL>if connections(fd) and self.twait[connections(fd)]:<EOL><INDENT>procid = random.sample(self.twait[connections(fd)], <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>self.awake(procid)<EOL><DEDENT>

Awake one process waiting to receive data on fd


filename = "<STR_LIT>"<EOL>for i in range(<NUM_LIT:0>, <NUM_LIT>):<EOL><INDENT>c = Operators.CHR(cpu.read_int(buf + i, <NUM_LIT:8>))<EOL>if c == '<STR_LIT:\x00>':<EOL><INDENT>break<EOL><DEDENT>filename += c<EOL><DEDENT>return filename<EOL>

Reads a null terminated concrete buffer form memory
:todo: FIX. move to cpu or memory


return self._open(self.files[fd])<EOL>

Duplicates a file descriptor
:rtype: int
:param fd: the file descriptor to close.
:return: C{0} on success.


try:<EOL><INDENT>self.current.execute()<EOL>self.clocks += <NUM_LIT:1><EOL>if self.clocks % <NUM_LIT> == <NUM_LIT:0>:<EOL><INDENT>self.check_timers()<EOL>self.sched()<EOL><DEDENT><DEDENT>except Interruption as e:<EOL><INDENT>if e.N != <NUM_LIT>:<EOL><INDENT>raise<EOL><DEDENT>try:<EOL><INDENT>self.int80(self.current)<EOL><DEDENT>except RestartSyscall:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return True<EOL>

Execute one cpu instruction in the current thread (only one supported).
:rtype: bool
:return: C{True}

:todo: This is where we could implement a simple schedule.


def sys_receive(self, cpu, fd, buf, count, rx_bytes):

data = '<STR_LIT>'<EOL>if count != <NUM_LIT:0>:<EOL><INDENT>if not self._is_open(fd):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return Decree.CGC_EBADF<EOL><DEDENT>if buf not in cpu.memory:  <EOL><INDENT>logger.info("<STR_LIT>")<EOL>return Decree.CGC_EFAULT<EOL><DEDENT>if fd > <NUM_LIT:2> and self.files[fd].is_empty():<EOL><INDENT>cpu.PC -= cpu.instruction.size<EOL>self.wait([fd], [], None)<EOL>raise RestartSyscall()<EOL><DEDENT>data = self.files[fd].receive(count)<EOL>self.syscall_trace.append(("<STR_LIT>", fd, data))<EOL>cpu.write_bytes(buf, data)<EOL>self.signal_receive(fd)<EOL><DEDENT>if rx_bytes:<EOL><INDENT>if rx_bytes not in cpu.memory:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return Decree.CGC_EFAULT<EOL><DEDENT>cpu.write_int(rx_bytes, len(data), <NUM_LIT:32>)<EOL><DEDENT>logger.info("<STR_LIT>" % (fd, buf, count, rx_bytes, repr(data)[:min(count, <NUM_LIT:10>)], len(data)))<EOL>return <NUM_LIT:0><EOL>

receive - receive bytes from a file descriptor

            The receive system call reads up to count bytes from file descriptor fd to the
            buffer pointed to by buf. If count is zero, receive returns 0 and optionally
            sets *rx_bytes to zero.

            :param cpu: current CPU.
            :param fd: a valid file descriptor
            :param buf: a memory buffer
            :param count: max number of bytes to receive
            :param rx_bytes: if valid, points to the actual number of bytes received
            :return: 0            Success
                     EBADF        fd is not a valid file descriptor or is not open
                     EFAULT       buf or rx_bytes points to an invalid address.


def sys_fdwait(self, cpu, nfds, readfds, writefds, timeout, readyfds):

logger.debug("<STR_LIT>" % (nfds, readfds, writefds, timeout, readyfds))<EOL>if timeout:<EOL><INDENT>if timeout not in cpu.memory:  <EOL><INDENT>logger.info("<STR_LIT>")<EOL>return Decree.CGC_EFAULT<EOL><DEDENT><DEDENT>if readyfds:<EOL><INDENT>if readyfds not in cpu.memory:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return Decree.CGC_EFAULT<EOL><DEDENT><DEDENT>writefds_wait = set()<EOL>writefds_ready = set()<EOL>fds_bitsize = (nfds + <NUM_LIT:7>) & ~<NUM_LIT:7><EOL>if writefds:<EOL><INDENT>if writefds not in cpu.memory:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return Decree.CGC_EFAULT<EOL><DEDENT>bits = cpu.read_int(writefds, fds_bitsize)<EOL>for fd in range(nfds):<EOL><INDENT>if (bits & <NUM_LIT:1> << fd):<EOL><INDENT>if self.files[fd].is_full():<EOL><INDENT>writefds_wait.add(fd)<EOL><DEDENT>else:<EOL><INDENT>writefds_ready.add(fd)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>readfds_wait = set()<EOL>readfds_ready = set()<EOL>if readfds:<EOL><INDENT>if readfds not in cpu.memory:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return Decree.CGC_EFAULT<EOL><DEDENT>bits = cpu.read_int(readfds, fds_bitsize)<EOL>for fd in range(nfds):<EOL><INDENT>if (bits & <NUM_LIT:1> << fd):<EOL><INDENT>if self.files[fd].is_empty():<EOL><INDENT>readfds_wait.add(fd)<EOL><DEDENT>else:<EOL><INDENT>readfds_ready.add(fd)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>n = len(readfds_ready) + len(writefds_ready)<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>if timeout != <NUM_LIT:0>:<EOL><INDENT>seconds = cpu.read_int(timeout, <NUM_LIT:32>)<EOL>microseconds = cpu.read_int(timeout + <NUM_LIT:4>, <NUM_LIT:32>)<EOL>logger.info("<STR_LIT>", repr(<EOL>list(readfds_wait)), repr(list(writefds_wait)), microseconds + <NUM_LIT:1000> * seconds)<EOL>to = microseconds + <NUM_LIT:1000> * seconds<EOL><DEDENT>else:<EOL><INDENT>to = None<EOL>logger.info("<STR_LIT>",<EOL>repr(list(readfds_wait)), repr(list(writefds_wait)))<EOL><DEDENT>cpu.PC -= cpu.instruction.size<EOL>self.wait(readfds_wait, writefds_wait, to)<EOL>raise RestartSyscall()  <EOL><DEDENT>if readfds:<EOL><INDENT>bits = <NUM_LIT:0><EOL>for fd in readfds_ready:<EOL><INDENT>bits |= <NUM_LIT:1> << fd<EOL><DEDENT>for byte in range(<NUM_LIT:0>, nfds, <NUM_LIT:8>):<EOL><INDENT>cpu.write_int(readfds, (bits >> byte) & <NUM_LIT>, <NUM_LIT:8>)<EOL><DEDENT><DEDENT>if writefds:<EOL><INDENT>bits = <NUM_LIT:0><EOL>for fd in writefds_ready:<EOL><INDENT>bits |= <NUM_LIT:1> << fd<EOL><DEDENT>for byte in range(<NUM_LIT:0>, nfds, <NUM_LIT:8>):<EOL><INDENT>cpu.write_int(writefds, (bits >> byte) & <NUM_LIT>, <NUM_LIT:8>)<EOL><DEDENT><DEDENT>logger.info("<STR_LIT>", readyfds)<EOL>if readyfds:<EOL><INDENT>cpu.write_int(readyfds, n, <NUM_LIT:32>)<EOL><DEDENT>self.syscall_trace.append(("<STR_LIT>", -<NUM_LIT:1>, None))<EOL>return <NUM_LIT:0><EOL>

fdwait - wait for file descriptors to become ready


syscalls = {<NUM_LIT>: self.sys_terminate,<EOL><NUM_LIT>: self.sys_transmit,<EOL><NUM_LIT>: self.sys_receive,<EOL><NUM_LIT>: self.sys_fdwait,<EOL><NUM_LIT>: self.sys_allocate,<EOL><NUM_LIT>: self.sys_deallocate,<EOL><NUM_LIT>: self.sys_random,<EOL>}<EOL>if cpu.EAX not in syscalls.keys():<EOL><INDENT>raise TerminateState(f"<STR_LIT>")<EOL><DEDENT>func = syscalls[cpu.EAX]<EOL>logger.debug("<STR_LIT>", func.__name__, func.__code__.co_argcount)<EOL>nargs = func.__code__.co_argcount<EOL>args = [cpu, cpu.EBX, cpu.ECX, cpu.EDX, cpu.ESI, cpu.EDI, cpu.EBP]<EOL>cpu.EAX = func(*args[:nargs - <NUM_LIT:1>])<EOL>

32 bit dispatcher.
:param cpu: current CPU.
_terminate, transmit, receive, fdwait, allocate, deallocate and random


def __init__(self, constraints, programs, symbolic_random=None):

self.random = <NUM_LIT:0><EOL>self._constraints = constraints<EOL>super().__init__(programs)<EOL>

Builds a symbolic extension of a Decree OS
:param constraints: a constraint set
:param cpus: CPU for this platform
:param mem: memory for this platform


def sys_transmit(self, cpu, fd, buf, count, tx_bytes):

data = []<EOL>if count != <NUM_LIT:0>:<EOL><INDENT>if not self._is_open(fd):<EOL><INDENT>logger.error("<STR_LIT>", fd)<EOL>return Decree.CGC_EBADF<EOL><DEDENT>if buf not in cpu.memory or (buf + count) not in cpu.memory:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>return Decree.CGC_EFAULT<EOL><DEDENT>if fd > <NUM_LIT:2> and self.files[fd].is_full():<EOL><INDENT>cpu.PC -= cpu.instruction.size<EOL>self.wait([], [fd], None)<EOL>raise RestartSyscall()<EOL><DEDENT>for i in range(<NUM_LIT:0>, count):<EOL><INDENT>value = Operators.CHR(cpu.read_int(buf + i, <NUM_LIT:8>))<EOL>if not isinstance(value, str):<EOL><INDENT>logger.debug("<STR_LIT>", fd)<EOL><DEDENT>data.append(value)<EOL><DEDENT>self.files[fd].transmit(data)<EOL>logger.info("<STR_LIT>" % (fd, buf, count, tx_bytes, '<STR_LIT>'.join([str(x) for x in data])))<EOL>self.syscall_trace.append(("<STR_LIT>", fd, data))<EOL>self.signal_transmit(fd)<EOL><DEDENT>if tx_bytes:<EOL><INDENT>if tx_bytes not in cpu.memory:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>return Decree.CGC_EFAULT<EOL><DEDENT>cpu.write_int(tx_bytes, len(data), <NUM_LIT:32>)<EOL><DEDENT>return <NUM_LIT:0><EOL>

transmit - send bytes through a file descriptor
          The  transmit system call writes up to count bytes from the buffer pointed
          to by buf to the file descriptor fd. If count is zero, transmit returns 0
          and optionally sets *tx_bytes to zero.

          :param cpu           current CPU
          :param fd            a valid file descriptor
          :param buf           a memory buffer
          :param count         number of bytes to send
          :param tx_bytes      if valid, points to the actual number of bytes transmitted
          :return: 0            Success
                   EBADF        fd is not a valid file descriptor or is not open.
                   EFAULT       buf or tx_bytes points to an invalid address.


if issymbolic(fd):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>cpu.PC = cpu.PC - cpu.instruction.size<EOL>raise SymbolicSyscallArgument(cpu, <NUM_LIT:0>)<EOL><DEDENT>if issymbolic(buf):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>cpu.PC = cpu.PC - cpu.instruction.size<EOL>raise SymbolicSyscallArgument(cpu, <NUM_LIT:1>)<EOL><DEDENT>if issymbolic(count):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>cpu.PC = cpu.PC - cpu.instruction.size<EOL>raise SymbolicSyscallArgument(cpu, <NUM_LIT:2>)<EOL><DEDENT>if issymbolic(rx_bytes):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>cpu.PC = cpu.PC - cpu.instruction.size<EOL>raise SymbolicSyscallArgument(cpu, <NUM_LIT:3>)<EOL><DEDENT>return super().sys_receive(cpu, fd, buf, count, rx_bytes)<EOL>


def sys_lseek(self, fd, offset, whence):

signed_offset = self._to_signed_dword(offset)<EOL>try:<EOL><INDENT>return self._get_fd(fd).seek(signed_offset, whence)<EOL><DEDENT>except FdError as e:<EOL><INDENT>logger.info(("<STR_LIT>"<EOL>"<STR_LIT>"))<EOL>return -e.err<EOL><DEDENT>

lseek - reposition read/write file offset

The lseek() function repositions the file offset of the open file description associated
with the file descriptor fd to the argument offset according to the directive whence

:param fd: a valid file descriptor
:param offset: the offset in bytes
:param whence: SEEK_SET: The file offset is set to offset bytes.
               SEEK_CUR: The file offset is set to its current location plus offset bytes.
               SEEK_END: The file offset is set to the size of the file plus offset bytes.

:return: offset from file beginning, or EBADF (fd is not a valid file descriptor or is not open)


return <NUM_LIT:1000><EOL>

Gets user identity.
:rtype: int

:return: This call returns C{1000} for all the users.


logger.debug("<STR_LIT>")<EOL>return -<NUM_LIT:1><EOL>

System call not implemented.
:rtype: int

:return: C{-1}


def wait(self, readfds, writefds, timeout):

logger.debug("<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>for fd in readfds:<EOL><INDENT>self.rwait[fd].add(self._current)<EOL><DEDENT>for fd in writefds:<EOL><INDENT>self.twait[fd].add(self._current)<EOL><DEDENT>if timeout is not None:<EOL><INDENT>self.timers[self._current] = self.clocks + timeout<EOL><DEDENT>procid = self._current<EOL>next_index = (self.running.index(procid) + <NUM_LIT:1>) % len(self.running)<EOL>self._current = self.running[next_index]<EOL>logger.debug(f"<STR_LIT>")<EOL>logger.debug(f"<STR_LIT>")<EOL>self.running.remove(procid)<EOL>if self._current not in self.running:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>self._current = None<EOL>self.check_timers()<EOL><DEDENT>

Wait for file descriptors or timeout.
            Adds the current process in the correspondent waiting list and
            yield the cpu to another running process.


return self.sys_exit_group(error_code)<EOL>


def __init__(self, program, argv=None, envp=None, disasm='<STR_LIT>', **kwargs):

super().__init__(path=program, **kwargs)<EOL>self.program = program<EOL>self.clocks = <NUM_LIT:0><EOL>self.files = []<EOL>self._closed_files = []<EOL>self.syscall_trace = []<EOL>self.programs = program<EOL>self.disasm = disasm<EOL>self.envp = envp<EOL>self.argv = argv<EOL>self._rlimits = {<EOL>resource.RLIMIT_NOFILE: (<NUM_LIT>, <NUM_LIT>),<EOL>resource.RLIMIT_STACK: (<NUM_LIT> * <NUM_LIT>, <NUM_LIT:0>)<EOL>}<EOL>if program is not None:<EOL><INDENT>self.elf = ELFFile(open(program, '<STR_LIT:rb>'))<EOL>self.arch = {'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>'}[self.elf.get_machine_arch()]<EOL>self._init_cpu(self.arch)<EOL>self._init_std_fds()<EOL>self._execve(program, argv, envp)<EOL><DEDENT>

Builds a Linux OS platform
:param string program: The path to ELF binary
:param string disasm: Disassembler to be used
:param list argv: The argv array; not including binary.
:param list envp: The ENV variables.
:ivar files: List of active file descriptors
:type files: list[Socket] or list[File]


def sys_rt_sigaction(self, signum, act, oldact):

return self.sys_sigaction(signum, act, oldact)<EOL>


return self.pos<EOL>

Returns the read/write file offset
:rtype: int
:return: the read/write file offset.


return <NUM_LIT:1000><EOL>

Gets user identity.
:rtype: int

:return: this call returns C{1000} for all the users.


size = min(len(data), self.max_size - self.pos)<EOL>for i in range(self.pos, self.pos + size):<EOL><INDENT>self.array[i] = data[i - self.pos]<EOL><DEDENT>

Writes the symbolic bytes in C{data} onto the file.


try:<EOL><INDENT>stat = self._get_fd(fd).stat()<EOL><DEDENT>except FdError as e:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return -e.err<EOL><DEDENT>def add(width, val):<EOL><INDENT>fformat = {<NUM_LIT:2>: '<STR_LIT:H>', <NUM_LIT:4>: '<STR_LIT:L>', <NUM_LIT:8>: '<STR_LIT>'}[width]<EOL>return struct.pack('<STR_LIT:<>' + fformat, val)<EOL><DEDENT>def to_timespec(ts):<EOL><INDENT>return struct.pack('<STR_LIT>', int(ts), int(ts % <NUM_LIT:1> * <NUM_LIT>))<EOL><DEDENT>bufstat = add(<NUM_LIT:8>, stat.st_dev)        <EOL>bufstat += add(<NUM_LIT:8>, stat.st_ino)        <EOL>bufstat += add(<NUM_LIT:4>, stat.st_mode)       <EOL>bufstat += add(<NUM_LIT:4>, stat.st_nlink)      <EOL>bufstat += add(<NUM_LIT:4>, stat.st_uid)        <EOL>bufstat += add(<NUM_LIT:4>, stat.st_gid)        <EOL>bufstat += add(<NUM_LIT:8>, stat.st_rdev)       <EOL>bufstat += add(<NUM_LIT:8>, <NUM_LIT:0>)                  <EOL>bufstat += add(<NUM_LIT:8>, stat.st_size)       <EOL>bufstat += add(<NUM_LIT:4>, stat.st_blksize)    <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)                  <EOL>bufstat += add(<NUM_LIT:8>, stat.st_blocks)     <EOL>bufstat += to_timespec(stat.st_atime)  <EOL>bufstat += to_timespec(stat.st_mtime)  <EOL>bufstat += to_timespec(stat.st_ctime)  <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)                   <EOL>bufstat += add(<NUM_LIT:4>, <NUM_LIT:0>)                   <EOL>self.current.write_bytes(buf, bufstat)<EOL>return <NUM_LIT:0><EOL>

Determines information about a file based on its file descriptor (for Linux 64 bits).
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success, EBADF when called with bad fd
:todo: Fix device number.


if None in self.files:<EOL><INDENT>fd = self.files.index(None)<EOL>self.files[fd] = f<EOL><DEDENT>else:<EOL><INDENT>fd = len(self.files)<EOL>self.files.append(f)<EOL><DEDENT>return fd<EOL>

Adds a file descriptor to the current file descriptor list

:rtype: int
:param f: the file descriptor to add.
:return: the index of the file descriptor in the file descr. list


try:<EOL><INDENT>self.current.execute()<EOL>self.clocks += <NUM_LIT:1><EOL>if self.clocks % <NUM_LIT> == <NUM_LIT:0>:<EOL><INDENT>self.check_timers()<EOL>self.sched()<EOL><DEDENT><DEDENT>except (Interruption, Syscall) as e:<EOL><INDENT>try:<EOL><INDENT>self.syscall()<EOL>if hasattr(e, '<STR_LIT>'):<EOL><INDENT>e.on_handled()<EOL><DEDENT><DEDENT>except RestartSyscall:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return True<EOL>


return self._exit(f"<STR_LIT>")<EOL>

Exits all threads in a process
:raises Exception: 'Finished'


logger.debug(f"<STR_LIT>")<EOL>for wait_list in self.rwait:<EOL><INDENT>if procid in wait_list:<EOL><INDENT>wait_list.remove(procid)<EOL><DEDENT><DEDENT>for wait_list in self.twait:<EOL><INDENT>if procid in wait_list:<EOL><INDENT>wait_list.remove(procid)<EOL><DEDENT><DEDENT>self.timers[procid] = None<EOL>self.running.append(procid)<EOL>if self._current is None:<EOL><INDENT>self._current = procid<EOL><DEDENT>

Remove procid from waitlists and reestablish it in the running list


cpu = self.current<EOL>ptrsize = cpu.address_bit_size<EOL>sizeof_iovec = <NUM_LIT:2> * (ptrsize // <NUM_LIT:8>)<EOL>total = <NUM_LIT:0><EOL>try:<EOL><INDENT>write_fd = self._get_fd(fd)<EOL><DEDENT>except FdError as e:<EOL><INDENT>logger.error(f"<STR_LIT>")<EOL>return -e.err<EOL><DEDENT>for i in range(<NUM_LIT:0>, count):<EOL><INDENT>buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize)<EOL>size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // <NUM_LIT:2>), ptrsize)<EOL>data = [Operators.CHR(cpu.read_int(buf + i, <NUM_LIT:8>)) for i in range(size)]<EOL>data = self._transform_write_data(data)<EOL>write_fd.write(data)<EOL>self.syscall_trace.append(("<STR_LIT>", fd, data))<EOL>total += size<EOL><DEDENT>return total<EOL>

Works just like C{sys_write} except that multiple buffers are written out.
:rtype: int

:param fd: the file descriptor of the file to write.
:param iov: the buffer where the the bytes to write are taken.
:param count: amount of C{iov} buffers to write into the file.
:return: the amount of bytes written in total.


def sys_mmap(self, address, size, prot, flags, fd, offset):

if address == <NUM_LIT:0>:<EOL><INDENT>address = None<EOL><DEDENT>cpu = self.current<EOL>if flags & <NUM_LIT>:<EOL><INDENT>cpu.memory.munmap(address, size)<EOL><DEDENT>perms = perms_from_protflags(prot)<EOL>if flags & <NUM_LIT>:<EOL><INDENT>result = cpu.memory.mmap(address, size, perms)<EOL><DEDENT>elif fd == <NUM_LIT:0>:<EOL><INDENT>assert offset == <NUM_LIT:0><EOL>result = cpu.memory.mmap(address, size, perms)<EOL>data = self.files[fd].read(size)<EOL>cpu.write_bytes(result, data)<EOL><DEDENT>else:<EOL><INDENT>result = cpu.memory.mmapFile(address, size, perms, self.files[fd].name, offset)<EOL><DEDENT>actually_mapped = f'<STR_LIT>'<EOL>if address is None or result != address:<EOL><INDENT>address = address or <NUM_LIT:0><EOL>actually_mapped += f'<STR_LIT>'<EOL><DEDENT>if flags & <NUM_LIT> != <NUM_LIT:0> and result != address:<EOL><INDENT>cpu.memory.munmap(result, size)<EOL>result = -<NUM_LIT:1><EOL><DEDENT>return result<EOL>

Creates a new mapping in the virtual address space of the calling process.
:rtype: int

:param address: the starting address for the new mapping. This address is used as hint unless the
                flag contains C{MAP_FIXED}.
:param size: the length of the mapping.
:param prot: the desired memory protection of the mapping.
:param flags: determines whether updates to the mapping are visible to other
              processes mapping the same region, and whether updates are carried
              through to the underlying file.
:param fd: the contents of a file mapping are initialized using C{size} bytes starting at
           offset C{offset} in the file referred to by the file descriptor C{fd}.
:param offset: the contents of a file mapping are initialized using C{size} bytes starting at
               offset C{offset} in the file referred to by the file descriptor C{fd}.
:return:
        - C{-1} in case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address.
        - the address of the new mapping (that must be the same as address in case you included C{MAP_FIXED} in flags).
:todo: handle exception.


return self._open(self.files[fd])<EOL>

Duplicates a file descriptor
:rtype: int
:param fd: the file descriptor to duplicate.
:return: C{0} on success.


try:<EOL><INDENT>self.files[fd].close()<EOL>self._closed_files.append(self.files[fd])  <EOL>self.files[fd] = None<EOL><DEDENT>except IndexError:<EOL><INDENT>raise FdError(f"<STR_LIT>")<EOL><DEDENT>

Removes a file descriptor from the file descriptor list
:rtype: int
:param fd: the file descriptor to close.
:return: C{0} on success.


def sys_rename(self, oldnamep, newnamep):

oldname = self.current.read_string(oldnamep)<EOL>newname = self.current.read_string(newnamep)<EOL>ret = <NUM_LIT:0><EOL>try:<EOL><INDENT>os.rename(oldname, newname)<EOL><DEDENT>except OSError as e:<EOL><INDENT>ret = -e.errno<EOL><DEDENT>return ret<EOL>

Rename filename `oldnamep` to `newnamep`.

:param int oldnamep: pointer to oldname
:param int newnamep: pointer to newname


super().__setstate__(state)<EOL>self.input = Socket()<EOL>self.input.buffer = state['<STR_LIT:input>']<EOL>self.output = Socket()<EOL>self.output.buffer = state['<STR_LIT>']<EOL>self.files = []<EOL>for ty, file_or_buffer in state['<STR_LIT>']:<EOL><INDENT>if ty == '<STR_LIT>':<EOL><INDENT>f = Socket()<EOL>f.buffer = file_or_buffer<EOL>self.files.append(f)<EOL><DEDENT>else:<EOL><INDENT>self.files.append(file_or_buffer)<EOL><DEDENT><DEDENT>self.files[<NUM_LIT:0>].peer = self.output<EOL>self.files[<NUM_LIT:1>].peer = self.output<EOL>self.files[<NUM_LIT:2>].peer = self.output<EOL>self._closed_files = state['<STR_LIT>']<EOL>self.input.peer = self.files[<NUM_LIT:0>]<EOL>self._rlimits = state['<STR_LIT>']<EOL>self.procs = state['<STR_LIT>']<EOL>self._current = state['<STR_LIT>']<EOL>self.running = state['<STR_LIT>']<EOL>self.rwait = state['<STR_LIT>']<EOL>self.twait = state['<STR_LIT>']<EOL>self.timers = state['<STR_LIT>']<EOL>self.clocks = state['<STR_LIT>']<EOL>self.syscall_trace = state['<STR_LIT>']<EOL>self.argv = state['<STR_LIT>']<EOL>self.envp = state['<STR_LIT>']<EOL>self.base = state['<STR_LIT>']<EOL>self.elf_bss = state['<STR_LIT>']<EOL>self.end_code = state['<STR_LIT>']<EOL>self.end_data = state['<STR_LIT>']<EOL>self.elf_brk = state['<STR_LIT>']<EOL>self.brk = state['<STR_LIT>']<EOL>self.auxv = state['<STR_LIT>']<EOL>self.program = state['<STR_LIT>']<EOL>self._function_abi = state['<STR_LIT>']<EOL>self._syscall_abi = state['<STR_LIT>']<EOL>self._uname_machine = state['<STR_LIT>']<EOL>if '<STR_LIT>' in state:<EOL><INDENT>self._arm_tls_memory = state['<STR_LIT>']<EOL><DEDENT>for proc in self.procs:<EOL><INDENT>self.forward_events_from(proc)<EOL><DEDENT>

:todo: some asserts
:todo: fix deps? (last line)


def sys_mprotect(self, start, size, prot):

perms = perms_from_protflags(prot)<EOL>ret = self.current.memory.mprotect(start, size, perms)<EOL>return <NUM_LIT:0><EOL>

Sets protection on a region of memory. Changes protection for the calling process's
memory page(s) containing any part of the address range in the interval [C{start}, C{start}+C{size}-1].
:rtype: int

:param start: the starting address to change the permissions.
:param size: the size of the portion of memory to change the permissions.
:param prot: the new access permission for the memory.
:return: C{0} on success.


connection = self.connections(fd)<EOL>if connection is None or connection >= len(self.rwait):<EOL><INDENT>return<EOL><DEDENT>procs = self.rwait[connection]<EOL>if procs:<EOL><INDENT>procid = random.sample(procs, <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>self.awake(procid)<EOL><DEDENT>

Awake one process waiting to transmit data on fd


return self.sys_stat64(fd, buf)<EOL>


platform = cls(None)<EOL>platform._init_cpu(arch)<EOL>platform._init_std_fds()<EOL>return platform<EOL>

Create a platform without an ELF loaded.

:param str arch: The architecture of the new platform
:rtype: Linux


try:<EOL><INDENT>current_dir = os.getcwd()<EOL>length = len(current_dir) + <NUM_LIT:1><EOL>if size > <NUM_LIT:0> and size < length:<EOL><INDENT>logger.info("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return -errno.ERANGE<EOL><DEDENT>if not self.current.memory.access_ok(slice(buf, buf + length), '<STR_LIT:w>'):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return -errno.EFAULT<EOL><DEDENT>self.current.write_string(buf, current_dir)<EOL>logger.debug(f"<STR_LIT>")<EOL>return length<EOL><DEDENT>except OSError as e:<EOL><INDENT>return -e.errno<EOL><DEDENT>

getcwd - Get the current working directory
:param int buf: Pointer to dest array
:param size: size in bytes of the array pointed to by the buf
:return: buf (Success), or 0


if self._current is None:<EOL><INDENT>advance = min([self.clocks] + [x for x in self.timers if x is not None]) + <NUM_LIT:1><EOL>logger.debug(f"<STR_LIT>")<EOL>self.clocks = advance<EOL><DEDENT>for procid in range(len(self.timers)):<EOL><INDENT>if self.timers[procid] is not None:<EOL><INDENT>if self.clocks > self.timers[procid]:<EOL><INDENT>self.procs[procid].PC += self.procs[procid].instruction.size<EOL>self.awake(procid)<EOL><DEDENT><DEDENT><DEDENT>


data: bytes = bytes()<EOL>cpu = self.current<EOL>if count != <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>write_fd = self._get_fd(fd)<EOL><DEDENT>except FdError as e:<EOL><INDENT>logger.error(f"<STR_LIT>")<EOL>return -e.err<EOL><DEDENT>if buf not in cpu.memory or buf + count not in cpu.memory:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>return -errno.EFAULT<EOL><DEDENT>if fd > <NUM_LIT:2> and write_fd.is_full():<EOL><INDENT>cpu.PC -= cpu.instruction.size<EOL>self.wait([], [fd], None)<EOL>raise RestartSyscall()<EOL><DEDENT>data: MixedSymbolicBuffer = cpu.read_bytes(buf, count)<EOL>data: bytes = self._transform_write_data(data)<EOL>write_fd.write(data)<EOL>for line in data.split(b'<STR_LIT:\n>'):<EOL><INDENT>line = line.decode('<STR_LIT>')  <EOL>logger.debug(f"<STR_LIT>")<EOL><DEDENT>self.syscall_trace.append(("<STR_LIT>", fd, data))<EOL>self.signal_transmit(fd)<EOL><DEDENT>return len(data)<EOL>

write - send bytes through a file descriptor
          The write system call writes up to count bytes from the buffer pointed
          to by buf to the file descriptor fd. If count is zero, write returns 0
          and optionally sets *tx_bytes to zero.

          :param fd            a valid file descriptor
          :param buf           a memory buffer
          :param count         number of bytes to send
          :return: 0          Success
                    EBADF      fd is not a valid file descriptor or is not open.
                    EFAULT     buf or tx_bytes points to an invalid address.


ret = <NUM_LIT:0><EOL>try:<EOL><INDENT>self.files[fd].sync()<EOL><DEDENT>except IndexError:<EOL><INDENT>ret = -errno.EBADF<EOL><DEDENT>except FdError:<EOL><INDENT>ret = -errno.EINVAL<EOL><DEDENT>return ret<EOL>

Synchronize a file's in-core state with that on disk.


filename = self.current.read_string(buf)<EOL>try:<EOL><INDENT>f = self._sys_open_get_file(filename, flags)<EOL>logger.debug(f"<STR_LIT>")<EOL><DEDENT>except IOError as e:<EOL><INDENT>logger.warning(f"<STR_LIT>")<EOL>return -e.errno if e.errno is not None else -errno.EINVAL<EOL><DEDENT>return self._open(f)<EOL>

:param buf: address of zero-terminated pathname
:param flags: file access bits
:param mode: file permission mode


def sys_getrandom(self, buf, size, flags):

GRND_NONBLOCK = <NUM_LIT><EOL>GRND_RANDOM = <NUM_LIT><EOL>if size == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if buf not in self.current.memory:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return -errno.EFAULT<EOL><DEDENT>if flags & ~(GRND_NONBLOCK | GRND_RANDOM):<EOL><INDENT>return -errno.EINVAL<EOL><DEDENT>self.current.write_bytes(buf, '<STR_LIT:\x00>' * size)<EOL>return size<EOL>

The getrandom system call fills the buffer with random bytes of buflen.
The source of random (/dev/random or /dev/urandom) is decided based on
the flags value.

Manticore's implementation simply fills a buffer with zeroes -- choosing
determinism over true randomness.

:param buf: address of buffer to be filled with random bytes
:param size: number of random bytes
:param flags: source of random (/dev/random or /dev/urandom)
:return: number of bytes copied to buf


def sys_mmap2(self, address, size, prot, flags, fd, offset):

return self.sys_mmap(address, size, prot, flags, fd, offset * <NUM_LIT>)<EOL>

Creates a new mapping in the virtual address space of the calling process.
:rtype: int
:param address: the starting address for the new mapping. This address is used as hint unless the
                flag contains C{MAP_FIXED}.
:param size: the length of the mapping.
:param prot: the desired memory protection of the mapping.
:param flags: determines whether updates to the mapping are visible to other
              processes mapping the same region, and whether updates are carried
              through to the underlying file.
:param fd: the contents of a file mapping are initialized using C{size} bytes starting at
           offset C{offset} in the file referred to by the file descriptor C{fd}.
:param offset: the contents of a file mapping are initialized using C{size} bytes starting at
               offset C{offset}*0x1000 in the file referred to by the file descriptor C{fd}.
:return:
    - C{-1} In case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address.
    - the address of the new mapping.


def _transform_write_data(self, data: T) -> T:

return data<EOL>

Implement in subclass to transform data written by write(2)/writev(2)
Nop by default.


cpu = self.current<EOL>ptrsize = cpu.address_bit_size<EOL>sizeof_iovec = <NUM_LIT:2> * (ptrsize // <NUM_LIT:8>)<EOL>total = <NUM_LIT:0><EOL>for i in range(<NUM_LIT:0>, count):<EOL><INDENT>buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize)<EOL>size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // <NUM_LIT:2>),<EOL>ptrsize)<EOL>data = self.files[fd].read(size)<EOL>total += len(data)<EOL>cpu.write_bytes(buf, data)<EOL>self.syscall_trace.append(("<STR_LIT>", fd, data))<EOL><DEDENT>return total<EOL>

Works just like C{sys_read} except that data is read into multiple buffers.
:rtype: int

:param fd: the file descriptor of the file to read.
:param iov: the buffer where the the bytes to read are stored.
:param count: amount of C{iov} buffers to read from the file.
:return: the amount of bytes read in total.


index = self._syscall_abi.syscall_number()<EOL>try:<EOL><INDENT>table = getattr(linux_syscalls, self.current.machine)<EOL>name = table.get(index, None)<EOL>implementation = getattr(self, name)<EOL><DEDENT>except (AttributeError, KeyError):<EOL><INDENT>if name is not None:<EOL><INDENT>raise SyscallNotImplemented(index, name)<EOL><DEDENT>else:<EOL><INDENT>raise Exception(f"<STR_LIT>")<EOL><DEDENT><DEDENT>return self._syscall_abi.invoke(implementation)<EOL>


filename = b'<STR_LIT>'<EOL>for i in range(<NUM_LIT:0>, <NUM_LIT:255>):<EOL><INDENT>c = Operators.CHR(self.current.read_int(buf + i, <NUM_LIT:8>))<EOL>if c == b'<STR_LIT:\x00>':<EOL><INDENT>break<EOL><DEDENT>filename += c<EOL><DEDENT>if os.access(filename, mode):<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>

Checks real user's permissions for a file
:rtype: int

:param buf: a buffer containing the pathname to the file to check its permissions.
:param mode: the access permissions to check.
:return:
    -  C{0} if the calling process can access the file in the desired mode.
    - C{-1} if the calling process can not access the file in the desired mode.


self.stdin.write(text)<EOL>self.stdin.flush()<EOL>str_buffer = '<STR_LIT>'<EOL>while not str_buffer.endswith(self.prompt):<EOL><INDENT>str_buffer += self.stdout.read(<NUM_LIT:1>)<EOL><DEDENT>return str_buffer<EOL>

Communicate with the child process without closing stdin.


def __init__(self, prg, prompt='<STR_LIT>'):

self.prompt = prompt<EOL>subprocess.Popen.__init__(self, ['<STR_LIT>', prg], stdin=subprocess.PIPE, stdout=subprocess.PIPE , stderr=subprocess.STDOUT)<EOL>


def make_chr(c):<EOL><INDENT>try:<EOL><INDENT>return chr(c)<EOL><DEDENT>except Exception:<EOL><INDENT>return c<EOL><DEDENT><DEDENT>newset = constraints_to_constraintset(constupl)<EOL>ret = '<STR_LIT>'<EOL>for data in datas:<EOL><INDENT>for c in data:<EOL><INDENT>ret += make_chr(solver.get_value(newset, c))<EOL><DEDENT><DEDENT>return ret<EOL>


equal = copy.copy(constraint)<EOL>assert len(equal.operands) == <NUM_LIT:2><EOL>ite, forcepc = equal.operands<EOL>assert isinstance(ite, BitVecITE) and isinstance(forcepc, BitVecConstant)<EOL>assert len(ite.operands) == <NUM_LIT:3><EOL>cond, iifpc, eelsepc = ite.operands<EOL>assert isinstance(iifpc, BitVecConstant) and isinstance(eelsepc, BitVecConstant)<EOL>equal._operands= (equal.operands[<NUM_LIT:0>], eelsepc if forcepc.value == iifpc.value else iifpc)<EOL>return equal<EOL>

flips a constraint (Equal)

(Equal (BitVecITE Cond IfC ElseC) IfC)
    ->
(Equal (BitVecITE Cond IfC ElseC) ElseC)


return any(eq(new, old) for old in olds)<EOL>

__contains__ operator using the `eq` function


return solver.check(constraints_to_constraintset(cons))<EOL>


for i in range(<NUM_LIT:1>, <NUM_LIT:2>**len(lst)):<EOL><INDENT>yield [func(item) if (<NUM_LIT:1><<j)&i else item for (j, item) in enumerate(lst)]<EOL><DEDENT>

Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly
    possible that returned constraints can be unsat this does it blindly, without any attention to the constraints
    themselves

    Considering lst as a list of constraints, e.g.

      [ C1, C2, C3 ]

    we'd like to consider scenarios of all possible permutations of flipped constraints, excluding the original list.
    So we'd like to generate:

      [ func(C1),      C2 ,       C3 ],
      [      C1 , func(C2),       C3 ],
      [ func(C1), func(C2),       C3 ],
      [      C1 ,      C2 ,  func(C3)],
      .. etc

    This is effectively treating the list of constraints as a bitmask of width len(lst) and counting up, skipping the
    0th element (unmodified array).

    The code below yields lists of constraints permuted as above by treating list indeces as bitmasks from 1 to
     2**len(lst) and applying func to all the set bit offsets.


if os.path.isfile(self.workspace):<EOL><INDENT>t = threading.Thread(target=self.highlight_from_file,<EOL>args=(self.workspace,))<EOL><DEDENT>elif os.path.isdir(self.workspace):<EOL><INDENT>t = threading.Thread(target=self.highlight_from_dir,<EOL>args=(self.workspace,))<EOL><DEDENT>t.start()<EOL>

Given a Manticore workspace, or trace file, highlight the basic blocks.


syscall = state.cpu.R7 <EOL>name = linux_syscalls.armv7[syscall]<EOL>logger.debug(f"<STR_LIT>")<EOL>try:<EOL><INDENT>if '<STR_LIT>' in name:<EOL><INDENT>returned = gdb.getR('<STR_LIT>')<EOL>logger.debug(f"<STR_LIT>")<EOL>state.cpu.write_register('<STR_LIT>', returned)<EOL><DEDENT>if '<STR_LIT>' in name:<EOL><INDENT>return<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>for reg in state.cpu.canonical_registers:<EOL><INDENT>print(f'<STR_LIT>')<EOL><DEDENT>raise<EOL><DEDENT>

Mirror some service calls in manticore. Happens after qemu executed a SVC
instruction, but before manticore did.


with open(binary, '<STR_LIT:rb>') as f:<EOL><INDENT>elffile = ELFFile(f)<EOL>if elffile['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>

helper method for determining binary architecture

:param binary: str for binary to introspect.
:rtype bool: True for x86_64, False otherwise


def substr_after(string, delim):<EOL><INDENT>return string.partition(delim)[<NUM_LIT:2>]<EOL><DEDENT>with open(binary, '<STR_LIT:rb>') as f:<EOL><INDENT>elffile = ELFFile(f)<EOL>for section in elffile.iter_sections():<EOL><INDENT>if not isinstance(section, SymbolTableSection):<EOL><INDENT>continue<EOL><DEDENT>symbols = [sym.name for sym in section.iter_symbols() if sym]<EOL>return [substr_after(name, PREPEND_SYM) for name in symbols<EOL>if name.startswith(PREPEND_SYM)]<EOL><DEDENT><DEDENT>

helper method for getting all binary symbols with SANDSHREW_ prepended.
We do this in order to provide the symbols Manticore should hook on to
perform main analysis.

:param binary: str for binary to instrospect.
:rtype list: list of symbols from binary


self.entries = []<EOL>self.entry_keys = {}<EOL>self.by_key = {}<EOL>self.callbacks = []<EOL>if entries is None:<EOL><INDENT>entries = sys.path<EOL><DEDENT>for entry in entries:<EOL><INDENT>self.add_entry(entry)<EOL><DEDENT>

Create working set from list of path entries (default=sys.path)


def resolve(self, requirements, env=None, installer=None):

requirements = list(requirements)[::-<NUM_LIT:1>]  <EOL>processed = {}  <EOL>best = {}  <EOL>to_activate = []<EOL>while requirements:<EOL><INDENT>req = requirements.pop(<NUM_LIT:0>)   <EOL>if req in processed:<EOL><INDENT>continue<EOL><DEDENT>dist = best.get(req.key)<EOL>if dist is None:<EOL><INDENT>dist = self.by_key.get(req.key)<EOL>if dist is None:<EOL><INDENT>if env is None:<EOL><INDENT>env = Environment(self.entries)<EOL><DEDENT>dist = best[req.key] = env.best_match(req, self, installer)<EOL>if dist is None:<EOL><INDENT>raise DistributionNotFound(req)  <EOL><DEDENT><DEDENT>to_activate.append(dist)<EOL><DEDENT>if dist not in req:<EOL><INDENT>raise VersionConflict(dist,req) <EOL><DEDENT>requirements.extend(dist.requires(req.extras)[::-<NUM_LIT:1>])<EOL>processed[req] = True<EOL><DEDENT>return to_activate<EOL>

List all distributions needed to (recursively) meet `requirements`

        `requirements` must be a sequence of ``Requirement`` objects.  `env`,
        if supplied, should be an ``Environment`` instance.  If
        not supplied, it defaults to all distributions available within any
        entry or distribution in the working set.  `installer`, if supplied,
        will be invoked with each requirement that cannot be met by an
        already-installed distribution; it should return a ``Distribution`` or
        ``None``.


List of resource names in the directory (like ``os.listdir()``)


return os.path.normcase(os.path.realpath(filename))<EOL>

Normalize a file/dir name for comparison purposes


def postprocess(self, tempname, filename):

if os.name == '<STR_LIT>':<EOL><INDENT>mode = ((os.stat(tempname).st_mode) | <NUM_LIT>) & <NUM_LIT><EOL>os.chmod(tempname, mode)<EOL><DEDENT>

Perform any platform-specific postprocessing of `tempname`

        This is where Mac header rewrites should be done; other platforms don't
        have anything special they should do.

        Resource providers should call this method ONLY after successfully
        extracting a compressed resource.  They must NOT call it on resources
        that are already in the filesystem.

        `tempname` is the current (temporary) name of the file, and `filename`
        is the name it will be renamed to by the caller after this routine
        returns.


return re.sub('<STR_LIT>', '<STR_LIT:->', name)<EOL>

Convert an arbitrary string to a standard distribution name

    Any runs of non-alphanumeric/. characters are replaced with a single '-'.


def resource_listdir(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).resource_listdir(<EOL>resource_name<EOL>)<EOL>

List the contents of the named resource directory


_provider_factories[loader_type] = provider_factory<EOL>

Register `provider_factory` to make providers for `loader_type`

    `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
    and `provider_factory` is a function that, passed a *module* object,
    returns an ``IResourceProvider`` for that module.


loc = loc or self.location<EOL>if not loc:<EOL><INDENT>return<EOL><DEDENT>if path is sys.path:<EOL><INDENT>self.check_version_conflict()<EOL><DEDENT>nloc = _normalize_cached(loc)<EOL>bdir = os.path.dirname(nloc)<EOL>npath= list(map(_normalize_cached, path))<EOL>bp = None<EOL>for p, item in enumerate(npath):<EOL><INDENT>if item==nloc:<EOL><INDENT>break<EOL><DEDENT>elif item==bdir and self.precedence==EGG_DIST:<EOL><INDENT>path.insert(p, loc)<EOL>npath.insert(p, nloc)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>path.append(loc)<EOL>return<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>np = npath.index(nloc, p+<NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>del npath[np], path[np]<EOL>p = np  <EOL><DEDENT><DEDENT>return<EOL>

Insert self.location in path before its nearest parent directory


ns = sys._getframe(<NUM_LIT:1>).f_globals<EOL>name = ns['<STR_LIT>']<EOL>ns.clear()<EOL>ns['<STR_LIT>'] = name<EOL>require(dist_spec)[<NUM_LIT:0>].run_script(script_name, ns)<EOL>

Locate distribution `dist_spec` and run its `script_name` script


imp.acquire_lock()<EOL>try:<EOL><INDENT>if packageName in _namespace_packages:<EOL><INDENT>return<EOL><DEDENT>path, parent = sys.path, None<EOL>if '<STR_LIT:.>' in packageName:<EOL><INDENT>parent = '<STR_LIT:.>'.join(packageName.split('<STR_LIT:.>')[:-<NUM_LIT:1>])<EOL>declare_namespace(parent)<EOL>__import__(parent)<EOL>try:<EOL><INDENT>path = sys.modules[parent].__path__<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise TypeError("<STR_LIT>", parent)<EOL><DEDENT><DEDENT>_namespace_packages.setdefault(parent,[]).append(packageName)<EOL>_namespace_packages.setdefault(packageName,[])<EOL>for path_item in path:<EOL><INDENT>_handle_ns(packageName, path_item)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>imp.release_lock()<EOL><DEDENT>

Declare that package 'packageName' is a namespace package


def resource_string(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).get_resource_string(<EOL>self, resource_name<EOL>)<EOL>


if not isinstance(cls,type):<EOL><INDENT>class cls(cls,object): pass<EOL>return cls.__mro__[<NUM_LIT:1>:]<EOL><DEDENT>return cls.__mro__<EOL>


def __init__(self, project_name, specs, extras):

self.unsafe_name, project_name = project_name, safe_name(project_name)<EOL>self.project_name, self.key = project_name, project_name.lower()<EOL>index = [(parse_version(v),state_machine[op],op,v) for op,v in specs]<EOL>index.sort()<EOL>self.specs = [(op,ver) for parsed,trans,op,ver in index]<EOL>self.index, self.extras = index, tuple(map(safe_extra,extras))<EOL>self.hashCmp = (<EOL>self.key, tuple([(op,parsed) for parsed,trans,op,ver in index]),<EOL>frozenset(self.extras)<EOL>)<EOL>self.__hash = hash(self.hashCmp)<EOL>

DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!


if isinstance(strs,str):<EOL><INDENT>for s in strs.splitlines():<EOL><INDENT>s = s.strip()<EOL>if s and not s.startswith('<STR_LIT:#>'):     <EOL><INDENT>yield s<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for ss in strs:<EOL><INDENT>for s in yield_lines(ss):<EOL><INDENT>yield s<EOL><DEDENT><DEDENT><DEDENT>

Yield non-empty/non-comment lines of a ``basestring`` or sequence


Does the package's distribution contain the named metadata?


return name.replace('<STR_LIT:->','<STR_LIT:_>')<EOL>

Convert a project or version name to its filename-escaped form

    Any '-' characters are currently replaced with '_'.


if path is None: path = sys.path<EOL>self.insert_on(path)<EOL>if path is sys.path:<EOL><INDENT>fixup_namespace_packages(self.location)<EOL>list(map(declare_namespace, self._get_metadata('<STR_LIT>')))<EOL><DEDENT>

Ensure distribution is importable on `path` (default=sys.path)


if isinstance(data,dict):<EOL><INDENT>data = list(data.items())<EOL><DEDENT>else:<EOL><INDENT>data = split_sections(data)<EOL><DEDENT>maps = {}<EOL>for group, lines in data:<EOL><INDENT>if group is None:<EOL><INDENT>if not lines:<EOL><INDENT>continue<EOL><DEDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>group = group.strip()<EOL>if group in maps:<EOL><INDENT>raise ValueError("<STR_LIT>", group)<EOL><DEDENT>maps[group] = cls.parse_group(group, lines, dist)<EOL><DEDENT>return maps<EOL>


return get_distribution(dist).get_entry_info(group, name)<EOL>

Return the EntryPoint object for `group`+`name`, or ``None``


Return a readable file-like object for `resource_name`

        `manager` must be an ``IResourceManager``


if self.can_add(dist) and dist.has_version():<EOL><INDENT>dists = self._distmap.setdefault(dist.key,[])<EOL>if dist not in dists:<EOL><INDENT>dists.append(dist)<EOL>if dist.key in self._cache:<EOL><INDENT>_sort_dists(self._cache[dist.key])<EOL><DEDENT><DEDENT><DEDENT>

Add `dist` if we ``can_add()`` it and it isn't already added


return self.get_entry_map(group).get(name)<EOL>


def resource_filename(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).get_resource_filename(<EOL>self, resource_name<EOL>)<EOL>

Return a true filesystem path for specified resource


if provided is None or required is None or provided==required:<EOL><INDENT>return True     <EOL><DEDENT>reqMac = macosVersionString.match(required)<EOL>if reqMac:<EOL><INDENT>provMac = macosVersionString.match(provided)<EOL>if not provMac:<EOL><INDENT>provDarwin = darwinVersionString.match(provided)<EOL>if provDarwin:<EOL><INDENT>dversion = int(provDarwin.group(<NUM_LIT:1>))<EOL>macosversion = "<STR_LIT>" % (reqMac.group(<NUM_LIT:1>), reqMac.group(<NUM_LIT:2>))<EOL>if dversion == <NUM_LIT:7> and macosversion >= "<STR_LIT>" ordversion == <NUM_LIT:8> and macosversion >= "<STR_LIT>":<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False    <EOL><DEDENT>if provMac.group(<NUM_LIT:1>) != reqMac.group(<NUM_LIT:1>) orprovMac.group(<NUM_LIT:3>) != reqMac.group(<NUM_LIT:3>):<EOL><INDENT>return False<EOL><DEDENT>if int(provMac.group(<NUM_LIT:2>)) > int(reqMac.group(<NUM_LIT:2>)):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL><DEDENT>return False<EOL>

Can code for the `provided` platform run on the `required` platform?

    Returns true if either platform is ``None``, or the platforms are equal.

    XXX Needs compatibility checks for Linux and other unixy OSes.


try:<EOL><INDENT>importer = sys.path_importer_cache[path_item]<EOL><DEDENT>except KeyError:<EOL><INDENT>for hook in sys.path_hooks:<EOL><INDENT>try:<EOL><INDENT>importer = hook(path_item)<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>importer = None<EOL><DEDENT><DEDENT>sys.path_importer_cache.setdefault(path_item,importer)<EOL>if importer is None:<EOL><INDENT>try:<EOL><INDENT>importer = ImpWrapper(path_item)<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return importer<EOL>

Retrieve a PEP 302 "importer" for the given path item

    If there is no importer, this returns a wrapper around the builtin import
    machinery.  The returned importer is only cached if it was created by a
    path hook.


def load_entry_point(dist, group, name):

return get_distribution(dist).load_entry_point(group, name)<EOL>

Return `name` entry point of `group` for `dist` or raise ImportError


dist = self.by_key.get(req.key)<EOL>if dist is not None and dist not in req:<EOL><INDENT>raise VersionConflict(dist,req)     <EOL><DEDENT>else:<EOL><INDENT>return dist<EOL><DEDENT>

Find a distribution matching requirement `req`

        If there is an active distribution for the requested project, this
        returns it as long as it meets the version requirement specified by
        `req`.  But, if there is an active distribution for the project and it
        does *not* meet the `req` requirement, ``VersionConflict`` is raised.
        If there is no active distribution for the requested project, ``None``
        is returned.


Does the package contain the named resource?


dirname = os.path.dirname(path)<EOL>if not os.path.isdir(dirname):<EOL><INDENT>os.makedirs(dirname)<EOL><DEDENT>

Ensure that the parent directory of `path` exists


<EOL>lines = iter(yield_lines(strs))<EOL>def scan_list(ITEM,TERMINATOR,line,p,groups,item_name):<EOL><INDENT>items = []<EOL>while not TERMINATOR(line,p):<EOL><INDENT>if CONTINUE(line,p):<EOL><INDENT>try:<EOL><INDENT>line = next(lines); p = <NUM_LIT:0><EOL><DEDENT>except StopIteration:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>match = ITEM(line,p)<EOL>if not match:<EOL><INDENT>raise ValueError("<STR_LIT>"+item_name+"<STR_LIT>",line,"<STR_LIT>",line[p:])<EOL><DEDENT>items.append(match.group(*groups))<EOL>p = match.end()<EOL>match = COMMA(line,p)<EOL>if match:<EOL><INDENT>p = match.end() <EOL><DEDENT>elif not TERMINATOR(line,p):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>",line,"<STR_LIT>",line[p:]<EOL>)<EOL><DEDENT><DEDENT>match = TERMINATOR(line,p)<EOL>if match: p = match.end()   <EOL>return line, p, items<EOL><DEDENT>for line in lines:<EOL><INDENT>match = DISTRO(line)<EOL>if not match:<EOL><INDENT>raise ValueError("<STR_LIT>", line)<EOL><DEDENT>project_name = match.group(<NUM_LIT:1>)<EOL>p = match.end()<EOL>extras = []<EOL>match = OBRACKET(line,p)<EOL>if match:<EOL><INDENT>p = match.end()<EOL>line, p, extras = scan_list(<EOL>DISTRO, CBRACKET, line, p, (<NUM_LIT:1>,), "<STR_LIT>"<EOL>)<EOL><DEDENT>line, p, specs = scan_list(VERSION,LINE_END,line,p,(<NUM_LIT:1>,<NUM_LIT:2>),"<STR_LIT>")<EOL>specs = [(op,safe_version(val)) for op,val in specs]<EOL>yield Requirement(project_name, specs, extras)<EOL><DEDENT>

Yield ``Requirement`` objects for each specification in `strs`

    `strs` must be an instance of ``basestring``, or a (possibly-nested)
    iterable thereof.


if attr.startswith('<STR_LIT:_>'):<EOL><INDENT>raise AttributeError(attr)<EOL><DEDENT>return getattr(self._provider, attr)<EOL>

Delegate all unrecognized public attributes to .metadata provider


List of metadata names in the directory (like ``os.listdir()``)


if isinstance(moduleOrReq,Requirement):<EOL><INDENT>return working_set.find(moduleOrReq) or require(str(moduleOrReq))[<NUM_LIT:0>]<EOL><DEDENT>try:<EOL><INDENT>module = sys.modules[moduleOrReq]<EOL><DEDENT>except KeyError:<EOL><INDENT>__import__(moduleOrReq)<EOL>module = sys.modules[moduleOrReq]<EOL><DEDENT>loader = getattr(module, '<STR_LIT>', None)<EOL>return _find_adapter(_provider_factories, loader)(module)<EOL>

Return an IResourceProvider for the named module or requirement


def add(self, dist, entry=None, insert=True):

if insert:<EOL><INDENT>dist.insert_on(self.entries, entry)<EOL><DEDENT>if entry is None:<EOL><INDENT>entry = dist.location<EOL><DEDENT>keys = self.entry_keys.setdefault(entry,[])<EOL>keys2 = self.entry_keys.setdefault(dist.location,[])<EOL>if dist.key in self.by_key:<EOL><INDENT>return      <EOL><DEDENT>self.by_key[dist.key] = dist<EOL>if dist.key not in keys:<EOL><INDENT>keys.append(dist.key)<EOL><DEDENT>if dist.key not in keys2:<EOL><INDENT>keys2.append(dist.key)<EOL><DEDENT>self._added_new(dist)<EOL>

Add `dist` to working set, associated with `entry`

        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
        On exit from this routine, `entry` is added to the end of the working
        set's ``.entries`` (if it wasn't already present).

        `dist` is only added to the working set if it's for a project that
        doesn't already have a distribution in the set.  If it's added, any
        callbacks registered with the ``subscribe()`` method will be called.


Is the named metadata a directory?  (like ``os.path.isdir()``)


def resource_exists(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).has_resource(resource_name)<EOL>


needed = self.resolve(parse_requirements(requirements))<EOL>for dist in needed:<EOL><INDENT>self.add(dist)<EOL><DEDENT>return needed<EOL>

Ensure that distributions matching `requirements` are activated

        `requirements` must be a string or a (possibly-nested) sequence
        thereof, specifying the distributions and versions required.  The
        return value is a sequence of the distributions that needed to be
        activated to fulfill the requirements; all relevant distributions are
        included, even if they were already activated in this working set.


return self.by_key.get(dist.key) == dist<EOL>

True if `dist` is the active distribution for its project


for t in _get_mro(getattr(ob, '<STR_LIT>', type(ob))):<EOL><INDENT>if t in registry:<EOL><INDENT>return registry[t]<EOL><DEDENT><DEDENT>

Return an adapter factory for `ob` from `registry`


if isinstance(other,Distribution):<EOL><INDENT>self.add(other)<EOL><DEDENT>elif isinstance(other,Environment):<EOL><INDENT>for project in other:<EOL><INDENT>for dist in other[project]:<EOL><INDENT>self.add(dist)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" % (other,))<EOL><DEDENT>return self<EOL>

In-place addition of a distribution or environment


self.zipinfo = zipimport._zip_directory_cache[importer.archive]<EOL>self.zip_pre = importer.archive+os.sep<EOL>self.loader = importer<EOL>if importer.prefix:<EOL><INDENT>self.module_path = os.path.join(importer.archive, importer.prefix)<EOL><DEDENT>else:<EOL><INDENT>self.module_path = importer.archive<EOL><DEDENT>self._setup_prefix()<EOL>

Create a metadata provider from a zipimporter


Is the named resource a directory?  (like ``os.path.isdir()``)


seen = {}<EOL>for item in self.entries:<EOL><INDENT>for key in self.entry_keys[item]:<EOL><INDENT>if key not in seen:<EOL><INDENT>seen[key]=<NUM_LIT:1><EOL>yield self.by_key[key]<EOL><DEDENT><DEDENT><DEDENT>

Yield distributions for non-duplicate projects in the working set

        The yield order is the order in which the items' path entries were
        added to the working set.


Yield named metadata resource as list of non-blank non-comment lines

       Leading and trailing whitespace is stripped from each line, and lines
       with ``#`` as the first non-blank character are omitted.


if dt.tzinfo is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return dt.replace(tzinfo=self)<EOL>


if zone.upper() == '<STR_LIT>':<EOL><INDENT>return utc<EOL><DEDENT>try:<EOL><INDENT>zone = zone.encode('<STR_LIT>')<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>raise UnknownTimeZoneError(zone)<EOL><DEDENT>zone = _unmunge_zone(zone)<EOL>if zone not in _tzinfo_cache:<EOL><INDENT>if zone in all_timezones_set:<EOL><INDENT>_tzinfo_cache[zone] = build_tzinfo(zone, open_resource(zone))<EOL><DEDENT>else:<EOL><INDENT>raise UnknownTimeZoneError(zone)<EOL><DEDENT><DEDENT>return _tzinfo_cache[zone]<EOL>

r''' Return a datetime.tzinfo implementation for the given timezone

    >>> from datetime import datetime, timedelta
    >>> utc = timezone('UTC')
    >>> eastern = timezone('US/Eastern')
    >>> eastern.zone
    'US/Eastern'
    >>> timezone(u'US/Eastern') is eastern
    True
    >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
    >>> loc_dt = utc_dt.astimezone(eastern)
    >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
    >>> loc_dt.strftime(fmt)
    '2002-10-27 01:00:00 EST (-0500)'
    >>> (loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 00:50:00 EST (-0500)'
    >>> eastern.normalize(loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:50:00 EDT (-0400)'
    >>> (loc_dt + timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:10:00 EST (-0500)'

    Raises UnknownTimeZoneError if passed an unknown zone.

    >>> timezone('Asia/Shangri-La')
    Traceback (most recent call last):
    ...
    UnknownTimeZoneError: 'Asia/Shangri-La'

    >>> timezone(u'\N{TRADE MARK SIGN}')
    Traceback (most recent call last):
    ...
    UnknownTimeZoneError: u'\u2122'


if offset == <NUM_LIT:0>:<EOL><INDENT>return UTC<EOL><DEDENT>info = _tzinfos.get(offset)<EOL>if info is None:<EOL><INDENT>info = _tzinfos.setdefault(offset, _FixedOffset(offset))<EOL><DEDENT>return info<EOL>

return a fixed-offset timezone based off a number of minutes.

        >>> one = FixedOffset(-330)
        >>> one
        pytz.FixedOffset(-330)
        >>> one.utcoffset(datetime.datetime.now())
        datetime.timedelta(-1, 66600)

        >>> two = FixedOffset(1380)
        >>> two
        pytz.FixedOffset(1380)
        >>> two.utcoffset(datetime.datetime.now())
        datetime.timedelta(0, 82800)

    The datetime.timedelta must be between the range of -1 and 1 day,
    non-inclusive.

        >>> FixedOffset(1440)
        Traceback (most recent call last):
        ...
        ValueError: ('absolute offset is too large', 1440)

        >>> FixedOffset(-1440)
        Traceback (most recent call last):
        ...
        ValueError: ('absolute offset is too large', -1440)

    An offset of 0 is special-cased to return UTC.

        >>> FixedOffset(0) is UTC
        True

    There should always be only one instance of a FixedOffset per timedelta.
    This should be true for multiple creation calls.

        >>> FixedOffset(-330) is one
        True
        >>> FixedOffset(1380) is two
        True

    It should also be true for pickling.

        >>> import pickle
        >>> pickle.loads(pickle.dumps(one)) is one
        True
        >>> pickle.loads(pickle.dumps(two)) is two
        True


try:<EOL><INDENT>return _timedelta_cache[seconds]<EOL><DEDENT>except KeyError:<EOL><INDENT>delta = timedelta(seconds=seconds)<EOL>_timedelta_cache[seconds] = delta<EOL>return delta<EOL><DEDENT>

Create only one instance of each distinct timedelta


try:<EOL><INDENT>return _datetime_cache[seconds]<EOL><DEDENT>except KeyError:<EOL><INDENT>dt = _epoch + timedelta(seconds=seconds)<EOL>_datetime_cache[seconds] = dt<EOL>return dt<EOL><DEDENT>

Create only one instance of each distinct datetime


def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):

<EOL>tz = pytz.timezone(zone)<EOL>if utcoffset is None:<EOL><INDENT>return tz<EOL><DEDENT>utcoffset = memorized_timedelta(utcoffset)<EOL>dstoffset = memorized_timedelta(dstoffset)<EOL>try:<EOL><INDENT>return tz._tzinfos[(utcoffset, dstoffset, tzname)]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>for localized_tz in list(tz._tzinfos.values()):<EOL><INDENT>if (localized_tz._utcoffset == utcoffset<EOL>and localized_tz._dst == dstoffset):<EOL><INDENT>return localized_tz<EOL><DEDENT><DEDENT>inf = (utcoffset, dstoffset, tzname)<EOL>tz._tzinfos[inf] = tz.__class__(inf, tz._tzinfos)<EOL>return tz._tzinfos[inf]<EOL>

Factory function for unpickling pytz tzinfo instances.

    This is shared for both StaticTzInfo and DstTzInfo instances, because
    database changes could cause a zones implementation to switch between
    these two base classes and we can't break pickles on a pytz version
    upgrade.


def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length,<EOL>pivot, sizes, fill_empty, flip):

<EOL>spacing = length * sizes.get('<STR_LIT>', <NUM_LIT>)<EOL>full_height = length * sizes.get('<STR_LIT>', <NUM_LIT>)<EOL>full_width = length * sizes.get('<STR_LIT:width>', <NUM_LIT>)<EOL>empty_rad = length * sizes.get('<STR_LIT>', <NUM_LIT>)<EOL>pivot_points = dict(tip=<NUM_LIT:0.0>, middle=-length/<NUM_LIT>)<EOL>if flip: full_height = -full_height<EOL>endx = <NUM_LIT:0.0><EOL>endy = pivot_points[pivot.lower()]<EOL>angles = -(ma.arctan2(v, u) + np.pi/<NUM_LIT:2>)<EOL>circ = CirclePolygon((<NUM_LIT:0>,<NUM_LIT:0>), radius=empty_rad).get_verts()<EOL>if fill_empty:<EOL><INDENT>empty_barb = circ<EOL><DEDENT>else:<EOL><INDENT>empty_barb = np.concatenate((circ, circ[::-<NUM_LIT:1>]))<EOL><DEDENT>barb_list = []<EOL>for index, angle in np.ndenumerate(angles):<EOL><INDENT>if empty_flag[index]:<EOL><INDENT>barb_list.append(empty_barb)<EOL>continue<EOL><DEDENT>poly_verts = [(endx, endy)]<EOL>offset = length<EOL>for i in range(nflags[index]):<EOL><INDENT>if offset != length: offset += spacing / <NUM_LIT><EOL>poly_verts.extend([[endx, endy + offset],<EOL>[endx + full_height, endy - full_width/<NUM_LIT:2> + offset],<EOL>[endx, endy - full_width + offset]])<EOL>offset -= full_width + spacing<EOL><DEDENT>for i in range(nbarbs[index]):<EOL><INDENT>poly_verts.extend([(endx, endy + offset),<EOL>(endx + full_height, endy + offset + full_width/<NUM_LIT:2>),<EOL>(endx, endy + offset)])<EOL>offset -= spacing<EOL><DEDENT>if half_barb[index]:<EOL><INDENT>if offset == length:<EOL><INDENT>poly_verts.append((endx, endy + offset))<EOL>offset -= <NUM_LIT> * spacing<EOL><DEDENT>poly_verts.extend([(endx, endy + offset),<EOL>(endx + full_height/<NUM_LIT:2>, endy + offset + full_width/<NUM_LIT:4>),<EOL>(endx, endy + offset)])<EOL><DEDENT>poly_verts = transforms.Affine2D().rotate(-angle).transform(<EOL>poly_verts)<EOL>barb_list.append(poly_verts)<EOL><DEDENT>return barb_list<EOL>

This function actually creates the wind barbs.  *u* and *v*
are components of the vector in the *x* and *y* directions,
respectively.

*nflags*, *nbarbs*, and *half_barb*, empty_flag* are,
*respectively, the number of flags, number of barbs, flag for
*half a barb, and flag for empty barb, ostensibly obtained
*from :meth:`_find_tails`.

*length* is the length of the barb staff in points.

*pivot* specifies the point on the barb around which the
entire barb should be rotated.  Right now, valid options are
'head' and 'middle'.

*sizes* is a dictionary of coefficients specifying the ratio
of a given feature to the length of the barb. These features
include:

    - *spacing*: space between features (flags, full/half
       barbs)

    - *height*: distance from shaft of top of a flag or full
       barb

    - *width* - width of a flag, twice the width of a full barb

    - *emptybarb* - radius of the circle used for low
       magnitudes

*fill_empty* specifies whether the circle representing an
empty barb should be filled or not (this changes the drawing
of the polygon).

*flip* is a flag indicating whether the features should be flipped to
the other side of the barb (useful for winds in the southern
hemisphere.

This function returns list of arrays of vertices, defining a polygon for
each of the wind barbs.  These polygons have been rotated to properly
align with the vector direction.


def _find_tails(self, mag, rounding=True, half=<NUM_LIT:5>, full=<NUM_LIT:10>, flag=<NUM_LIT:50>):

<EOL>if rounding:<EOL><INDENT>mag = half * (mag / half + <NUM_LIT:0.5>).astype(np.int)<EOL><DEDENT>num_flags = np.floor(mag / flag).astype(np.int)<EOL>mag = np.mod(mag, flag)<EOL>num_barb = np.floor(mag / full).astype(np.int)<EOL>mag = np.mod(mag, full)<EOL>half_flag = mag >= half<EOL>empty_flag = ~(half_flag | (num_flags > <NUM_LIT:0>) | (num_barb > <NUM_LIT:0>))<EOL>return num_flags, num_barb, half_flag, empty_flag<EOL>

Find how many of each of the tail pieces is necessary.  Flag
specifies the increment for a flag, barb for a full barb, and half for
half a barb. Mag should be the magnitude of a vector (ie. >= 0).

This returns a tuple of:

    (*number of flags*, *number of barbs*, *half_flag*, *empty_flag*)

*half_flag* is a boolean whether half of a barb is needed,
since there should only ever be one half on a given
barb. *empty_flag* flag is an array of flags to easily tell if
a barb is empty (too low to plot any barbs/flags.


self.x = xy[:,<NUM_LIT:0>]<EOL>self.y = xy[:,<NUM_LIT:1>]<EOL>x,y,u,v = delete_masked_points(self.x.ravel(), self.y.ravel(), self.u,<EOL>self.v)<EOL>xy = np.hstack((x[:,np.newaxis], y[:,np.newaxis]))<EOL>collections.PolyCollection.set_offsets(self, xy)<EOL>

Set the offsets for the barb polygons.  This saves the offets passed in
and actually sets version masked as appropriate for the existing U/V
data. *offsets* should be a sequence.

ACCEPTS: sequence of pairs of floats


<EOL>if True: <EOL><INDENT>trans = self._set_transform()<EOL>ax = self.ax<EOL>sx, sy = trans.inverted().transform_point(<EOL>(ax.bbox.width, ax.bbox.height))<EOL>self.span = sx<EOL>sn = max(<NUM_LIT:8>, min(<NUM_LIT>, math.sqrt(self.N)))<EOL>if self.width is None:<EOL><INDENT>self.width = <NUM_LIT> * self.span / sn<EOL><DEDENT><DEDENT>

initialization delayed until first draw;
        allow time for axes setup.


if ax is None:<EOL><INDENT>ax=gca()<EOL><DEDENT>ax1 = ax.twiny()<EOL>draw_if_interactive()<EOL>return ax1<EOL>

Make a second axes overlay *ax* (or the current axes if *ax* is
*None*) sharing the yaxis.  The ticks for *ax2* will be placed on
the top, and the *ax2* instance is returned.


ax = gca(polar=True)<EOL>ret = ax.plot(*args, **kwargs)<EOL>draw_if_interactive()<EOL>return ret<EOL>

call signature::

  polar(theta, r, **kwargs)

Make a polar plot.  Multiple *theta*, *r* arguments are supported,
with format strings, as in :func:`~matplotlib.pyplot.plot`.


rc('<STR_LIT:image>', cmap='<STR_LIT>')<EOL>im = gci()<EOL>if im is not None:<EOL><INDENT>im.set_cmap(cm.gray)<EOL><DEDENT>draw_if_interactive()<EOL>

set the default colormap to gray and apply to current image if any.
See help(colormaps) for more information


rc('<STR_LIT:image>', cmap='<STR_LIT>')<EOL>im = gci()<EOL>if im is not None:<EOL><INDENT>im.set_cmap(cm.flag)<EOL><DEDENT>draw_if_interactive()<EOL>

set the default colormap to flag and apply to current image if any.
See help(colormaps) for more information


ax = gca()<EOL>ret = ax.set_yscale(*args, **kwargs)<EOL>draw_if_interactive()<EOL>return ret<EOL>

call signature::

  xscale(scale, **kwargs)

Set the scaling for the y-axis: %(scale)s

Different keywords may be accepted, depending on the scale:

%(scale_docs)s


fig = gcf()<EOL>a = fig.add_subplot(*args, **kwargs)<EOL>bbox = a.bbox<EOL>byebye = []<EOL>for other in fig.axes:<EOL><INDENT>if other==a: continue<EOL>if bbox.fully_overlaps(other.bbox):<EOL><INDENT>byebye.append(other)<EOL><DEDENT><DEDENT>for ax in byebye: delaxes(ax)<EOL>draw_if_interactive()<EOL>return a<EOL>

Create a subplot command, creating axes with::

  subplot(numRows, numCols, plotNum)

where *plotNum* = 1 is the first plot number and increasing *plotNums*
fill rows first.  max(*plotNum*) == *numRows* * *numCols*

You can leave out the commas if *numRows* <= *numCols* <=
*plotNum* < 10, as in::

  subplot(211)    # 2 rows, 1 column, first (upper) plot

``subplot(111)`` is the default axis.

New subplots that overlap old will delete the old axes.  If you do
not want this behavior, use
:meth:`matplotlib.figure.Figure.add_subplot` or the
:func:`~matplotlib.pyplot.axes` command.  Eg.::

  from pylab import *
  plot([1,2,3])  # implicitly creates subplot(111)
  subplot(211)   # overlaps, subplot(111) is killed
  plot(rand(12), rand(12))
  subplot(212, axisbg='y') # creates 2nd subplot with yellow background

Keyword arguments:

  *axisbg*:
    The background color of the subplot, which can be any valid
    color specifier.  See :mod:`matplotlib.colors` for more
    information.

  *polar*:
    A boolean flag indicating whether the subplot plot should be
    a polar projection.  Defaults to False.

  *projection*:
    A string giving the name of a custom projection to be used
    for the subplot. This projection must have been previously
    registered. See :func:`matplotlib.projections.register_projection`

.. seealso::
    :func:`~matplotlib.pyplot.axes`:
        For additional information on :func:`axes` and
        :func:`subplot` keyword arguments.

    :file:`examples/pylab_examples/polar_scatter.py`

**Example:**

.. plot:: mpl_examples/pylab_examples/subplot_demo.py


def figure(num=None, <EOL>figsize   = None, <EOL>dpi       = None, <EOL>facecolor = None, <EOL>edgecolor = None, <EOL>frameon = True,<EOL>FigureClass = Figure,<EOL>**kwargs<EOL>):

if figsize is None   : figsize   = rcParams['<STR_LIT>']<EOL>if dpi is None       : dpi       = rcParams['<STR_LIT>']<EOL>if facecolor is None : facecolor = rcParams['<STR_LIT>']<EOL>if edgecolor is None : edgecolor = rcParams['<STR_LIT>']<EOL>if num is None:<EOL><INDENT>allnums = [f.num for f in _pylab_helpers.Gcf.get_all_fig_managers()]<EOL>if allnums:<EOL><INDENT>num = max(allnums) + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>num = <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>num = int(num)  <EOL><DEDENT>figManager = _pylab_helpers.Gcf.get_fig_manager(num)<EOL>if figManager is None:<EOL><INDENT>if get_backend().lower() == '<STR_LIT>':  dpi = <NUM_LIT><EOL>figManager = new_figure_manager(num, figsize=figsize,<EOL>dpi=dpi,<EOL>facecolor=facecolor,<EOL>edgecolor=edgecolor,<EOL>frameon=frameon,<EOL>FigureClass=FigureClass,<EOL>**kwargs)<EOL>def make_active(event):<EOL><INDENT>_pylab_helpers.Gcf.set_active(figManager)<EOL><DEDENT>cid = figManager.canvas.mpl_connect('<STR_LIT>', make_active)<EOL>figManager._cidgcf = cid<EOL>_pylab_helpers.Gcf.set_active(figManager)<EOL>figManager.canvas.figure.number = num<EOL><DEDENT>draw_if_interactive()<EOL>return figManager.canvas.figure<EOL>

call signature::

  figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

Create a new figure and return a :class:`matplotlib.figure.Figure`
instance.  If *num* = *None*, the figure number will be incremented and
a new figure will be created.  The returned figure objects have a
*number* attribute holding this number.

If *num* is an integer, and ``figure(num)`` already exists, make it
active and return the handle to it.  If ``figure(num)`` does not exist
it will be created.  Numbering starts at 1, matlab style::

  figure(1)

If you are creating many figures, make sure you explicitly call "close"
on the figures you are not using, because this will enable pylab
to properly clean up the memory.

Optional keyword arguments:

  =========   =======================================================
  Keyword     Description
  =========   =======================================================
  figsize     width x height in inches; defaults to rc figure.figsize
  dpi         resolution; defaults to rc figure.dpi
  facecolor   the background color; defaults to rc figure.facecolor
  edgecolor   the border color; defaults to rc figure.edgecolor
  =========   =======================================================

rcParams defines the default values, which can be modified in the
matplotlibrc file

*FigureClass* is a :class:`~matplotlib.figure.Figure` or derived
class that will be passed on to :meth:`new_figure_manager` in the
backends which allows you to hook custom Figure classes into the
pylab interface.  Additional kwargs will be passed on to your
figure init function.


fig = gcf()<EOL>fig.subplots_adjust(*args, **kwargs)<EOL>draw_if_interactive()<EOL>

call signature::

  subplots_adjust(left=None, bottom=None, right=None, top=None,
                  wspace=None, hspace=None)

Tune the subplot layout via the
:class:`matplotlib.figure.SubplotParams` mechanism.  The parameter
meanings (and suggested defaults) are::

  left  = 0.125  # the left side of the subplots of the figure
  right = 0.9    # the right side of the subplots of the figure
  bottom = 0.1   # the bottom of the subplots of the figure
  top = 0.9      # the top of the subplots of the figure
  wspace = 0.2   # the amount of width reserved for blank space between subplots
  hspace = 0.2   # the amount of height reserved for white space between subplots

The actual defaults are controlled by the rc file


ax = gca()<EOL>ret = ax.set_xlim(*args, **kwargs)<EOL>draw_if_interactive()<EOL>return ret<EOL>

Set/Get the xlimits of the current axes::

  xmin, xmax = xlim()   # return the current xlim
  xlim( (xmin, xmax) )  # set the xlim to xmin, xmax
  xlim( xmin, xmax )    # set the xlim to xmin, xmax

If you do not specify args, you can pass the xmin and xmax as
kwargs, eg.::

  xlim(xmax=3) # adjust the max leaving min unchanged
  xlim(xmin=1) # adjust the min leaving max unchanged

The new axis limits are returned as a length 2 tuple.


rc('<STR_LIT:image>', cmap='<STR_LIT>')<EOL>im = gci()<EOL>if im is not None:<EOL><INDENT>im.set_cmap(cm.spring)<EOL><DEDENT>draw_if_interactive()<EOL>

set the default colormap to spring and apply to current image if any.
See help(colormaps) for more information


rc('<STR_LIT:image>', cmap='<STR_LIT>')<EOL>im = gci()<EOL>if im is not None:<EOL><INDENT>im.set_cmap(cm.bone)<EOL><DEDENT>draw_if_interactive()<EOL>

set the default colormap to bone and apply to current image if any.
See help(colormaps) for more information


def plotfile(fname, cols=(<NUM_LIT:0>,), plotfuncs=None,<EOL>comments='<STR_LIT:#>', skiprows=<NUM_LIT:0>, checkrows=<NUM_LIT:5>, delimiter='<STR_LIT:U+002C>',<EOL>**kwargs):

fig = figure()<EOL>if len(cols)<<NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if plotfuncs is None:<EOL><INDENT>plotfuncs = dict()<EOL><DEDENT>r = mlab.csv2rec(fname, comments=comments,<EOL>skiprows=skiprows, checkrows=checkrows, delimiter=delimiter)<EOL>def getname_val(identifier):<EOL><INDENT>'<STR_LIT>'<EOL>if is_string_like(identifier):<EOL><INDENT>return identifier, r[identifier]<EOL><DEDENT>elif is_numlike(identifier):<EOL><INDENT>name = r.dtype.names[int(identifier)]<EOL>return name, r[name]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>xname, x = getname_val(cols[<NUM_LIT:0>])<EOL>if len(cols)==<NUM_LIT:1>:<EOL><INDENT>ax1 = fig.add_subplot(<NUM_LIT:1>,<NUM_LIT:1>,<NUM_LIT:1>)<EOL>funcname = plotfuncs.get(cols[<NUM_LIT:0>], '<STR_LIT>')<EOL>func = getattr(ax1, funcname)<EOL>func(x, **kwargs)<EOL>ax1.set_xlabel(xname)<EOL><DEDENT>else:<EOL><INDENT>N = len(cols)<EOL>for i in range(<NUM_LIT:1>,N):<EOL><INDENT>if i==<NUM_LIT:1>:<EOL><INDENT>ax = ax1 = fig.add_subplot(N-<NUM_LIT:1>,<NUM_LIT:1>,i)<EOL>ax.grid(True)<EOL><DEDENT>else:<EOL><INDENT>ax = fig.add_subplot(N-<NUM_LIT:1>,<NUM_LIT:1>,i, sharex=ax1)<EOL>ax.grid(True)<EOL><DEDENT>yname, y = getname_val(cols[i])<EOL>funcname = plotfuncs.get(cols[i], '<STR_LIT>')<EOL>func = getattr(ax, funcname)<EOL>func(x, y, **kwargs)<EOL>ax.set_ylabel(yname)<EOL>if ax.is_last_row():<EOL><INDENT>ax.set_xlabel(xname)<EOL><DEDENT>else:<EOL><INDENT>ax.set_xlabel('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>if xname=='<STR_LIT:date>':<EOL><INDENT>fig.autofmt_xdate()<EOL><DEDENT>draw_if_interactive()<EOL>

Plot the data in *fname*

*cols* is a sequence of column identifiers to plot.  An identifier
is either an int or a string.  If it is an int, it indicates the
column number.  If it is a string, it indicates the column header.
matplotlib will make column headers lower case, replace spaces with
underscores, and remove all illegal characters; so ``'Adj Close*'``
will have name ``'adj_close'``.

- If len(*cols*) == 1, only that column will be plotted on the *y* axis.

- If len(*cols*) > 1, the first element will be an identifier for
  data for the *x* axis and the remaining elements will be the
  column indexes for multiple subplots

*plotfuncs*, if not *None*, is a dictionary mapping identifier to
an :class:`~matplotlib.axes.Axes` plotting function as a string.
Default is 'plot', other choices are 'semilogy', 'fill', 'bar',
etc.  You must use the same type of identifier in the *cols*
vector as you use in the *plotfuncs* dictionary, eg., integer
column numbers in both or column names in both.

*comments*, *skiprows*, *checkrows*, and *delimiter* are all passed on to
:func:`matplotlib.pylab.csv2rec` to load the data into a record array.

kwargs are passed on to plotting functions.

Example usage::

  # plot the 2nd and 4th column against the 1st in two subplots
  plotfile(fname, (0,1,3))

  # plot using column names; specify an alternate plot type for volume
  plotfile(fname, ('date', 'volume', 'adj_close'), plotfuncs={'volume': 'semilogy'})


rc('<STR_LIT:image>', cmap='<STR_LIT>')<EOL>im = gci()<EOL>if im is not None:<EOL><INDENT>im.set_cmap(cm.hot)<EOL><DEDENT>draw_if_interactive()<EOL>

set the default colormap to hot and apply to current image if any.
See help(colormaps) for more information


ax = gca()<EOL>ret = ax.set_ylim(*args, **kwargs)<EOL>draw_if_interactive()<EOL>return ret<EOL>

Set/Get the ylimits of the current axes::

  ymin, ymax = ylim()   # return the current ylim
  ylim( (ymin, ymax) )  # set the ylim to ymin, ymax
  ylim( ymin, ymax )    # set the ylim to ymin, ymax

If you do not specify args, you can pass the *ymin* and *ymax* as
kwargs, eg.::

  ylim(ymax=3) # adjust the max leaving min unchanged
  ylim(ymin=1) # adjust the min leaving max unchanged

The new axis limits are returned as a length 2 tuple.


im = gci()<EOL>if im is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>im.set_clim(vmin, vmax)<EOL>draw_if_interactive()<EOL>

Set the color limits of the current image

To apply clim to all axes images do::

  clim(0, 0.5)

If either *vmin* or *vmax* is None, the image min/max respectively
will be used for color scaling.

If you want to set the clim of multiple images,
use, for example::

  for im in gca().get_images():
      im.set_clim(0, 0.05)


rc('<STR_LIT:image>', cmap='<STR_LIT>')<EOL>im = gci()<EOL>if im is not None:<EOL><INDENT>im.set_cmap(cm.summer)<EOL><DEDENT>draw_if_interactive()<EOL>

set the default colormap to summer and apply to current image if any.
See help(colormaps) for more information


ax = gca()<EOL>if len(args)==<NUM_LIT:0>:<EOL><INDENT>locs = ax.get_yticks()<EOL>labels = ax.get_yticklabels()<EOL><DEDENT>elif len(args)==<NUM_LIT:1>:<EOL><INDENT>locs = ax.set_yticks(args[<NUM_LIT:0>])<EOL>labels = ax.get_yticklabels()<EOL><DEDENT>elif len(args)==<NUM_LIT:2>:<EOL><INDENT>locs = ax.set_yticks(args[<NUM_LIT:0>])<EOL>labels = ax.set_yticklabels(args[<NUM_LIT:1>], **kwargs)<EOL><DEDENT>else: raise TypeError('<STR_LIT>')<EOL>if len(kwargs):<EOL><INDENT>for l in labels:<EOL><INDENT>l.update(kwargs)<EOL><DEDENT><DEDENT>draw_if_interactive()<EOL>return ( locs,<EOL>silent_list('<STR_LIT>', labels)<EOL>)<EOL>

Set/Get the ylimits of the current ticklocs and labels::

  # return locs, labels where locs is an array of tick locations and
  # labels is an array of tick labels.
  locs, labels = yticks()

  # set the locations of the yticks
  yticks( arange(6) )

  # set the locations and labels of the yticks
  yticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )

The keyword args, if any, are :class:`~matplotlib.text.Text`
properties.


pass<EOL>

This is a do nothing function to provide you with help on how
matplotlib handles colors.

Commands which take color arguments can use several formats to
specify the colors.  For the basic builtin colors, you can use a
single letter

  =====   =======
  Alias   Color
  =====   =======
  'b'     blue
  'g'     green
  'r'     red
  'c'     cyan
  'm'     magenta
  'y'     yellow
  'k'     black
  'w'     white
  =====   =======

For a greater range of colors, you have two options.  You can
specify the color using an html hex string, as in::

  color = '#eeefff'

or you can pass an R,G,B tuple, where each of R,G,B are in the
range [0,1].

You can also use any legal html name for a color, for example::

  color = 'red',
  color = 'burlywood'
  color = 'chartreuse'

The example below creates a subplot with a dark
slate gray background

   subplot(111, axisbg=(0.1843, 0.3098, 0.3098))

Here is an example that creates a pale turqoise title::

  title('Is this the best color?', color='#afeeee')


rc('<STR_LIT:image>', cmap='<STR_LIT>')<EOL>im = gci()<EOL>if im is not None:<EOL><INDENT>im.set_cmap(cm.prism)<EOL><DEDENT>draw_if_interactive()<EOL>

set the default colormap to prism and apply to current image if any.
See help(colormaps) for more information


return matplotlib.is_interactive()<EOL>


rc('<STR_LIT:image>', cmap='<STR_LIT>')<EOL>im = gci()<EOL>if im is not None:<EOL><INDENT>im.set_cmap(cm.copper)<EOL><DEDENT>draw_if_interactive()<EOL>

set the default colormap to copper and apply to current image if any.
See help(colormaps) for more information


l =  gca().set_title(s, *args, **kwargs)<EOL>draw_if_interactive()<EOL>return l<EOL>

Set the title of the current axis to *s*.

Default font override is::

  override = {'fontsize': 'medium',
              'verticalalignment': 'bottom',
              'horizontalalignment': 'center'}

.. seealso::
   :func:`~matplotlib.pyplot.text`:
       for information on how override and the optional args work.


if not len(args):<EOL><INDENT>ax = gca()<EOL><DEDENT>else:<EOL><INDENT>ax = args[<NUM_LIT:0>]<EOL><DEDENT>ret = gcf().delaxes(ax)<EOL>draw_if_interactive()<EOL>return ret<EOL>

``delaxes(ax)``: remove *ax* from the current figure.  If *ax*
doesn't exist, an error will be raised.

``delaxes()``: delete the current axes


close('<STR_LIT:all>')<EOL>global new_figure_manager, draw_if_interactive, show<EOL>matplotlib.use(newbackend, warn=False)<EOL>reload(matplotlib.backends)<EOL>from matplotlib.backends import pylab_setup<EOL>new_figure_manager, draw_if_interactive, show = pylab_setup()<EOL>

Switch the default backend to newbackend.  This feature is
**experimental**, and is only expected to work switching to an
image backend.  Eg, if you have a bunch of PostScript scripts that
you want to run from an interactive ipython session, you may want
to switch to the PS backend before running them to avoid having a
bunch of GUI windows popup.  If you try to interactively switch
from one GUI backend to another, you will explode.

Calling this command will close all open windows.


if len(args)==<NUM_LIT:0>:<EOL><INDENT>figManager = _pylab_helpers.Gcf.get_active()<EOL>if figManager is None: return<EOL>else:<EOL><INDENT>figManager.canvas.mpl_disconnect(figManager._cidgcf)<EOL>_pylab_helpers.Gcf.destroy(figManager.num)<EOL><DEDENT><DEDENT>elif len(args)==<NUM_LIT:1>:<EOL><INDENT>arg = args[<NUM_LIT:0>]<EOL>if arg=='<STR_LIT:all>':<EOL><INDENT>for manager in _pylab_helpers.Gcf.get_all_fig_managers():<EOL><INDENT>manager.canvas.mpl_disconnect(manager._cidgcf)<EOL>_pylab_helpers.Gcf.destroy(manager.num)<EOL><DEDENT><DEDENT>elif isinstance(arg, int):<EOL><INDENT>_pylab_helpers.Gcf.destroy(arg)<EOL><DEDENT>elif isinstance(arg, Figure):<EOL><INDENT>for manager in _pylab_helpers.Gcf.get_all_fig_managers():<EOL><INDENT>if manager.canvas.figure==arg:<EOL><INDENT>manager.canvas.mpl_disconnect(manager._cidgcf)<EOL>_pylab_helpers.Gcf.destroy(manager.num)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'%type(arg))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>

Close a figure window

``close()`` by itself closes the current figure

``close(num)`` closes figure number *num*

``close(h)`` where *h* is a :class:`Figure` instance, closes that figure

``close('all')`` closes all the figure windows


ax = gca()<EOL>if not isinstance(ax, PolarAxes):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if len(args)==<NUM_LIT:0>:<EOL><INDENT>lines = ax.xaxis.get_ticklines()<EOL>labels = ax.xaxis.get_ticklabels()<EOL><DEDENT>else:<EOL><INDENT>lines, labels = ax.set_thetagrids(*args, **kwargs)<EOL><DEDENT>draw_if_interactive()<EOL>return (silent_list('<STR_LIT>', lines),<EOL>silent_list('<STR_LIT>', labels)<EOL>)<EOL>

Set/Get the theta locations of the gridlines and ticklabels.

If no arguments are passed, return a tuple (*lines*, *labels*)
where *lines* is an array of radial gridlines
(:class:`~matplotlib.lines.Line2D` instances) and *labels* is an
array of tick labels (:class:`~matplotlib.text.Text` instances)::

  lines, labels = thetagrids()

Otherwise the syntax is::

  lines, labels = thetagrids(angles, labels=None, fmt='%d', frac = 1.1)

set the angles at which to place the theta grids (these gridlines
are equal along the theta dimension).

*angles* is in degrees.

*labels*, if not *None*, is a len(angles) list of strings of the
labels to use at each angle.

If *labels* is *None*, the labels will be ``fmt%angle``.

*frac* is the fraction of the polar axes radius at which to place
the label (1 is the edge). Eg. 1.05 is outside the axes and 0.95
is inside the axes.

Return value is a list of tuples (*lines*, *labels*):

  - *lines* are :class:`~matplotlib.lines.Line2D` instances

  - *labels* are :class:`~matplotlib.text.Text` instances.

Note that on input, the *labels* argument is a list of strings,
and on output it is a list of :class:`~matplotlib.text.Text`
instances.

Examples::

  # set the locations of the radial gridlines and labels
  lines, labels = thetagrids( range(45,360,90) )

  # set the locations and labels of the radial gridlines and labels
  lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') )


return gcf().waitforbuttonpress(*args, **kwargs)<EOL>

Blocking call to interact with the figure.

This will wait for *n* key or mouse clicks from the user and
return a list containing True's for keyboard clicks and False's
for mouse clicks.

If *timeout* is negative, does not timeout.


if ax is None:<EOL><INDENT>ax=gca()<EOL><DEDENT>ax1 = ax.twinx()<EOL>draw_if_interactive()<EOL>return ax1<EOL>

Make a second axes overlay *ax* (or the current axes if *ax* is
*None*) sharing the xaxis.  The ticks for *ax2* will be placed on
the right, and the *ax2* instance is returned.

.. seealso::
   :file:`examples/api_examples/two_scales.py`