INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Load from native memory.
def _load_from_native_memory(self, addr, data_type=None, data_size=None, no_of_elements=1, return_as_list=False): """ Load from native memory. :param addr: Native load address. :param data_type: Java type of elements. ...
Load zero terminated UTF - 8 string from native memory.
def _load_string_from_native_memory(self, addr_): """ Load zero terminated UTF-8 string from native memory. :param addr_: Native load address. :return: Loaded string. """ # check if addr is symbolic if self.state.solver.symbolic(addr_): l.error("...
Store given string UTF - 8 encoded and zero terminated in native memory.
def _store_string_in_native_memory(self, string, addr=None): """ Store given string UTF-8 encoded and zero terminated in native memory. :param str string: String :param addr: Native store address. If not set, native memory is allocated. :retur...
In Java all array indices are represented by a 32 bit integer and consequently we are using in the Soot engine a 32bit bitvector for this. This function normalize the given index to follow this convention.
def _normalize_array_idx(self, idx): """ In Java, all array indices are represented by a 32 bit integer and consequently we are using in the Soot engine a 32bit bitvector for this. This function normalize the given index to follow this "convention". :return: Index as a 32bit bit...
Given the target target apply the hooks given as keyword arguments to it. If any targeted method has already been hooked the hooks will not be overridden but will instead be pushed into a list of pending hooks. The final behavior should be that all hooks call each other in a nested stack.
def install_hooks(target, **hooks): """ Given the target `target`, apply the hooks given as keyword arguments to it. If any targeted method has already been hooked, the hooks will not be overridden but will instead be pushed into a list of pending hooks. The final behavior should be that...
Remove the given hooks from the given target.
def remove_hooks(target, **hooks): """ Remove the given hooks from the given target. :param target: The object from which to remove hooks. If all hooks are removed from a given method, the HookedMethod object will be removed and replaced with the original function. ...
Reset the internal node traversal state. Must be called prior to visiting future nodes.
def reset(self): """ Reset the internal node traversal state. Must be called prior to visiting future nodes. :return: None """ self._sorted_nodes.clear() self._node_to_index.clear() self._reached_fixedpoint.clear() for i, n in enumerate(self.sort_nodes(...
Returns all successors to the specific node.
def all_successors(self, node, skip_reached_fixedpoint=False): """ Returns all successors to the specific node. :param node: A node in the graph. :return: A set of nodes that are all successors to the given node. :rtype: set """ successors = set() ...
Revisit a node in the future. As a result the successors to this node will be revisited as well.
def revisit(self, node, include_self=True): """ Revisit a node in the future. As a result, the successors to this node will be revisited as well. :param node: The node to revisit in the future. :return: None """ successors = self.successors(node) #, skip_reached_fix...
Appended a new job to this JobInfo node.: param job: The new job to append.: param bool merged: Whether it is a merged job or not.: param bool widened: Whether it is a widened job or not.
def add_job(self, job, merged=False, widened=False): """ Appended a new job to this JobInfo node. :param job: The new job to append. :param bool merged: Whether it is a merged job or not. :param bool widened: Whether it is a widened job or not. """ job_type = '' ...
Checks whether there exists another job which has the same job key.: param job: The job to check.
def has_job(self, job): """ Checks whether there exists another job which has the same job key. :param job: The job to check. :return: True if there exists another job with the same key, False otherwise. """ job_key = self._job_key(job) return job_key in self....
The main analysis routine.
def _analyze(self): """ The main analysis routine. :return: None """ self._pre_analysis() if self._graph_visitor is None: # There is no base graph that we can rely on. The analysis itself should generate successors for the # current job. ...
Add the input state to all successors of the given node.
def _add_input_state(self, node, input_state): """ Add the input state to all successors of the given node. :param node: The node whose successors' input states will be touched. :param input_state: The state that will be added to successors of the node. :return: ...
Get the input abstract state for this node and remove it from the state map.
def _pop_input_state(self, node): """ Get the input abstract state for this node, and remove it from the state map. :param node: The node in graph. :return: A merged state, or None if there is no input state for this node available. """ if node in self._state_map: ...
Get abstract states for all predecessors of the node merge them and return the merged state.
def _merge_state_from_predecessors(self, node): """ Get abstract states for all predecessors of the node, merge them, and return the merged state. :param node: The node in graph. :return: A merged state, or None if no predecessor is available. """ preds = self._grap...
Process a job get all successors of this job and call _handle_successor () to handle each successor.
def _process_job_and_get_successors(self, job_info): """ Process a job, get all successors of this job, and call _handle_successor() to handle each successor. :param JobInfo job_info: The JobInfo instance :return: None """ job = job_info.job successors = self._...
Insert a new job into the job queue. If the job queue is ordered this job will be inserted at the correct position.
def _insert_job(self, job): """ Insert a new job into the job queue. If the job queue is ordered, this job will be inserted at the correct position. :param job: The job to insert :return: None """ key = self._job_key(job) if self._allow_merging: ...
Return the job currently at position pos but still keep it in the job queue. An IndexError will be raised if that position does not currently exist in the job list.
def _peek_job(self, pos): """ Return the job currently at position `pos`, but still keep it in the job queue. An IndexError will be raised if that position does not currently exist in the job list. :param int pos: Position of the job to get. :return: The job """ ...
Insert an element into a sorted list and keep the list sorted.
def _binary_insert(lst, elem, key, lo=0, hi=None): """ Insert an element into a sorted list, and keep the list sorted. The major difference from bisect.bisect_left is that this function supports a key method, so user doesn't have to create the key array for each insertion. :par...
Merge this SimMemory with the other SimMemory
def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument """ Merge this SimMemory with the other SimMemory """ changed_bytes = self._changes_to_merge(others) l.info("Merging %d bytes", len(changed_bytes)) l.info("... %s has chan...
Replaces length bytes starting at addr with a symbolic variable named name. Adds a constraint equaling that symbolic variable to the value previously at addr and returns the variable.
def make_symbolic(self, name, addr, length=None): """ Replaces `length` bytes starting at `addr` with a symbolic variable named name. Adds a constraint equaling that symbolic variable to the value previously at `addr`, and returns the variable. """ l.debug("making %s bytes symbol...
Applies concretization strategies on the address until one of them succeeds.
def _apply_concretization_strategies(self, addr, strategies, action): """ Applies concretization strategies on the address until one of them succeeds. """ # we try all the strategies in order for s in strategies: # first, we trigger the SimInspect breakpoint and give...
Concretizes an address meant for writing.
def concretize_write_addr(self, addr, strategies=None): """ Concretizes an address meant for writing. :param addr: An expression for the address. :param strategies: A list of concretization strategies (to override the default). :returns: ...
Concretizes an address meant for reading.
def concretize_read_addr(self, addr, strategies=None): """ Concretizes an address meant for reading. :param addr: An expression for the address. :param strategies: A list of concretization strategies (to override the default). :returns: ...
Print out debugging information.
def dbg_print(self, indent=0): """ Print out debugging information. """ lst = [] more_data = False for i, addr in enumerate(self.mem.keys()): lst.append(addr) if i >= 20: more_data = True break for addr in s...
Retrieve the permissions of the page at address addr.
def permissions(self, addr, permissions=None): """ Retrieve the permissions of the page at address `addr`. :param addr: address to get the page permissions :param permissions: Integer or BVV to optionally set page permissions to :return: AST representing the pe...
Map a number of pages at address addr with permissions permissions.: param addr: address to map the pages at: param length: length in bytes of region to map will be rounded upwards to the page size: param permissions: AST of permissions to map will be a bitvalue representing flags: param init_zero: Initialize page with...
def map_region(self, addr, length, permissions, init_zero=False): """ Map a number of pages at address `addr` with permissions `permissions`. :param addr: address to map the pages at :param length: length in bytes of region to map, will be rounded upwards to the page size :param ...
Perform execution using any applicable engine. Enumerate the current engines and use the first one that works. Return a SimSuccessors object classifying the results of the run.
def successors(self, *args, **kwargs): """ Perform execution using any applicable engine. Enumerate the current engines and use the first one that works. Return a SimSuccessors object classifying the results of the run. :param state: The state to analyze :param addr: ...
Returns a state object initialized to the start of a given function as if it were called with given parameters.
def call_state(self, addr, *args, **kwargs): """ Returns a state object initialized to the start of a given function, as if it were called with given parameters. :param addr: The address the state should start at instead of the entry point. :param args: Any additio...
Constructs a new simulation manager.
def simulation_manager(self, thing=None, **kwargs): """ Constructs a new simulation manager. :param thing: Optional - What to put in the new SimulationManager's active stash (either a SimState or a list of SimStates). :param kwargs: Any additional keyword arguments wi...
A Callable is a representation of a function in the binary that can be interacted with like a native python function.
def callable(self, addr, concrete_only=False, perform_merge=True, base_state=None, toc=None, cc=None): """ A Callable is a representation of a function in the binary that can be interacted with like a native python function. :param addr: The address of the function to use ...
Return a SimCC ( calling convention ) parametrized for this project and optionally a given function.
def cc(self, args=None, ret_val=None, sp_delta=None, func_ty=None): """ Return a SimCC (calling convention) parametrized for this project and, optionally, a given function. :param args: A list of argument storage locations, as SimFunctionArguments. :param ret_val: The return ...
Get a SimCC ( calling convention ) that will extract floating - point/ integral args correctly.
def cc_from_arg_kinds(self, fp_args, ret_fp=None, sizes=None, sp_delta=None, func_ty=None): """ Get a SimCC (calling convention) that will extract floating-point/integral args correctly. :param arch: The Archinfo arch for this CC :param fp_args: A list, with one entry for eac...
An iterator of all local blocks in the current function.
def blocks(self): """ An iterator of all local blocks in the current function. :return: angr.lifter.Block instances. """ for block_addr, block in self._local_blocks.items(): try: yield self._get_block(block_addr, size=block.size, ...
All of the operations that are done by this functions.
def operations(self): """ All of the operations that are done by this functions. """ return [op for block in self.blocks for op in block.vex.operations]
All of the constants that are used by this functions s code.
def code_constants(self): """ All of the constants that are used by this functions's code. """ # TODO: remove link register values return [const.value for block in self.blocks for const in block.vex.constants]
All of the constant string references used by this function.
def string_references(self, minimum_length=2, vex_only=False): """ All of the constant string references used by this function. :param minimum_length: The minimum length of strings to find (default is 1) :param vex_only: Only analyze VEX IR, don't interpret the entry state to de...
Tries to find all runtime values of this function which do not come from inputs. These values are generated by starting from a blank state and reanalyzing the basic blocks once each. Function calls are skipped and back edges are never taken so these values are often unreliable This function is good at finding simple co...
def local_runtime_values(self): """ Tries to find all runtime values of this function which do not come from inputs. These values are generated by starting from a blank state and reanalyzing the basic blocks once each. Function calls are skipped, and back edges are never taken so these v...
All of the concrete values used by this function at runtime ( i. e. including passed - in arguments and global values ).
def runtime_values(self): """ All of the concrete values used by this function at runtime (i.e., including passed-in arguments and global values). """ constants = set() for b in self.block_addrs: for sirsb in self._function_manager._cfg.get_all_irsbs(b): ...
Get the object this function belongs to.: return: The object this function belongs to.
def binary(self): """ Get the object this function belongs to. :return: The object this function belongs to. """ return self._project.loader.find_object_containing(self.addr, membership_check=False)
Add a custom jumpout site.
def add_jumpout_site(self, node): """ Add a custom jumpout site. :param node: The address of the basic block that control flow leaves during this transition. :return: None """ self._register_nodes(True, node) self._jumpout_sites.add(node) self....
Add a custom retout site.
def add_retout_site(self, node): """ Add a custom retout site. Retout (returning to outside of the function) sites are very rare. It mostly occurs during CFG recovery when we incorrectly identify the beginning of a function in the first iteration, and then correctly identify that ...
Determine the most suitable name of the function.
def _get_initial_name(self): """ Determine the most suitable name of the function. :return: The initial function name. :rtype: string """ name = None addr = self.addr # Try to get a name from existing labels if self._function_manager is n...
Determine the name of the binary where this function is.
def _get_initial_binary_name(self): """ Determine the name of the binary where this function is. :return: None """ binary_name = None # if this function is a simprocedure but not a syscall, use its library name as # its binary name # if it is a syscall,...
Determine if this function returns or not * if it is hooked by a SimProcedure or a user hook *.
def _get_initial_returning(self): """ Determine if this function returns or not *if it is hooked by a SimProcedure or a user hook*. :return: True if the hooker returns, False otherwise. :rtype: bool """ hooker = None if self.is_syscall: hooker...
Registers an edge between basic blocks in this function s transition graph. Arguments are CodeNode objects.
def _transit_to(self, from_node, to_node, outside=False, ins_addr=None, stmt_idx=None): """ Registers an edge between basic blocks in this function's transition graph. Arguments are CodeNode objects. :param from_node The address of the basic block that control ...
Registers an edge between the caller basic block and callee function.
def _call_to(self, from_node, to_func, ret_node, stmt_idx=None, ins_addr=None, return_to_outside=False): """ Registers an edge between the caller basic block and callee function. :param from_addr: The basic block that control flow leaves during the transition. :type from_addr: angr...
Registers a basic block as a site for control flow to return from this function.
def _add_return_site(self, return_site): """ Registers a basic block as a site for control flow to return from this function. :param CodeNode return_site: The block node that ends with a return. """ self._register_nodes(True, return_site) self._ret_sites.add(return_...
Registers a basic block as calling a function and returning somewhere.
def _add_call_site(self, call_site_addr, call_target_addr, retn_addr): """ Registers a basic block as calling a function and returning somewhere. :param call_site_addr: The address of a basic block that ends in a call. :param call_target_addr: The address of the target of said...
Iterate through all call edges in transition graph. For each call a non - returning function mark the source basic block as an endpoint.
def mark_nonreturning_calls_endpoints(self): """ Iterate through all call edges in transition graph. For each call a non-returning function, mark the source basic block as an endpoint. This method should only be executed once all functions are recovered and analyzed by CFG recovery, so ...
Return a local transition graph that only contain nodes in current function.
def graph(self): """ Return a local transition graph that only contain nodes in current function. """ if self._local_transition_graph is not None: return self._local_transition_graph g = networkx.DiGraph() if self.startpoint is not None: g.add_no...
Generate a sub control flow graph of instruction addresses based on self. graph
def subgraph(self, ins_addrs): """ Generate a sub control flow graph of instruction addresses based on self.graph :param iterable ins_addrs: A collection of instruction addresses that should be included in the subgraph. :return: A subgraph. :rtype: networkx.DiGraph """ ...
Get the size of the instruction specified by insn_addr.
def instruction_size(self, insn_addr): """ Get the size of the instruction specified by `insn_addr`. :param int insn_addr: Address of the instruction :return: Size of the instruction in bytes, or None if the instruction is not found. :rtype: int """ for b in sel...
Draw the graph and save it to a PNG file.
def dbg_draw(self, filename): """ Draw the graph and save it to a PNG file. """ import matplotlib.pyplot as pyplot # pylint: disable=import-error from networkx.drawing.nx_agraph import graphviz_layout # pylint: disable=import-error tmp_graph = networkx.DiGraph() ...
Registers a register offset as being used as an argument to the function.
def _add_argument_register(self, reg_offset): """ Registers a register offset as being used as an argument to the function. :param reg_offset: The offset of the register to register. """ if reg_offset in self._function_manager._arg_registers and \ re...
Make sure all basic blocks in the transition graph of this function do not overlap. You will end up with a CFG that IDA Pro generates.
def normalize(self): """ Make sure all basic blocks in the transition graph of this function do not overlap. You will end up with a CFG that IDA Pro generates. This method does not touch the CFG result. You may call CFG{Emulated, Fast}.normalize() for that matter. :return: None...
Find the most likely function declaration from the embedded collection of prototypes set it to self. prototype and update self. calling_convention with the declaration.
def find_declaration(self): """ Find the most likely function declaration from the embedded collection of prototypes, set it to self.prototype, and update self.calling_convention with the declaration. :return: None """ # determine the library name if not self.i...
Reverse look - up.
def _rfind(lst, item): """ Reverse look-up. :param list lst: The list to look up in. :param item: The item to look for. :return: Offset of the item if found. A ValueError is raised if the item is not in the list. :rtype: int """ try: return d...
Push the frame cf onto the stack. Return the new stack.
def push(self, cf): """ Push the frame cf onto the stack. Return the new stack. """ cf.next = self if self.state is not None: self.state.register_plugin('callstack', cf) self.state.history.recent_stack_actions.append(CallStackAction( hash(c...
Pop the top frame from the stack. Return the new stack.
def pop(self): """ Pop the top frame from the stack. Return the new stack. """ if self.next is None: raise SimEmptyCallStackError("Cannot pop a frame from an empty call stack.") new_list = self.next.copy({}) if self.state is not None: self.state.r...
Push a stack frame into the call stack. This method is called when calling a function in CFG recovery.
def call(self, callsite_addr, addr, retn_target=None, stack_pointer=None): """ Push a stack frame into the call stack. This method is called when calling a function in CFG recovery. :param int callsite_addr: Address of the call site :param int addr: Address of the call target :p...
Pop one or many call frames from the stack. This method is called when returning from a function in CFG recovery.
def ret(self, retn_target=None): """ Pop one or many call frames from the stack. This method is called when returning from a function in CFG recovery. :param int retn_target: The target to return to. :return: None """ if retn_target is None: return s...
Debugging representation of this CallStack object.
def dbg_repr(self): """ Debugging representation of this CallStack object. :return: Details of this CalLStack :rtype: str """ stack = [ ] for i, frame in enumerate(self): s = "%d | %s -> %s, returning to %s" % ( i, "No...
Generate the stack suffix. A stack suffix can be used as the key to a SimRun in CFG recovery.
def stack_suffix(self, context_sensitivity_level): """ Generate the stack suffix. A stack suffix can be used as the key to a SimRun in CFG recovery. :param int context_sensitivity_level: Level of context sensitivity. :return: A tuple of stack suffix. :rtype: tuple """ ...
Check if the return target exists in the stack and return the index if exists. We always search from the most recent call stack frame since the most recent frame has a higher chance to be hit in normal CFG recovery.
def _find_return_target(self, target): """ Check if the return target exists in the stack, and return the index if exists. We always search from the most recent call stack frame since the most recent frame has a higher chance to be hit in normal CFG recovery. :param int target: Target o...
获取所有股票 ID 到 all_stock_code 目录下
def update_stock_codes(): """获取所有股票 ID 到 all_stock_code 目录下""" all_stock_codes_url = "http://www.shdjt.com/js/lib/astock.js" grep_stock_codes = re.compile(r"~(\d+)`") response = requests.get(all_stock_codes_url) all_stock_codes = grep_stock_codes.findall(response.text) with open(stock_code_path(...
获取所有股票 ID 到 all_stock_code 目录下
def get_stock_codes(realtime=False): """获取所有股票 ID 到 all_stock_code 目录下""" if realtime: all_stock_codes_url = "http://www.shdjt.com/js/lib/astock.js" grep_stock_codes = re.compile(r"~(\d+)`") response = requests.get(all_stock_codes_url) stock_codes = grep_stock_codes.findall(respo...
return specific stocks real quotation: param stock_codes: stock code or list of stock code when prefix is True stock code must start with sh/ sz: param prefix: if prefix i True stock_codes must contain sh/ sz market flag. If prefix is False index quotation can t return: return quotation dict key is stock_code value is ...
def real(self, stock_codes, prefix=False): """return specific stocks real quotation :param stock_codes: stock code or list of stock code, when prefix is True, stock code must start with sh/sz :param prefix: if prefix i True, stock_codes must contain sh/sz market flag....
return all market quotation snapshot: param prefix: if prefix is True return quotation dict s stock_code key start with sh/ sz market flag
def market_snapshot(self, prefix=False): """return all market quotation snapshot :param prefix: if prefix is True, return quotation dict's stock_code key start with sh/sz market flag """ return self.get_stock_data(self.stock_list, prefix=prefix)
获取并格式化股票信息
def get_stock_data(self, stock_list, **kwargs): """获取并格式化股票信息""" res = self._fetch_stock_data(stock_list) return self.format_response_data(res, **kwargs)
获取股票信息
def _fetch_stock_data(self, stock_list): """获取股票信息""" pool = multiprocessing.pool.ThreadPool(len(stock_list)) try: res = pool.map(self.get_stocks_by_range, stock_list) finally: pool.close() return [d for d in res if d is not None]
因为 timekline 的返回没有带对应的股票代码,所以要手动带上
def _fetch_stock_data(self, stock_list): """因为 timekline 的返回没有带对应的股票代码,所以要手动带上""" res = super()._fetch_stock_data(stock_list) with_stock = [] for stock, resp in zip(stock_list, res): if resp is not None: with_stock.append((stock, resp)) return with_st...
格式化集思录返回的json数据 以字典形式保存
def formatfundajson(fundajson): """格式化集思录返回的json数据,以字典形式保存""" result = {} for row in fundajson["rows"]: funda_id = row["id"] cell = row["cell"] result[funda_id] = cell return result
格式化集思录返回的json数据 以字典形式保存
def formatfundbjson(fundbjson): """格式化集思录返回的json数据,以字典形式保存""" result = {} for row in fundbjson["rows"]: cell = row["cell"] fundb_id = cell["fundb_id"] result[fundb_id] = cell return result
格式化集思录返回 指数ETF 的json数据 以字典形式保存
def formatetfindexjson(fundbjson): """格式化集思录返回 指数ETF 的json数据,以字典形式保存""" result = {} for row in fundbjson["rows"]: cell = row["cell"] fundb_id = cell["fund_id"] result[fundb_id] = cell return result
以字典形式返回分级A数据: param fields: 利率范围,形如 [ + 3. 0% 6. 0% ]: param min_volume: 最小交易量,单位万元: param min_discount: 最小折价率 单位%: param ignore_nodown: 是否忽略无下折品种 默认 False: param forever: 是否选择永续品种 默认 False
def funda( self, fields=None, min_volume=0, min_discount=0, ignore_nodown=False, forever=False, ): """以字典形式返回分级A数据 :param fields:利率范围,形如['+3.0%', '6.0%'] :param min_volume:最小交易量,单位万元 :param min_discount:最小折价率, 单位% :param ignore_...
以字典形式返回分级母基数据
def fundm(self): """以字典形式返回分级母基数据 """ # 添加当前的ctime self.__fundm_url = self.__fundm_url.format(ctime=int(time.time())) # 请求数据 rep = requests.get(self.__fundm_url) # 获取返回的json字符串 fundmjson = json.loads(rep.text) # 格式化返回的json字符串 data = self.fo...
以字典形式返回分级B数据: param fields: 利率范围,形如 [ + 3. 0% 6. 0% ]: param min_volume: 最小交易量,单位万元: param min_discount: 最小折价率 单位%: param forever: 是否选择永续品种 默认 False
def fundb(self, fields=None, min_volume=0, min_discount=0, forever=False): """以字典形式返回分级B数据 :param fields:利率范围,形如['+3.0%', '6.0%'] :param min_volume:最小交易量,单位万元 :param min_discount:最小折价率, 单位% :param forever: 是否选择永续品种,默认 False """ if fields is None: field...
以字典形式返回分级A数据: param jsl_username: 集思录用户名: param jsl_password: 集思路登录密码: param avolume: A成交额,单位百万: param bvolume: B成交额,单位百万: param ptype: 溢价计算方式,price = 现价,buy = 买一,sell = 卖一
def fundarb( self, jsl_username, jsl_password, avolume=100, bvolume=100, ptype="price", ): """以字典形式返回分级A数据 :param jsl_username: 集思录用户名 :param jsl_password: 集思路登录密码 :param avolume: A成交额,单位百万 :param bvolume: B成交额,单位百万 :par...
以字典形式返回 指数ETF 数据: param index_id: 获取指定的指数: param min_volume: 最小成交量: param min_discount: 最低溢价率 适用于溢价套利 格式 - 1. 2% - 1. 2 - 0. 012 三种均可: param max_discount: 最高溢价率 适用于折价套利 格式 - 1. 2% - 1. 2 - 0. 012 三种均可: return: { fund_id: {} }
def etfindex( self, index_id="", min_volume=0, max_discount=None, min_discount=None ): """ 以字典形式返回 指数ETF 数据 :param index_id: 获取指定的指数 :param min_volume: 最小成交量 :param min_discount: 最低溢价率, 适用于溢价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可 :param max_discount: 最高溢价率, 适用于折价...
以字典形式返回QDII数据: param min_volume: 最小交易量,单位万元
def qdii(self, min_volume=0): """以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元 """ # 添加当前的ctime self.__qdii_url = self.__qdii_url.format(ctime=int(time.time())) # 请求数据 rep = requests.get(self.__qdii_url) # 获取返回的json字符串 fundjson = json.loads(rep.text) ...
以字典形式返回QDII数据: param min_volume: 最小交易量,单位万元
def cb(self, min_volume=0): """以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元 """ # 添加当前的ctime self.__cb_url = self.__cb_url.format(ctime=int(time.time())) # 请求数据 rep = requests.get(self.__cb_url) # 获取返回的json字符串 fundjson = json.loads(rep.text) ...
Update current date/ time.
def update(self): """Update current date/time.""" # Had to convert it to string because datetime is not JSON serializable self.stats = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Add the time zone (issue #1249 and issue #1337) if 'tmzone' in localtime(): self.stats...
Return the string to display in the curse interface.
def msg_curse(self, args=None, max_width=None): """Return the string to display in the curse interface.""" # Init the return message ret = [] # Build the string message # 23 is the padding for the process list msg = '{:23}'.format(self.stats) ret.append(self.curs...
Load the web list from the configuration file.
def load(self, config): """Load the web list from the configuration file.""" web_list = [] if config is None: logger.debug("No configuration file available. Cannot load ports list.") elif not config.has_section(self._section): logger.debug("No [%s] section in the...
Set the key to the value for the pos ( position in the list ).
def set_server(self, pos, key, value): """Set the key to the value for the pos (position in the list).""" self._web_list[pos][key] = value
Update sensors stats using the input method.
def update(self): """Update sensors stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the dedicated lib stats = [] # Get the temperature try: ...
Set the plugin type.
def __set_type(self, stats, sensor_type): """Set the plugin type. 4 types of stats is possible in the sensors plugin: - Core temperature: 'temperature_core' - Fan speed: 'fan_speed' - HDD temperature: 'temperature_hdd' - Battery capacity: 'battery' """ fo...
Return the dict to display in the curse interface.
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist and display plugin enable... if not self.stats or self.is_disable(): return ret # Max si...
Build the sensors list depending of the type.
def build_sensors_list(self, type): """Build the sensors list depending of the type. type: SENSOR_TEMP_UNIT or SENSOR_FAN_UNIT output: a list """ ret = [] if type == SENSOR_TEMP_UNIT and self.init_temp: input_list = self.stemps self.stemps = psut...
Get sensors list.
def get(self, sensor_type='temperature_core'): """Get sensors list.""" self.__update__() if sensor_type == 'temperature_core': ret = [s for s in self.sensors_list if s['unit'] == SENSOR_TEMP_UNIT] elif sensor_type == 'fan_speed': ret = [s for s in self.sensors_lis...
Add an user to the dictionary.
def add_user(self, username, password): """Add an user to the dictionary.""" self.server.user_dict[username] = password self.server.isAuth = True
Call the main loop.
def serve_forever(self): """Call the main loop.""" # Set the server login/password (if -P/--password tag) if self.args.password != "": self.add_user(self.args.username, self.args.password) # Serve forever self.server.serve_forever()
End of the Glances server session.
def end(self): """End of the Glances server session.""" if not self.args.disable_autodiscover: self.autodiscover_client.close() self.server.end()
Return the threshold dict. If stat_name is None return the threshold for all plugins ( dict of Threshold * ) Else return the Threshold * instance for the given plugin
def get(self, stat_name=None): """Return the threshold dict. If stat_name is None, return the threshold for all plugins (dict of Threshold*) Else return the Threshold* instance for the given plugin """ if stat_name is None: return self._thresholds if stat_nam...
Add a new threshold to the dict ( key = stat_name )
def add(self, stat_name, threshold_description): """Add a new threshold to the dict (key = stat_name)""" if threshold_description not in self.threshold_list: return False else: self._thresholds[stat_name] = getattr(self.current_module, ...
Init the connection to the rabbitmq server.
def init(self): """Init the connection to the rabbitmq server.""" if not self.export_enable: return None try: parameters = pika.URLParameters( 'amqp://' + self.user + ':' + self.password + '@' + self.host + '...
Write the points in RabbitMQ.
def export(self, name, columns, points): """Write the points in RabbitMQ.""" data = ('hostname=' + self.hostname + ', name=' + name + ', dateinfo=' + datetime.datetime.utcnow().isoformat()) for i in range(len(columns)): if not isinstance(points[i], Number): ...
Normalize name for the Statsd convention
def normalize(name): """Normalize name for the Statsd convention""" # Name should not contain some specials chars (issue #1068) ret = name.replace(':', '') ret = ret.replace('%', '') ret = ret.replace(' ', '_') return ret
Init the connection to the Statsd server.
def init(self): """Init the connection to the Statsd server.""" if not self.export_enable: return None logger.info( "Stats will be exported to StatsD server: {}:{}".format(self.host, self.port)) r...