code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.MUL, src1, src2, dst) | def gen_mul(src1, src2, dst) | Return a MUL instruction. | 7.335664 | 5.548961 | 1.321989 |
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.DIV, src1, src2, dst) | def gen_div(src1, src2, dst) | Return a DIV instruction. | 8.200307 | 5.577916 | 1.470138 |
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.MOD, src1, src2, dst) | def gen_mod(src1, src2, dst) | Return a MOD instruction. | 8.471423 | 5.45368 | 1.553341 |
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.BSH, src1, src2, dst) | def gen_bsh(src1, src2, dst) | Return a BSH instruction. | 6.978339 | 5.322498 | 1.311102 |
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.AND, src1, src2, dst) | def gen_and(src1, src2, dst) | Return an AND instruction. | 6.948312 | 5.147962 | 1.349721 |
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.OR, src1, src2, dst) | def gen_or(src1, src2, dst) | Return an OR instruction. | 6.974043 | 5.172745 | 1.348229 |
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.XOR, src1, src2, dst) | def gen_xor(src1, src2, dst) | Return a XOR instruction. | 6.538808 | 5.308764 | 1.231701 |
return ReilBuilder.build(ReilMnemonic.LDM, src, ReilEmptyOperand(), dst) | def gen_ldm(src, dst) | Return a LDM instruction. | 18.025846 | 12.633066 | 1.426878 |
return ReilBuilder.build(ReilMnemonic.STM, src, ReilEmptyOperand(), dst) | def gen_stm(src, dst) | Return a STM instruction. | 20.710373 | 14.218981 | 1.45653 |
return ReilBuilder.build(ReilMnemonic.STR, src, ReilEmptyOperand(), dst) | def gen_str(src, dst) | Return a STR instruction. | 20.655912 | 13.937337 | 1.482056 |
return ReilBuilder.build(ReilMnemonic.BISZ, src, ReilEmptyOperand(), dst) | def gen_bisz(src, dst) | Return a BISZ instruction. | 19.981785 | 15.247343 | 1.310509 |
return ReilBuilder.build(ReilMnemonic.JCC, src, ReilEmptyOperand(), dst) | def gen_jcc(src, dst) | Return a JCC instruction. | 15.551395 | 13.71063 | 1.134258 |
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.UNKN, empty_reg, empty_reg, empty_reg) | def gen_unkn() | Return an UNKN instruction. | 10.179391 | 7.093716 | 1.434987 |
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.UNDEF, empty_reg, empty_reg, empty_reg) | def gen_undef() | Return an UNDEF instruction. | 8.440197 | 6.588076 | 1.281132 |
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.NOP, empty_reg, empty_reg, empty_reg) | def gen_nop() | Return a NOP instruction. | 7.992677 | 6.459446 | 1.237363 |
assert src.size <= dst.size
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.SEXT, src, empty_reg, dst) | def gen_sext(src, dst) | Return a SEXT instruction. | 11.012756 | 9.139263 | 1.204994 |
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SDIV, src1, src2, dst) | def gen_sdiv(src1, src2, dst) | Return a SDIV instruction. | 6.468458 | 5.377913 | 1.202782 |
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SMOD, src1, src2, dst) | def gen_smod(src1, src2, dst) | Return a SMOD instruction. | 7.905497 | 5.59783 | 1.412243 |
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SMUL, src1, src2, dst) | def gen_smul(src1, src2, dst) | Return a SMUL instruction. | 6.701715 | 5.638752 | 1.18851 |
ins = ReilInstruction()
ins.mnemonic = mnemonic
ins.operands = [oprnd1, oprnd2, oprnd3]
return ins | def build(mnemonic, oprnd1, oprnd2, oprnd3) | Return the specified instruction. | 3.997154 | 3.187774 | 1.253902 |
# set up architecture information
self.arch_info = None
if self.binary.architecture == ARCH_X86:
self._setup_x86_arch(arch_mode)
else:
# TODO: add arch to the binary file class.
self._setup_arm_arch(arch_mode) | def _setup_arch(self, arch_mode=None) | Set up architecture. | 5.571123 | 5.118577 | 1.088412 |
if arch_mode is None:
arch_mode = ARCH_ARM_MODE_THUMB
self.name = "ARM"
self.arch_info = ArmArchitectureInformation(arch_mode)
self.disassembler = ArmDisassembler(architecture_mode=arch_mode)
self.ir_translator = ArmTranslator(architecture_mode=arch_mode) | def _setup_arm_arch(self, arch_mode=None) | Set up ARM architecture. | 3.800006 | 3.662643 | 1.037504 |
if arch_mode is None:
arch_mode = self.binary.architecture_mode
# Set up architecture information
self.name = "x86"
self.arch_info = X86ArchitectureInformation(arch_mode)
self.disassembler = X86Disassembler(arch_mode)
self.ir_translator = X86Translat... | def _setup_x86_arch(self, arch_mode=None) | Set up x86 architecture. | 3.404664 | 3.127313 | 1.088687 |
self.ir_emulator = None
self.smt_solver = None
self.smt_translator = None
if self.arch_info:
# Set REIL emulator.
self.ir_emulator = ReilEmulator(self.arch_info)
# Set SMT Solver.
self.smt_solver = None
if SMT_SOLVER... | def _setup_core_modules(self) | Set up core modules. | 2.808471 | 2.722519 | 1.031571 |
# Basic block.
self.bb_builder = CFGRecoverer(RecursiveDescent(self.disassembler, self.text_section, self.ir_translator,
self.arch_info))
# Code analyzer.
self.code_analyzer = None
if self.smt_translator:
... | def _setup_analysis_modules(self) | Set up analysis modules. | 3.775976 | 3.628178 | 1.040736 |
if filename:
self.binary = BinaryFile(filename)
self.text_section = self.binary.text_section
self._load(arch_mode=self.binary.architecture_mode) | def open(self, filename) | Open a file for analysis.
Args:
filename (str): Name of an executable file. | 9.478468 | 9.92527 | 0.954983 |
# Set up architecture information.
self.name = name
self.arch_info = arch_info
self.disassembler = disassembler
self.ir_translator = translator
# Setup analysis modules.
self._setup_analysis_modules() | def load_architecture(self, name, arch_info, disassembler, translator) | Translate to REIL instructions.
Args:
name (str): Architecture's name.
arch_info (ArchitectureInformation): Architecture information object.
disassembler (Disassembler): Disassembler for the architecture.
translator (Translator): Translator for the architecture. | 3.871808 | 4.576782 | 0.845967 |
start_addr = start if start else self.binary.ea_start
end_addr = end if end else self.binary.ea_end
self.ir_translator.reset()
for addr, asm, _ in self.disassemble(start=start_addr, end=end_addr, arch_mode=arch_mode):
yield addr, asm, self.ir_translator.translate(a... | def translate(self, start=None, end=None, arch_mode=None) | Translate to REIL instructions.
Args:
start (int): Start address.
end (int): End address.
arch_mode (int): Architecture mode.
Returns:
(int, Instruction, list): A tuple of the form (address, assembler instruction, REIL instructions). | 3.779334 | 3.998434 | 0.945204 |
if arch_mode is None:
arch_mode = self.binary.architecture_mode
curr_addr = start if start else self.binary.ea_start
end_addr = end if end else self.binary.ea_end
while curr_addr < end_addr:
# Fetch the instruction.
encoding = self.__fetch_i... | def disassemble(self, start=None, end=None, arch_mode=None) | Disassemble native instructions.
Args:
start (int): Start address.
end (int): End address.
arch_mode (int): Architecture mode.
Returns:
(int, Instruction, int): A tuple of the form (address, assembler instruction, instruction size). | 3.268312 | 3.10868 | 1.051351 |
# Set architecture in case it wasn't already set.
if arch_mode is None:
arch_mode = self.binary.architecture_mode
# Reload modules.
self._load(arch_mode=arch_mode)
# Check start address.
start = start if start else self.binary.entry_point
c... | def recover_cfg(self, start=None, end=None, symbols=None, callback=None, arch_mode=None) | Recover CFG.
Args:
start (int): Start address.
end (int): End address.
symbols (dict): Symbol table.
callback (function): A callback function which is called after each successfully recovered CFG.
arch_mode (int): Architecture mode.
Returns:
... | 4.019423 | 4.489288 | 0.895336 |
# Set architecture in case it wasn't already set.
if arch_mode is None:
arch_mode = self.binary.architecture_mode
# Reload modules.
self._load(arch_mode=arch_mode)
# Set symbols.
symbols = {} if not symbols else symbols
# Recover the CFGs.
... | def recover_cfg_all(self, entries, symbols=None, callback=None, arch_mode=None) | Recover CFG for all functions from an entry point and/or symbol table.
Args:
entries (list): A list of function addresses' to start the CFG recovery process.
symbols (dict): Symbol table.
callback (function): A callback function which is called after each successfully recove... | 3.445157 | 3.436669 | 1.00247 |
# Retrieve symbol name in case it is available.
if symbols and start in symbols:
name = symbols[start][0]
size = symbols[start][1] - 1 if symbols[start][1] != 0 else 0
else:
name = "sub_{:x}".format(start)
size = 0
# Compute start... | def _recover_cfg(self, start=None, end=None, symbols=None, callback=None) | Recover CFG | 3.898593 | 3.875102 | 1.006062 |
if arch_mode is not None:
# Reload modules.
self._load(arch_mode=arch_mode)
context = context if context else {}
start_addr = start if start else self.binary.ea_start
end_addr = end if end else self.binary.ea_end
hooks = hooks if hooks else {}
... | def emulate(self, context=None, start=None, end=None, arch_mode=None, hooks=None, max_instrs=None, print_asm=False) | Emulate native code.
Args:
context (dict): Processor context (register and/or memory).
start (int): Start address.
end (int): End address.
arch_mode (int): Architecture mode.
hooks (dict): Hooks by address.
max_instrs (int): Maximum number... | 3.304568 | 3.305876 | 0.999604 |
self._max_bytes = byte_depth
self._instrs_depth = instrs_depth
if self._architecture == ARCH_X86:
candidates = self._find_x86_candidates(start_address, end_address)
elif self._architecture == ARCH_ARM:
candidates = self._find_arm_candidates(start_address... | def find(self, start_address, end_address, byte_depth=20, instrs_depth=2) | Find gadgets. | 2.517916 | 2.318951 | 1.0858 |
roots = []
# find gadgets tail
for addr in xrange(start_address, end_address + 1):
# TODO: Make this 'speed improvement' architecture-agnostic
op_codes = [
0xc3, # RET
0xc2, # RET imm16
0xeb, # JMP rel8... | def _find_x86_candidates(self, start_address, end_address) | Finds possible 'RET-ended' gadgets. | 3.931869 | 3.827806 | 1.027186 |
roots = []
gadget_tail_addr = []
# From ROPgadget:
free_jump_gadgets = [
b"[\x10-\x19\x1e]{1}\xff\x2f\xe1", # bx reg
b"[\x30-\x39\x3e]{1}\xff\x2f\xe1", # blx reg
b"[\x00-\xff]{1}\x80\xbd\xe8", # pop {,pc}
]
# find g... | def _find_arm_candidates(self, start_address, end_address) | Finds possible 'RET-ended' gadgets. | 4.582566 | 4.482522 | 1.022319 |
if depth == 0:
return
end_addr = address
for step in range(1, self._max_bytes + 1):
start_addr = address - step
if start_addr < 0 or start_addr < base_address:
break
raw_bytes = self._mem[start_addr:end_addr]
... | def _build_from(self, address, root, base_address, depth=2) | Build gadgets recursively. | 3.156581 | 3.021831 | 1.044592 |
node_list = self._build_gadgets_rec(gadget_tree_root)
return [RawGadget(n) for n in node_list] | def _build_gadgets(self, gadget_tree_root) | Return a gadgets list. | 4.778421 | 3.853568 | 1.239999 |
root = gadget_tree_root.get_root()
children = gadget_tree_root.get_children()
node_list = []
root_gadget_ins = root
if not children:
node_list += [[root_gadget_ins]]
else:
for child in children:
node_list_rec = self._bui... | def _build_gadgets_rec(self, gadget_tree_root) | Build a gadgets from a gadgets tree. | 2.888227 | 2.68951 | 1.073886 |
invalid_instrs = [
ReilMnemonic.JCC,
ReilMnemonic.UNDEF,
ReilMnemonic.UNKN,
]
return not any([i.mnemonic in invalid_instrs for i in ins_ir]) | def _is_valid_ins(self, ins_ir) | Check for instruction validity as a gadgets. | 5.064817 | 4.489391 | 1.128175 |
try:
trans_instrs = self._translate(instruction)
except Exception:
self._log_translation_exception(instruction)
raise TranslationError("Unknown error")
return trans_instrs | def translate(self, instruction) | Return REIL representation of an instruction. | 6.482549 | 6.131896 | 1.057185 |
if isinstance(operand, ReilRegisterOperand):
if operand.name in self._arch_info.registers_all:
# Process architectural registers (eax, ebx, etc.)
expr = self.get_register_expr(operand.name, mode=mode)
else:
# Process temporal regis... | def get_operand_expr(self, operand, mode="post") | Return a smt bit vector that represents a register (architectural or
temporal). | 3.900831 | 3.337891 | 1.168652 |
reg_info = self._arch_info.alias_mapper.get(register_name, None)
if reg_info:
var_base_name, offset = reg_info
else:
var_base_name = register_name
var_name = self._get_var_name(var_base_name, mode)
var_size = self._arch_info.registers_size[var_b... | def get_register_expr(self, register_name, mode="post") | Return a smt bit vector that represents an architectural (native)
register. | 3.302726 | 3.085372 | 1.070447 |
mem = self.get_memory(mode)
return smtfunction.concat(8, *reversed([mem[address + i] for i in range(size)])) | def get_memory_expr(self, address, size, mode="post") | Return a smt bit vector that represents a memory location. | 12.36745 | 10.311007 | 1.199442 |
mem = {
"pre": self._translator.get_memory_init(),
"post": self._translator.get_memory_curr(),
}
return mem[mode] | def get_memory(self, mode) | Return a smt bit vector that represents a memory location. | 6.980113 | 6.393669 | 1.091723 |
for expr in self._translator.translate(reil_instruction):
self._solver.add(expr) | def add_instruction(self, reil_instruction) | Add an instruction for analysis. | 8.28038 | 6.727956 | 1.230742 |
var_name = {
"pre": self._translator.get_name_init(register_name),
"post": self._translator.get_name_curr(register_name),
}
return var_name[mode] | def _get_var_name(self, register_name, mode) | Get variable name for a register considering pre and post mode. | 4.926921 | 4.168982 | 1.181804 |
# Set initial CPU state.
self.__set_cpu_state(initial_state)
# Convert input native addresses to reil addresses.
start = to_reil_address(start) if start else None
end = to_reil_address(end) if end else None
find = to_reil_address(find) if find else None
... | def find_address(self, container, start=None, end=None, find=None, avoid=None, initial_state=None) | Execute instructions. | 4.079535 | 3.990396 | 1.022338 |
self.__set_cpu_state(initial_state)
# Convert input native addresses to reil addresses.
start = to_reil_address(start) if start else None
end = to_reil_address(end) if end else None
avoid = [to_reil_address(addr) for addr in avoid] if avoid else []
# Load instr... | def find_state(self, container, start=None, end=None, avoid=None, initial_state=None, final_state=None) | Execute instructions. | 4.7251 | 4.580091 | 1.031661 |
# Process branch (JCC oprnd0, empty, oprnd2).
if instr.mnemonic == ReilMnemonic.JCC:
not_taken_addr = next_addr
address, index = split_address(instr.address)
logger.debug("[+] Processing branch: {:#08x}:{:02x} : {}".format(address, index, instr))
... | def __process_instr(self, instr, avoid, next_addr, initial_state, execution_state, trace_current) | Process a REIL instruction.
Args:
instr (ReilInstruction): Instruction to process.
avoid (list): List of addresses to avoid while executing the code.
next_addr (int): Address of the following instruction.
initial_state (State): Initial execution state.
... | 4.232234 | 4.094633 | 1.033605 |
# TODO: Process execution intra states.
ip = sequence.address
next_ip = None
while ip:
# Fetch next instruction in the sequence.
try:
instr = sequence.fetch(ip)
except ReilSequenceInvalidAddressError:
# At thi... | def __fa_process_sequence(self, sequence, avoid, initial_state, execution_state, trace_current, next_addr) | Process a REIL sequence.
Args:
sequence (ReilSequence): A REIL sequence to process.
avoid (list): List of address to avoid.
initial_state: Initial state.
execution_state: Execution state queue.
trace_current (list): Current trace.
next_add... | 4.917406 | 4.635135 | 1.060898 |
ip = start
while ip:
# NOTE *ip* and *next_addr* variables can be, independently, either intra
# or inter addresses.
# Fetch next instruction.
try:
instr = container.fetch(ip)
except ReilContainerInvalidAddressError:
... | def __fa_process_container(self, container, find, start, end, avoid, initial_state, execution_state, trace_current,
trace_final) | Process a REIL container.
Args:
avoid (list): List of addresses to avoid while executing the code.
container (ReilContainer): REIL container to execute.
end (int): End address.
execution_state (Queue): Queue of execution states.
find (int): Address to... | 2.901313 | 2.79537 | 1.0379 |
cfg_start = self.find_function_by_name(start_name)
cfg_end = self.find_function_by_name(end_name)
if not cfg_start or not cfg_end:
raise Exception("Start/End function not found.")
start_address = cfg_start.start_address
end_address = cfg_end.start_address
... | def simple_paths_by_name(self, start_name, end_name) | Return a list of paths between start and end functions. | 2.362998 | 2.215899 | 1.066384 |
cfg_start = self.find_function_by_address(start_address)
cfg_end = self.find_function_by_address(end_address)
if not cfg_start or not cfg_end:
raise Exception("Start/End function not found.")
start_address = cfg_start.start_address
end_address = cfg_end.sta... | def simple_paths_by_address(self, start_address, end_address) | Return a list of paths between start and end functions. | 2.376371 | 2.252902 | 1.054804 |
cfg_rv = None
for cfg in self._cfgs:
if cfg.name == name:
cfg_rv = cfg
break
return cfg_rv | def find_function_by_name(self, name) | Return the cfg of the requested function by name. | 4.176926 | 2.709545 | 1.54156 |
cfg_rv = None
for cfg in self._cfgs:
if cfg.start_address == address:
cfg_rv = cfg
break
return cfg_rv | def find_function_by_address(self, address) | Return the cfg of the requested function by address. | 4.526968 | 2.85961 | 1.583072 |
try:
dot_graph = Dot(**self.graph_format)
# add nodes
nodes = {}
for cfg_addr in cf._graph.node.keys():
nodes[cfg_addr] = self._create_node(cfg_addr, cf)
dot_graph.add_node(nodes[cfg_addr])
# add edges
... | def save(self, cf, filename, format='dot') | Save basic block graph into a file. | 2.71957 | 2.667692 | 1.019447 |
bb_start = self._find_basic_block(start_address)
bb_end = self._find_basic_block(end_address)
paths = networkx.all_simple_paths(self._graph, source=bb_start.address, target=bb_end.address)
return ([self._bb_by_addr[addr] for addr in path] for path in paths) | def all_simple_bb_paths(self, start_address, end_address) | Return a list of path between start and end address. | 2.511259 | 2.395131 | 1.048485 |
symbols = {} if not symbols else symbols
# First pass: Recover BBs.
bbs = self._recover_bbs(start, end, symbols)
# Second pass: Split overlapping basic blocks introduced by back edges.
bbs = self._split_bbs(bbs, symbols)
# Third pass: Extract call targets for ... | def build(self, start, end, symbols=None) | Return the list of basic blocks.
:int start: Start address of the disassembling process.
:int end: End address of the disassembling process. | 5.047094 | 5.250089 | 0.961335 |
if options is None:
options = {}
try:
dot_graph = Dot(**self.graph_format)
# Add nodes.
nodes = {}
for bb in cfg.basic_blocks:
nodes[bb.address] = self._create_node(bb, cfg.name, print_ir, options)
do... | def save(self, cfg, filename, print_ir=False, format='dot', options=None) | Save basic block graph into a file. | 2.570526 | 2.446991 | 1.050484 |
sizes = {
"dqword": 128,
"pointer": 72,
"qword": 64,
"pointer": 40,
"dword": 32,
"word": 16,
"byte": 8,
"bit": 1,
}
if "immediate" in tokens:
imm_str = "".join(tokens["immediate"])
base = 16 if imm_str.start... | def parse_operand(string, location, tokens) | Parse instruction operand. | 3.062449 | 2.99195 | 1.023563 |
mnemonic_str = ReilMnemonic.from_string(tokens["mnemonic"])
oprnd1 = tokens["fst_operand"][0]
oprnd2 = tokens["snd_operand"][0]
oprnd3 = tokens["trd_operand"][0]
ins_builder = ReilBuilder()
return ins_builder.build(mnemonic_str, oprnd1, oprnd2, oprnd3) | def parse_instruction(string, location, tokens) | Parse instruction. | 3.951307 | 3.958832 | 0.998099 |
instrs_reil = []
try:
for instr in instrs:
instr_lower = instr.lower()
# If the instruction to parsed is not in the cache,
# parse it and add it to the cache.
if instr_lower not in self._cache:
sel... | def parse(self, instrs) | Parse an IR instruction. | 3.495527 | 3.382791 | 1.033326 |
if "immediate_operand" in tokens:
size = arch_info.operand_size
oprnd = ArmImmediateOperand("".join(tokens["immediate_operand"]), size)
if "register_operand" in tokens:
oprnd = process_register(tokens["register_operand"])
# TODO: Figure out where to really store this flag... | def parse_operand(string, location, tokens) | Parse an ARM instruction operand. | 2.386074 | 2.34652 | 1.016856 |
mnemonic_str = tokens.get("mnemonic")
operands = [op for op in tokens.get("operands", [])]
instr = ArmInstruction(
string,
mnemonic_str["ins"],
operands,
arch_info.architecture_mode
)
if "cc" in mnemonic_str:
instr.condition_code = cc_mapper[mnemonic_st... | def parse_instruction(string, location, tokens) | Parse an ARM instruction. | 3.977845 | 3.804462 | 1.045574 |
# Remove all paranteses
path = re.sub('\([^\)]*\)', '', path)
args = re.findall('<([^>]+)>', path)
def split_arg(arg):
spl = arg.split(':')
if len(spl) == 1:
return {'name': spl[0],
'dataType': 'string',
'paramType': 'path'}
else:
return {'name': spl[1],
... | def extract_path_arguments(path) | Extracts a swagger path arguments from the given flask path.
This /path/<parameter> extracts [{name: 'parameter'}]
And this /<string(length=2):lang_code>/<string:id>/<float:probability>
extracts: [
{name: 'lang_code', dataType: 'string'},
{name: 'id', dataType: 'string'}
{name: 'probability', dataType... | 3.001125 | 2.643422 | 1.135318 |
itr = croniter.croniter(cron_string, datetime.utcnow())
return itr.get_next(datetime) | def get_next_scheduled_time(cron_string) | Calculate the next scheduled time by creating a crontab object
with a cron string | 3.920548 | 4.123282 | 0.950832 |
if until is None:
until = "+inf"
elif isinstance(until, datetime):
until = to_unix(until)
elif isinstance(until, timedelta):
until = to_unix((datetime.utcnow() + until))
return until | def rationalize_until(until=None) | Rationalizes the `until` argument used by other functions. This function
accepts datetime and timedelta instances as well as integers representing
epoch values. | 3.114191 | 2.979528 | 1.045196 |
self.log.info('Registering death')
with self.connection.pipeline() as p:
p.hset(self.scheduler_key, 'death', time.time())
p.expire(self.scheduler_key, 60)
p.execute() | def register_death(self) | Registers its own death. | 3.521855 | 3.445062 | 1.022291 |
key = '%s_lock' % self.scheduler_key
now = time.time()
expires = int(self._interval) + 10
self._lock_acquired = self.connection.set(
key, now, ex=expires, nx=True)
return self._lock_acquired | def acquire_lock(self) | Acquire lock before scheduling jobs to prevent another scheduler
from scheduling jobs at the same time.
This function returns True if a lock is acquired. False otherwise. | 4.884302 | 4.885974 | 0.999658 |
key = '%s_lock' % self.scheduler_key
if self._lock_acquired:
self.connection.delete(key) | def remove_lock(self) | Remove acquired lock. | 8.160574 | 6.59338 | 1.237692 |
def stop(signum, frame):
self.log.info('Shutting down RQ scheduler...')
self.register_death()
self.remove_lock()
raise SystemExit()
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) | def _install_signal_handlers(self) | Installs signal handlers for handling SIGINT and SIGTERM
gracefully. | 5.479716 | 4.845957 | 1.130781 |
if args is None:
args = ()
if kwargs is None:
kwargs = {}
job = self.job_class.create(
func, args=args, connection=self.connection,
kwargs=kwargs, result_ttl=result_ttl, ttl=ttl, id=id,
description=description, time... | def _create_job(self, func, args=None, kwargs=None, commit=True,
result_ttl=None, ttl=None, id=None, description=None,
queue_name=None, timeout=None, meta=None) | Creates an RQ job and saves it to Redis. | 2.084938 | 2.091617 | 0.996807 |
timeout = kwargs.pop('timeout', None)
job_id = kwargs.pop('job_id', None)
job_ttl = kwargs.pop('job_ttl', None)
job_result_ttl = kwargs.pop('job_result_ttl', None)
job_description = kwargs.pop('job_description', None)
meta = kwargs.pop('meta', None)
job ... | def enqueue_at(self, scheduled_time, func, *args, **kwargs) | Pushes a job to the scheduler queue. The scheduled queue is a Redis sorted
set ordered by timestamp - which in this case is job's scheduled execution time.
All args and kwargs are passed onto the job, except for the following kwarg
keys (which affect the job creation itself):
- timeout
... | 2.161298 | 1.959494 | 1.102988 |
timeout = kwargs.pop('timeout', None)
job_id = kwargs.pop('job_id', None)
job_ttl = kwargs.pop('job_ttl', None)
job_result_ttl = kwargs.pop('job_result_ttl', None)
job_description = kwargs.pop('job_description', None)
meta = kwargs.pop('meta', None)
job ... | def enqueue_in(self, time_delta, func, *args, **kwargs) | Similar to ``enqueue_at``, but accepts a timedelta instead of datetime object.
The job's scheduled execution time will be calculated by adding the timedelta
to datetime.utcnow(). | 2.297798 | 2.143386 | 1.072041 |
# Set result_ttl to -1 for periodic jobs, if result_ttl not specified
if interval is not None and result_ttl is None:
result_ttl = -1
job = self._create_job(func, args=args, kwargs=kwargs, commit=False,
result_ttl=result_ttl, ttl=ttl, id=id,
... | def schedule(self, scheduled_time, func, args=None, kwargs=None,
interval=None, repeat=None, result_ttl=None, ttl=None,
timeout=None, id=None, description=None, queue_name=None,
meta=None) | Schedule a job to be periodically executed, at a certain interval. | 2.783792 | 2.91779 | 0.954075 |
scheduled_time = get_next_scheduled_time(cron_string)
# Set result_ttl to -1, as jobs scheduled via cron are periodic ones.
# Otherwise the job would expire after 500 sec.
job = self._create_job(func, args=args, kwargs=kwargs, commit=False,
result... | def cron(self, cron_string, func, args=None, kwargs=None, repeat=None,
queue_name=None, id=None, timeout=None, description=None, meta=None) | Schedule a cronjob | 3.989704 | 4.067139 | 0.980961 |
if isinstance(job, self.job_class):
self.connection.zrem(self.scheduled_jobs_key, job.id)
else:
self.connection.zrem(self.scheduled_jobs_key, job) | def cancel(self, job) | Pulls a job from the scheduler queue. This function accepts either a
job_id or a job instance. | 2.949404 | 2.660244 | 1.108697 |
with self.connection.pipeline() as pipe:
while 1:
try:
pipe.watch(self.scheduled_jobs_key)
if pipe.zscore(self.scheduled_jobs_key, job.id) is None:
raise ValueError('Job not in scheduled jobs queue')
... | def change_execution_time(self, job, date_time) | Change a job's execution time. | 3.004209 | 2.957281 | 1.015869 |
until = rationalize_until(until)
return self.connection.zcount(self.scheduled_jobs_key, 0, until) | def count(self, until=None) | Returns the total number of jobs that are scheduled for all queues.
This function accepts datetime, timedelta instances as well as
integers representing epoch values. | 14.671238 | 8.006568 | 1.8324 |
def epoch_to_datetime(epoch):
return from_unix(float(epoch))
until = rationalize_until(until)
job_ids = self.connection.zrangebyscore(self.scheduled_jobs_key, 0,
until, withscores=with_times,
... | def get_jobs(self, until=None, with_times=False, offset=None, length=None) | Returns a iterator of job instances that will be queued until the given
time. If no 'until' argument is given all jobs are returned.
If with_times is True, a list of tuples consisting of the job instance
and it's scheduled execution time is returned.
If offset and length are specified,... | 3.090175 | 3.291712 | 0.938775 |
return self.get_jobs(to_unix(datetime.utcnow()), with_times=with_times) | def get_jobs_to_queue(self, with_times=False) | Returns a list of job instances that should be queued
(score lower than current timestamp).
If with_times is True a list of tuples consisting of the job instance and
it's scheduled execution time is returned. | 6.874554 | 7.635552 | 0.900335 |
if self._queue is not None:
return self._queue
key = '{0}{1}'.format(self.queue_class.redis_queue_namespace_prefix,
job.origin)
return self.queue_class.from_queue_key(
key, connection=self.connection, job_class=self.job_class) | def get_queue_for_job(self, job) | Returns a queue to put job into. | 4.984747 | 4.521697 | 1.102406 |
self.log.debug('Pushing {0} to {1}'.format(job.id, job.origin))
interval = job.meta.get('interval', None)
repeat = job.meta.get('repeat', None)
cron_string = job.meta.get('cron_string', None)
# If job is a repeated job, decrement counter
if repeat:
... | def enqueue_job(self, job) | Move a scheduled job to a queue. In addition, it also does puts the job
back into the scheduler if needed. | 2.5113 | 2.4433 | 1.027831 |
self.log.debug('Checking for scheduled jobs')
jobs = self.get_jobs_to_queue()
for job in jobs:
self.enqueue_job(job)
# Refresh scheduler key's expiry
self.connection.expire(self.scheduler_key, int(self._interval) + 10)
return jobs | def enqueue_jobs(self) | Move scheduled jobs into queues. | 6.260064 | 5.518902 | 1.134295 |
self.register_birth()
self._install_signal_handlers()
try:
while True:
self.log.debug("Entering run loop")
start_time = time.time()
if self.acquire_lock():
self.enqueue_jobs()
self.rem... | def run(self, burst=False) | Periodically check whether there's any job that should be put in the queue (score
lower than current time). | 3.917091 | 3.679434 | 1.064591 |
dim1 = len(arrays)
dim2, dim3 = arrays[0].shape
for aa in range(1, dim1):
dim2_aa, dim3_aa = arrays[aa].shape
if (dim2_aa != dim2) or (dim3_aa != dim3):
raise _error.InvalidError(_MDPERR["obj_square"])
return dim1, dim2, dim3 | def _checkDimensionsListLike(arrays) | Check that each array in a list of arrays has the same size. | 4.171216 | 4.111208 | 1.014596 |
try:
lenR = len(reward)
if lenR == n_actions:
dim1, dim2, dim3 = _checkDimensionsListLike(reward)
elif lenR == n_states:
dim1 = n_actions
dim2 = dim3 = lenR
else:
raise _error.InvalidError(_MDPERR["R_shape"])
except AttributeEr... | def _checkRewardsListLike(reward, n_actions, n_states) | Check that a list-like reward input is valid. | 3.915311 | 3.723277 | 1.051577 |
try:
try:
dim1, dim2 = matrix.shape
except AttributeError:
dim1, dim2 = _np.array(matrix).shape
except ValueError:
return False
if dim1 == dim2:
return True
return False | def isSquare(matrix) | Check that ``matrix`` is square.
Returns
=======
is_square : bool
``True`` if ``matrix`` is square, ``False`` otherwise. | 3.373586 | 2.94892 | 1.144007 |
try:
absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])))
except AttributeError:
matrix = _np.array(matrix)
absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])))
return (absdiff.max() <= 10*_np.spacing(_np.float64(1))) | def isStochastic(matrix) | Check that ``matrix`` is row stochastic.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is row stochastic, ``False`` otherwise. | 2.807722 | 2.840573 | 0.988435 |
try:
if (matrix >= 0).all():
return True
except (NotImplementedError, AttributeError, TypeError):
try:
if (matrix.data >= 0).all():
return True
except AttributeError:
matrix = _np.array(matrix)
if (matrix.data >= 0).all... | def isNonNegative(matrix) | Check that ``matrix`` is row non-negative.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is non-negative, ``False`` otherwise. | 2.654172 | 2.83699 | 0.935559 |
if not isSquare(matrix):
raise _error.SquareError
if not isStochastic(matrix):
raise _error.StochasticError
if not isNonNegative(matrix):
raise _error.NonNegativeError | def checkSquareStochastic(matrix) | Check if ``matrix`` is a square and row-stochastic.
To pass the check the following conditions must be met:
* The matrix should be square, so the number of columns equals the
number of rows.
* The matrix should be row-stochastic so the rows should sum to one.
* Each value in the matrix must be p... | 3.008733 | 3.640485 | 0.826465 |
# Checking P
try:
if P.ndim == 3:
aP, sP0, sP1 = P.shape
elif P.ndim == 1:
aP, sP0, sP1 = _checkDimensionsListLike(P)
else:
raise _error.InvalidError(_MDPERR["P_shape"])
except AttributeError:
try:
aP, sP0, sP1 = _checkDime... | def check(P, R) | Check if ``P`` and ``R`` define a valid Markov Decision Process (MDP).
Let ``S`` = number of states, ``A`` = number of actions.
Arguments
---------
P : array
The transition matrices. It can be a three dimensional array with
a shape of (A, S, S). It can also be a one dimensional arraye ... | 2.305199 | 2.274221 | 1.013621 |
#assert isValid(state)
assert 0 <= action < ACTIONS
if not isLegal(state, action):
# If the action is illegal, then transition back to the same state but
# incur a high negative reward
s1 = [convertTupleToIndex(state)]
return(s1, [1], -10)
# Update the state with the... | def getTransitionProbabilities(state, action) | Parameters
----------
state : tuple
The state
action : int
The action
Returns
-------
s1, p, r : tuple of two lists and an int
s1 are the next states, p are the probabilities, and r is the reward | 3.677091 | 3.500964 | 1.050308 |
for w in WINS:
S = sum(1 if (w[k] == 1 and state[k] == who) else 0
for k in range(ACTIONS))
if S == 3:
# We have a win
return True
# There were no wins so return False
return False | def isWon(state, who) | Test if a tic-tac-toe game has been won.
Assumes that the board is in a legal state.
Will test if the value 1 is in any winning combination. | 5.062378 | 5.026171 | 1.007204 |
db = "MDP-%sx%s.db" % (S, A)
if os.path.exists(db):
os.remove(db)
conn = sqlite3.connect(db)
with conn:
c = conn.cursor()
cmd = '''
CREATE TABLE info (name TEXT, value INTEGER);
INSERT INTO info VALUES('states', %s);
INSERT INTO info VALUE... | def exampleRand(S, A) | WARNING: This will delete a database with the same name as 'db'. | 3.690295 | 3.627264 | 1.017377 |
cmd = '''
UPDATE policy
SET action = (
SELECT action
FROM (SELECT state, action, MAX(value)
FROM Q
GROUP BY state) AS A
WHERE policy.state = A.s... | def _calculatePolicy(self) | This implements argmax() over the actions of Q. | 7.74223 | 6.157464 | 1.257373 |
cmd = '''
UPDATE V
SET value = (
SELECT MAX(value)
FROM Q
WHERE V.state = Q.state
GROUP BY state);'''
self._cur.execute(cmd)
self._conn.commit() | def _calculateValue(self) | This is max() over the actions of Q. | 10.53673 | 7.003869 | 1.504416 |
self._cur.execute("SELECT action FROM policy")
r = self._cur.fetchall()
policy = [x[0] for x in r]
self._cur.execute("SELECT value FROM V")
r = self._cur.fetchall()
value = [x[0] for x in r]
return policy, value | def getPolicyValue(self) | Get the policy and value vectors. | 2.834433 | 2.449883 | 1.156966 |
assert 0 <= population < POPULATION_CLASSES, "'population' must be in " \
"(0, 1...%s)" % str(POPULATION_CLASSES - 1)
assert 0 <= fire < FIRE_CLASSES, "'fire' must be in " \
"(0, 1...%s) " % str(FIRE_CLASSES - 1)
return(population * FIRE_CLASSES + fire) | def convertStateToIndex(population, fire) | Convert state parameters to transition probability matrix index.
Parameters
----------
population : int
The population abundance class of the threatened species.
fire : int
The time in years since last fire.
Returns
-------
index : int
The index into the tra... | 2.861131 | 3.247838 | 0.880934 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.