_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q3000
formatted_str_to_val
train
def formatted_str_to_val(data, format, enum_set=None): """ Return an unsigned integer representation of the data given format specified. :param data: a string holding the value to convert :param format: a string holding a format which will be used to convert the data string :param enum_set: an iterable of enums which are used as part of the converstion process Given a string (not a wirevector!) covert that to an unsigned integer ready for input to the simulation enviornment. This helps deal with signed/unsigned numbers (simulation assumes the values have been converted via two's complement already), but it also takes hex, binary, and enum types as inputs. It is easiest to see how it works with some examples. :: formatted_str_to_val('2', 's3') == 2 # 0b010 formatted_str_to_val('-1', 's3') == 7 # 0b111 formatted_str_to_val('101', 'b3') == 5 formatted_str_to_val('5', 'u3') == 5 formatted_str_to_val('-3', 's3') == 5 formatted_str_to_val('a', 'x3') == 10 class Ctl(Enum): ADD = 5 SUB = 12 formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5 formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12 """ type = format[0] bitwidth = int(format[1:].split('/')[0]) bitmask =
python
{ "resource": "" }
q3001
val_to_formatted_str
train
def val_to_formatted_str(val, format, enum_set=None): """ Return a string representation of the value given format specified. :param val: a string holding an unsigned integer to convert :param format: a string holding a format which will be used to convert the data string :param enum_set: an iterable of enums which are used as part of the converstion process Given an unsigned integer (not a wirevector!) covert that to a strong ready for output to a human to interpret. This helps deal with signed/unsigned numbers (simulation operates on values that have been converted via two's complement), but it also generates hex, binary, and enum types as outputs. It is easiest to see how it works with some examples. :: formatted_str_to_val(2, 's3') == '2' formatted_str_to_val(7, 's3') == '-1' formatted_str_to_val(5, 'b3') == '101' formatted_str_to_val(5, 'u3') == '5' formatted_str_to_val(5, 's3') == '-3' formatted_str_to_val(10, 'x3') == 'a' class Ctl(Enum): ADD = 5 SUB = 12 formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5 formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12 """ type = format[0] bitwidth = int(format[1:].split('/')[0]) bitmask = (1 << bitwidth)-1
python
{ "resource": "" }
q3002
_NetCount.shrank
train
def shrank(self, block=None, percent_diff=0, abs_diff=1): """ Returns whether a block has less nets than before :param Block block: block to check (if changed) :param Number percent_diff: percentage difference threshold :param int abs_diff: absolute difference threshold :return: boolean This function checks whether the change in the number of nets is greater than the percentage and absolute difference thresholds. """ if
python
{ "resource": "" }
q3003
kogge_stone
train
def kogge_stone(a, b, cin=0): """ Creates a Kogge-Stone adder given two inputs :param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match) :param cin: An optimal carry in WireVector or value :return: a Wirevector representing the output of the adder The Kogge-Stone adder is a fast tree-based adder with O(log(n)) propagation delay, useful for performance critical designs. However, it has O(n log(n)) area usage, and large fan out. """ a, b = libutils.match_bitwidth(a, b) prop_orig = a ^ b prop_bits = [i for i in prop_orig] gen_bits = [i for i in a & b] prop_dist = 1 # creation of the carry calculation while prop_dist < len(a): for i
python
{ "resource": "" }
q3004
_cla_adder_unit
train
def _cla_adder_unit(a, b, cin): """ Carry generation and propogation signals will be calculated only using the inputs; their values don't rely on the sum. Every unit generates a cout signal which is used as cin for the next unit. """ gen = a & b prop = a ^ b assert(len(prop) == len(gen)) carry = [gen[0] | prop[0] & cin] sum_bit = prop[0] ^ cin cur_gen = gen[0] cur_prop
python
{ "resource": "" }
q3005
fast_group_adder
train
def fast_group_adder(wires_to_add, reducer=wallace_reducer, final_adder=kogge_stone): """ A generalization of the carry save adder, this is designed to add many numbers together in a both area and time efficient manner. Uses a tree reducer to achieve this performance :param [WireVector] wires_to_add: an array of wirevectors to add :param reducer: the tree reducer to use :param final_adder: The two value adder to use at the end :return: a wirevector with the result of the addition The length of the result is: max(len(w) for w in wires_to_add) + ceil(len(wires_to_add)) """ import math longest_wire_len = max(len(w) for w in wires_to_add)
python
{ "resource": "" }
q3006
MemBlock._build
train
def _build(self, addr, data, enable): """ Builds a write port. """ if self.max_write_ports is not None: self.write_ports += 1 if self.write_ports > self.max_write_ports: raise PyrtlError('maximum number of write ports (%d) exceeded' % self.max_write_ports) writeport_net = LogicNet( op='@',
python
{ "resource": "" }
q3007
AES.encryption
train
def encryption(self, plaintext, key): """ Builds a single cycle AES Encryption circuit :param WireVector plaintext: text to encrypt :param WireVector key: AES key to use to encrypt :return: a WireVector containing the ciphertext """ if len(plaintext) != self._key_len: raise pyrtl.PyrtlError("Ciphertext length is invalid") if len(key) != self._key_len: raise pyrtl.PyrtlError("key length
python
{ "resource": "" }
q3008
AES.encrypt_state_m
train
def encrypt_state_m(self, plaintext_in, key_in, reset): """ Builds a multiple cycle AES Encryption state machine circuit :param reset: a one bit signal telling the state machine to reset and accept the current plaintext and key :return ready, cipher_text: ready is a one bit signal showing that the encryption result (cipher_text) has been calculated. """ if len(key_in) != len(plaintext_in): raise pyrtl.PyrtlError("AES key and plaintext should be the same length") plain_text, key = (pyrtl.Register(len(plaintext_in)) for i in range(2)) key_exp_in, add_round_in = (pyrtl.WireVector(len(plaintext_in)) for i in range(2)) counter = pyrtl.Register(4, 'counter') round = pyrtl.WireVector(4, 'round') counter.next <<= round sub_out = self._sub_bytes(plain_text) shift_out = self._shift_rows(sub_out) mix_out = self._mix_columns(shift_out) key_out = self._key_expansion(key, counter) add_round_out = self._add_round_key(add_round_in, key_exp_in) with pyrtl.conditional_assignment: with reset == 1: round |= 0 key_exp_in |= key_in # to lower the number of cycles
python
{ "resource": "" }
q3009
AES.decryption
train
def decryption(self, ciphertext, key): """ Builds a single cycle AES Decryption circuit :param WireVector ciphertext: data to decrypt :param WireVector key: AES key to use to encrypt (AES is symmetric) :return: a WireVector containing the plaintext """ if len(ciphertext) != self._key_len:
python
{ "resource": "" }
q3010
AES.decryption_statem
train
def decryption_statem(self, ciphertext_in, key_in, reset): """ Builds a multiple cycle AES Decryption state machine circuit :param reset: a one bit signal telling the state machine to reset and accept the current plaintext and key :return ready, plain_text: ready is a one bit signal showing that the decryption result (plain_text) has been calculated. """ if len(key_in) != len(ciphertext_in): raise pyrtl.PyrtlError("AES key and ciphertext should be the same length") cipher_text, key = (pyrtl.Register(len(ciphertext_in)) for i in range(2)) key_exp_in, add_round_in = (pyrtl.WireVector(len(ciphertext_in)) for i in range(2)) # this is not part of the state machine as we need the keys in # reverse order... reversed_key_list = reversed(self._key_gen(key_exp_in)) counter = pyrtl.Register(4, 'counter') round = pyrtl.WireVector(4) counter.next <<= round inv_shift = self._inv_shift_rows(cipher_text) inv_sub = self._sub_bytes(inv_shift, True) key_out = pyrtl.mux(round, *reversed_key_list, default=0) add_round_out = self._add_round_key(add_round_in, key_out) inv_mix_out = self._mix_columns(add_round_out, True) with pyrtl.conditional_assignment: with reset == 1: round |= 0
python
{ "resource": "" }
q3011
AES._g
train
def _g(self, word, key_expand_round): """ One-byte left circular rotation, substitution of each byte """ import numbers self._build_memories_if_not_exists() a = libutils.partition_wire(word, 8) sub = [self.sbox[a[index]] for index in (3, 0, 1, 2)] if isinstance(key_expand_round, numbers.Number):
python
{ "resource": "" }
q3012
extend
train
def extend(*args): """shallow dictionary merge Args: a: dict to extend b: dict to apply to a Returns: new instance of the same type as _a_, with _a_ and _b_ merged. """ if not args: return {}
python
{ "resource": "" }
q3013
_trivialgraph_default_namer
train
def _trivialgraph_default_namer(thing, is_edge=True): """ Returns a "good" string for thing in printed graphs. """ if is_edge: if thing.name is None or thing.name.startswith('tmp'): return '' else: return '/'.join([thing.name, str(len(thing))]) elif isinstance(thing, Const): return str(thing.val) elif isinstance(thing, WireVector):
python
{ "resource": "" }
q3014
net_graph
train
def net_graph(block=None, split_state=False): """ Return a graph representation of the current block. Graph has the following form: { node1: { nodeA: edge1A, nodeB: edge1B}, node2: { nodeB: edge2B, nodeC: edge2C}, ... } aka: edge = graph[source][dest] Each node can be either a logic net or a WireVector (e.g. an Input, and Output, a Const or even an undriven WireVector (which acts as a source or sink in the network) Each edge is a WireVector or derived type (Input, Output, Register, etc.) Note that inputs, consts, and outputs will be both "node" and "edge". WireVectors that are not connected to any nets are not returned as part of the
python
{ "resource": "" }
q3015
output_to_trivialgraph
train
def output_to_trivialgraph(file, namer=_trivialgraph_default_namer, block=None): """ Walk the block and output it in trivial graph format to the open file. """ graph = net_graph(block) node_index_map = {} # map node -> index # print the list of nodes for index, node in enumerate(graph): print('%d %s' % (index, namer(node, is_edge=False)), file=file) node_index_map[node] = index print('#', file=file)
python
{ "resource": "" }
q3016
_graphviz_default_namer
train
def _graphviz_default_namer(thing, is_edge=True, is_to_splitmerge=False): """ Returns a "good" graphviz label for thing. """ if is_edge: if (thing.name is None or thing.name.startswith('tmp') or isinstance(thing, (Input, Output, Const, Register))): name = '' else: name = '/'.join([thing.name, str(len(thing))]) penwidth = 2 if len(thing) == 1 else 6 arrowhead = 'none' if is_to_splitmerge else 'normal' return '[label="%s", penwidth="%d", arrowhead="%s"]' % (name, penwidth, arrowhead) elif isinstance(thing, Const): return '[label="%d", shape=circle, fillcolor=lightgrey]' % thing.val elif isinstance(thing, (Input, Output)): return '[label="%s", shape=circle, fillcolor=none]' % thing.name elif isinstance(thing, Register): return '[label="%s", shape=square, fillcolor=gold]' % thing.name elif isinstance(thing, WireVector): return '[label="", shape=circle, fillcolor=none]' else: try: if thing.op == '&': return '[label="and"]' elif thing.op == '|': return '[label="or"]' elif thing.op == '^':
python
{ "resource": "" }
q3017
output_to_graphviz
train
def output_to_graphviz(file, namer=_graphviz_default_namer, block=None): """ Walk the block and output it in graphviz format to
python
{ "resource": "" }
q3018
block_to_svg
train
def block_to_svg(block=None): """ Return an SVG for the block. """ block = working_block(block) try: from graphviz import
python
{ "resource": "" }
q3019
trace_to_html
train
def trace_to_html(simtrace, trace_list=None, sortkey=None): """ Return a HTML block showing the trace. """ from .simulation import SimulationTrace, _trace_sort_key if not isinstance(simtrace, SimulationTrace): raise PyrtlError('first arguement must be of type SimulationTrace') trace = simtrace.trace if sortkey is None: sortkey = _trace_sort_key if trace_list is None: trace_list = sorted(trace, key=sortkey) wave_template = ( """\ <script type="WaveDrom"> { signal : [ %s ]} </script> """ ) def extract(w): wavelist = [] datalist = [] last = None for i, value in enumerate(trace[w]): if last == value: wavelist.append('.') else: if len(w) == 1: wavelist.append(str(value)) else:
python
{ "resource": "" }
q3020
create_store
train
def create_store(reducer, initial_state=None, enhancer=None): """ redux in a nutshell. observable has been omitted. Args: reducer: root reducer function for the state tree initial_state: optional initial state data enhancer: optional enhancer function for middleware etc. Returns: a Pydux store """ if enhancer is not None: if not hasattr(enhancer, '__call__'): raise TypeError('Expected the enhancer to be a function.') return enhancer(create_store)(reducer, initial_state) if not hasattr(reducer, '__call__'): raise TypeError('Expected the reducer to be a function.') # single-element arrays for r/w closure current_reducer = [reducer] current_state = [initial_state] current_listeners = [[]] next_listeners = [current_listeners[0]] is_dispatching = [False] def ensure_can_mutate_next_listeners(): if next_listeners[0] == current_listeners[0]: next_listeners[0] = current_listeners[0][:] def get_state(): return current_state[0] def subscribe(listener): if not hasattr(listener, '__call__'): raise TypeError('Expected listener to be a function.') is_subscribed = [True] # r/w closure ensure_can_mutate_next_listeners() next_listeners[0].append(listener) def unsubcribe(): if not is_subscribed[0]: return is_subscribed[0] = False ensure_can_mutate_next_listeners() index = next_listeners[0].index(listener) next_listeners[0].pop(index) return unsubcribe def dispatch(action): if not isinstance(action, dict): raise TypeError('Actions must be a dict. ' 'Use custom middleware for async actions.') if action.get('type') is None: raise ValueError('Actions must have a non-None "type" property. '
python
{ "resource": "" }
q3021
set_debug_mode
train
def set_debug_mode(debug=True): """ Set the global debug mode. """ global debug_mode global _setting_keep_wirevector_call_stack
python
{ "resource": "" }
q3022
Block.add_wirevector
train
def add_wirevector(self, wirevector): """ Add a wirevector object to the block.""" self.sanity_check_wirevector(wirevector)
python
{ "resource": "" }
q3023
Block.remove_wirevector
train
def remove_wirevector(self, wirevector): """ Remove a wirevector object to the block."""
python
{ "resource": "" }
q3024
Block.add_net
train
def add_net(self, net): """ Add a net to the logic of the block. The passed net, which must be of type LogicNet, is checked and then
python
{ "resource": "" }
q3025
Block.wirevector_subset
train
def wirevector_subset(self, cls=None, exclude=tuple()): """Return set of wirevectors, filtered by the type or tuple of types provided as cls. If no cls is specified, the full set of wirevectors associated with the Block are returned. If cls is a single type, or a tuple of types, only those wirevectors of the matching types will be returned. This is helpful for getting all inputs, outputs, or registers of a block for example.""" if cls is None: initial_set = self.wirevector_set
python
{ "resource": "" }
q3026
Block.get_wirevector_by_name
train
def get_wirevector_by_name(self, name, strict=False): """Return the wirevector matching name. By fallthrough, if a matching wirevector cannot be found the value None is returned. However, if the argument strict is set to True, then this will instead throw a PyrtlError when no match is found.""" if name in
python
{ "resource": "" }
q3027
Block.net_connections
train
def net_connections(self, include_virtual_nodes=False): """ Returns a representation of the current block useful for creating a graph. :param include_virtual_nodes: if enabled, the wire itself will be used to signal an external source or sink (such as the source for an Input net). If disabled, these nodes will be excluded from the adjacency dictionaries :return wire_src_dict, wire_sink_dict Returns two dictionaries: one that map WireVectors to the logic nets that creates their signal and one that maps WireVectors to a list of logic nets that use the signal These dictionaries make the creation of a graph much easier, as well as facilitate other places in which one would need wire source and wire sink information Look at input_output.net_graph for one such graph that uses the information from
python
{ "resource": "" }
q3028
Block.sanity_check
train
def sanity_check(self): """ Check block and throw PyrtlError or PyrtlInternalError if there is an issue. Should not modify anything, only check data structures to make sure they have been built according to the assumptions stated in the Block comments.""" # TODO: check that the wirevector_by_name is sane from .wire import Input, Const, Output from .helperfuncs import get_stack, get_stacks # check for valid LogicNets (and wires) for net in self.logic: self.sanity_check_net(net) for w in self.wirevector_subset(): if w.bitwidth is None: raise PyrtlError( 'error, missing bitwidth for WireVector "%s" \n\n %s' % (w.name, get_stack(w))) # check for unique names wirevector_names_set = set(x.name for x in self.wirevector_set) if len(self.wirevector_set) != len(wirevector_names_set): wirevector_names_list = [x.name for x in self.wirevector_set] for w in wirevector_names_set: wirevector_names_list.remove(w) raise PyrtlError('Duplicate wire names found for the following ' 'different signals: %s' % repr(wirevector_names_list)) # check for dead input wires (not connected to anything) all_input_and_consts = self.wirevector_subset((Input, Const)) # The following line also checks for duplicate wire drivers
python
{ "resource": "" }
q3029
Block.sanity_check_memory_sync
train
def sanity_check_memory_sync(self, wire_src_dict=None): """ Check that all memories are synchronous unless explicitly specified as async. While the semantics of 'm' memories reads is asynchronous, if you want your design to use a block ram (on an FPGA or otherwise) you want to make sure the index is available at the beginning of the clock edge. This check will walk the logic structure and throw an error on any memory if finds that has an index that is not ready at the beginning of the cycle. """ sync_mems = set(m for m in self.logic_subset('m') if not m.op_param[1].asynchronous) if not len(sync_mems): return # nothing to check here if wire_src_dict is None: wire_src_dict, wdd = self.net_connections() from .wire import Input, Const sync_src = 'r' sync_prop = 'wcs' for net in sync_mems: wires_to_check = list(net.args) while len(wires_to_check): wire = wires_to_check.pop()
python
{ "resource": "" }
q3030
Block.sanity_check_wirevector
train
def sanity_check_wirevector(self, w): """ Check that w is a valid wirevector type. """ from .wire import WireVector if not isinstance(w, WireVector): raise PyrtlError(
python
{ "resource": "" }
q3031
_NameSanitizer.make_valid_string
train
def make_valid_string(self, string=''): """ Inputting a value for the first time """ if not self.is_valid_str(string): if string in self.val_map and not self.allow_dups: raise IndexError("Value {} has already been given to the sanitizer".format(string)) internal_name = super(_NameSanitizer, self).make_valid_string()
python
{ "resource": "" }
q3032
optimize
train
def optimize(update_working_block=True, block=None, skip_sanity_check=False): """ Return an optimized version of a synthesized hardware block. :param Boolean update_working_block: Don't copy the block and optimize the new block :param Block block: the block to optimize (defaults to working block) Note: optimize works on all hardware designs, both synthesized and non
python
{ "resource": "" }
q3033
_remove_wire_nets
train
def _remove_wire_nets(block): """ Remove all wire nodes from the block. """ wire_src_dict = _ProducerList() wire_removal_set = set() # set of all wirevectors to be removed # one pass to build the map of value producers and # all of the nets and wires to be removed for net in block.logic: if net.op == 'w': wire_src_dict[net.dests[0]] = net.args[0] if not isinstance(net.dests[0], Output): wire_removal_set.add(net.dests[0]) # second full pass to create the new logic without the wire nets new_logic = set() for net in block.logic: if net.op != 'w' or isinstance(net.dests[0], Output): new_args = tuple(wire_src_dict.find_producer(x) for x in net.args)
python
{ "resource": "" }
q3034
constant_propagation
train
def constant_propagation(block, silence_unexpected_net_warnings=False): """ Removes excess constants in the block. Note on resulting block: The output of the block can have wirevectors that are driven but not listened to. This is to be expected. These are
python
{ "resource": "" }
q3035
common_subexp_elimination
train
def common_subexp_elimination(block=None, abs_thresh=1, percent_thresh=0): """ Common Subexpression Elimination for PyRTL blocks :param block: the block to run the subexpression elimination on :param abs_thresh: absolute threshold for
python
{ "resource": "" }
q3036
_remove_unlistened_nets
train
def _remove_unlistened_nets(block): """ Removes all nets that are not connected to an output wirevector """ listened_nets = set() listened_wires = set() prev_listened_net_count = 0 def add_to_listened(net): listened_nets.add(net) listened_wires.update(net.args) for a_net in block.logic:
python
{ "resource": "" }
q3037
_remove_unused_wires
train
def _remove_unused_wires(block, keep_inputs=True): """ Removes all unconnected wires from a block""" valid_wires = set() for logic_net in block.logic: valid_wires.update(logic_net.args, logic_net.dests) wire_removal_set = block.wirevector_set.difference(valid_wires) for removed_wire in wire_removal_set: if isinstance(removed_wire, Input): term = " optimized away" if keep_inputs: valid_wires.add(removed_wire)
python
{ "resource": "" }
q3038
synthesize
train
def synthesize(update_working_block=True, block=None): """ Lower the design to just single-bit "and", "or", and "not" gates. :param update_working_block: Boolean specifying if working block update :param block: The block you want to synthesize :return: The newly synthesized block (of type PostSynthesisBlock). Takes as input a block (default to working block) and creates a new block which is identical in function but uses only single bit gates and excludes many of the more complicated primitives. The new block should consist *almost* exclusively of the combination elements of w, &, |, ^, and ~ and sequential elements of registers (which are one bit as well). The two exceptions are for inputs/outputs (so that we can keep the same interface) which are immediately broken down into the individual bits and memories. Memories (read and write ports) which require the reassembly and disassembly of the wirevectors immediately before and after. There arethe only two places where 'c' and 's' ops should exist. The block that results from synthesis is actually of type "PostSynthesisBlock" which contains a mapping from the original inputs and outputs to the inputs and outputs of this block. This is used during simulation to map the input/outputs so that the same testbench can be used both pre and post synthesis (see documentation for Simulation for more details). """ block_pre = working_block(block) block_pre.sanity_check() # before going further, make sure that pressynth is valid block_in = copy_block(block_pre, update_working_block=False) block_out = PostSynthBlock() # resulting block should only have one of a restricted set of net ops block_out.legal_ops = set('~&|^nrwcsm@') wirevector_map = {} # map from (vector,index) -> new_wire with set_working_block(block_out, no_sanity_check=True): # First, replace advanced operators with simpler ones for op, fun in [ ('*', _basic_mult), ('+', _basic_add), ('-', _basic_sub), ('x', _basic_select), ('=', _basic_eq), ('<', _basic_lt), ('>', _basic_gt)]: net_transform(_replace_op(op, fun), block_in) # Next, create all of the new wires for the new block # from the original wires and store them in the wirevector_map # for reference. for wirevector in block_in.wirevector_subset(): for i in range(len(wirevector)):
python
{ "resource": "" }
q3039
barrel_shifter
train
def barrel_shifter(bits_to_shift, bit_in, direction, shift_dist, wrap_around=0): """ Create a barrel shifter that operates on data based on the wire width. :param bits_to_shift: the input wire :param bit_in: the 1-bit wire giving the value to shift in :param direction: a one bit WireVector representing shift direction (0 = shift down, 1 = shift up) :param shift_dist: WireVector representing offset to shift :param wrap_around: ****currently not implemented**** :return: shifted WireVector """ from pyrtl import concat, select # just for readability if wrap_around != 0: raise NotImplementedError # Implement with logN stages pyrtl.muxing between shifted and un-shifted values final_width = len(bits_to_shift) val = bits_to_shift append_val = bit_in for i in range(len(shift_dist)): shift_amt = pow(2, i) # stages shift 1,2,4,8,... if shift_amt < final_width: newval = select(direction, concat(val[:-shift_amt], append_val), # shift up concat(append_val, val[shift_amt:])) # shift down
python
{ "resource": "" }
q3040
compose
train
def compose(*funcs): """ chained function composition wrapper creates function f, where f(x) = arg0(arg1(arg2(...argN(x)))) if *funcs is empty, an identity function is returned. Args: *funcs: list of functions to chain
python
{ "resource": "" }
q3041
software_fibonacci
train
def software_fibonacci(n): """ a normal old python function to return the Nth fibonacci number. """ a, b = 0, 1
python
{ "resource": "" }
q3042
apply_middleware
train
def apply_middleware(*middlewares): """ creates an enhancer function composed of middleware Args: *middlewares: list of middleware functions to apply Returns: an enhancer for subsequent calls to create_store() """ def inner(create_store_): def create_wrapper(reducer, enhancer=None): store = create_store_(reducer, enhancer) dispatch = store['dispatch'] middleware_api = { 'get_state': store['get_state'],
python
{ "resource": "" }
q3043
mux
train
def mux(index, *mux_ins, **kwargs): """ Multiplexer returning the value of the wire in . :param WireVector index: used as the select input to the multiplexer :param WireVector mux_ins: additional WireVector arguments selected when select>1 :param WireVector kwargs: additional WireVectors, keyword arg "default" If you are selecting between less items than your index can address, you can use the "default" keyword argument to auto-expand those terms. For example, if you have a 3-bit index but are selecting between 6 options, you need to specify a value for those other 2 possible values of index (0b110 and 0b111). :return: WireVector of length of the longest input (not including select) To avoid confusion, if you are using the mux where the select is a "predicate" (meaning something that you are checking the truth value of rather than using it as a number) it is recommended that you use the select function instead as named arguments because the ordering is different from the classic ternary operator of some languages. Example of mux as "selector" to pick between a0 and a1: :: index = WireVector(1) mux( index, a0, a1 ) Example of mux as "selector" to pick between a0 ... a3: :: index = WireVector(2) mux( index, a0, a1, a2, a3 ) Example of "default" to specify additional arguments: :: index = WireVector(3) mux( index, a0, a1, a2, a3, a4, a5, default=0 ) """ if kwargs: # only "default" is allowed as kwarg. if len(kwargs) != 1 or 'default' not in kwargs: try: result = select(index, **kwargs) import warnings warnings.warn("Predicates are being deprecated in Mux. " "Use the select operator instead.", stacklevel=2) return result except Exception:
python
{ "resource": "" }
q3044
select
train
def select(sel, truecase, falsecase): """ Multiplexer returning falsecase for select==0, otherwise truecase. :param WireVector sel: used as the select input to the multiplexer :param WireVector falsecase: the WireVector selected if select==0 :param WireVector truecase: the WireVector selected if select==1 The hardware this generates is exactly the same as "mux" but by putting the true case as the first argument it matches more of the C-style ternary operator semantics which can be helpful for readablity. Example of mux as "ternary operator" to take the max of 'a' and 5: :: select( a<5, truecase=a, falsecase=5 ) """
python
{ "resource": "" }
q3045
concat
train
def concat(*args): """ Concatenates multiple WireVectors into a single WireVector :param WireVector args: inputs to be concatenated :return: WireVector with length equal to the sum of the args' lengths You can provide multiple arguments and they will be combined with the right-most argument being the least significant bits of the result. Note that if you have a list of arguments to concat together you will likely want index 0 to be the least significant bit and so if you unpack the list into the arguements here it will be backwards. The function concat_list is provided for that case specifically. Example using concat to combine two bytes into a 16-bit quantity: :: concat( msb, lsb ) """ if len(args) <= 0:
python
{ "resource": "" }
q3046
signed_add
train
def signed_add(a, b): """ Return wirevector for result of signed addition. :param a: a wirevector to serve as first input to addition :param b: a wirevector to serve as second input to addition Given a length n and length m wirevector the result of the signed addition is length max(n,m)+1. The inputs are twos complement sign extended to the same length before adding.""" a, b =
python
{ "resource": "" }
q3047
signed_lt
train
def signed_lt(a, b): """ Return a single bit result of signed less than comparison. """ a, b = match_bitwidth(as_wires(a),
python
{ "resource": "" }
q3048
signed_le
train
def signed_le(a, b): """ Return a single bit result of signed less than or equal comparison. """ a, b = match_bitwidth(as_wires(a),
python
{ "resource": "" }
q3049
signed_gt
train
def signed_gt(a, b): """ Return a single bit result of signed greater than comparison. """ a, b = match_bitwidth(as_wires(a),
python
{ "resource": "" }
q3050
signed_ge
train
def signed_ge(a, b): """ Return a single bit result of signed greater than or equal comparison. """ a, b = match_bitwidth(as_wires(a),
python
{ "resource": "" }
q3051
shift_right_arithmetic
train
def shift_right_arithmetic(bits_to_shift, shift_amount): """ Shift right arithmetic operation. :param bits_to_shift: WireVector to shift right :param shift_amount: WireVector specifying amount to shift :return: WireVector of same length as bits_to_shift This function returns a new WireVector of length equal to the length of the input `bits_to_shift` but where the bits have been shifted to the right. An arithemetic shift is one that treats the value as as signed number, meaning the
python
{ "resource": "" }
q3052
match_bitwidth
train
def match_bitwidth(*args, **opt): """ Matches the bitwidth of all of the input arguments with zero or sign extend :param args: WireVectors of which to match bitwidths :param opt: Optional keyword argument 'signed=True' (defaults to False) :return: tuple of args in order with extended bits Example of matching the bitwidths of two WireVectors `a` and `b` with with zero extention: :: a,b = match_bitwidth(a, b) Example of matching the bitwidths of three WireVectors `a`,`b`, and `c` with with sign extention: :: a,b = match_bitwidth(a, b, c, signed=True) """ # TODO: when we drop 2.7 support, this code should be cleaned up with explicit # kwarg support for "signed" rather than the less than helpful "**opt"
python
{ "resource": "" }
q3053
as_wires
train
def as_wires(val, bitwidth=None, truncating=True, block=None): """ Return wires from val which may be wires, integers, strings, or bools. :param val: a wirevector-like object or something that can be converted into a Const :param bitwidth: The bitwidth the resulting wire should be :param bool truncating: determines whether bits will be dropped to achieve the desired bitwidth if it is too long (if true, the most-significant bits will be dropped) :param Block block: block to use for wire This function is mainly used to coerce values into WireVectors (for example, operations such as "x+1" where "1" needs to be converted to a Const WireVector). An example: :: def myhardware(input_a, input_b): a = as_wires(input_a) b = as_wires(input_b) myhardware(3, x) The function as_wires will covert the 3 to Const but keep `x` unchanged assuming it is a WireVector. """ from .memory import _MemIndexed block = working_block(block) if isinstance(val, (int, six.string_types)): # note that this case captures bool as well (as bools are instances of ints) return Const(val, bitwidth=bitwidth, block=block) elif isinstance(val, _MemIndexed): # convert to a memory read when the value is actually used if val.wire is None: val.wire =
python
{ "resource": "" }
q3054
bitfield_update
train
def bitfield_update(w, range_start, range_end, newvalue, truncating=False): """ Return wirevector w but with some of the bits overwritten by newvalue. :param w: a wirevector to use as the starting point for the update :param range_start: the start of the range of bits to be updated :param range_end: the end of the range of bits to be updated :param newvalue: the value to be written in to the start:end range :param truncating: if true, clip the newvalue to be the proper number of bits Given a wirevector w, this function returns a new wirevector that is identical to w except in the range of bits specified. In that specified range, the value newvalue is swapped in. For example: `bitfield_update(w, 20, 23, 0x7)` will return return a wirevector of the same length as w, and with the same values as w, but with bits 20, 21, and 22 all set to 1. Note that range_start and range_end will be inputs to a slice and so standar Python slicing rules apply (e.g. negative values for end-relative indexing and support for None). :: w = bitfield_update(w, 20, 23, 0x7) # sets bits 20, 21, 22 to 1 w = bitfield_update(w, 20, 23, 0x6) # sets bit 20 to 0, bits 21 and 22 to 1 w = bitfield_update(w, 20, None, 0x7) # assuming w is 32 bits, sets bits 31..20 = 0x7 w = bitfield_update(w, -1, None, 0x1) # set the LSB (bit) to 1 """ from .corecircuits import concat_list w = as_wires(w) idxs = list(range(len(w))) # we make a
python
{ "resource": "" }
q3055
enum_mux
train
def enum_mux(cntrl, table, default=None, strict=True): """ Build a mux for the control signals specified by an enum. :param cntrl: is a wirevector and control for the mux. :param table: is a dictionary of the form mapping enum->wirevector. :param default: is a wirevector to use when the key is not present. In addtion it is possible to use the key 'otherwise' to specify a default value, but it is an error if both are supplied. :param strict: is flag, that when set, will cause enum_mux to check that the dictionary has an entry for every possible value in the enum. Note that if a default is set, then this check is not performed as the default will provide valid values for any underspecified keys. :return: a wirevector which is the result of the mux. :: class Command(Enum): ADD = 1 SUB = 2 enum_mux(cntrl, {ADD: a+b, SUB: a-b}) enum_mux(cntrl, {ADD: a+b}, strict=False) # SUB case undefined enum_mux(cntrl, {ADD: a+b, otherwise: a-b}) enum_mux(cntrl, {ADD: a+b}, default=a-b) """ # check dictionary keys are of the right type keytypeset = set(type(x) for x in table.keys() if x is not otherwise) if len(keytypeset) != 1: raise PyrtlError('table mixes multiple types {} as keys'.format(keytypeset)) keytype = list(keytypeset)[0] # check that dictionary is complete for the enum try: enumkeys = list(keytype.__members__.values()) except AttributeError:
python
{ "resource": "" }
q3056
rtl_any
train
def rtl_any(*vectorlist): """ Hardware equivalent of python native "any". :param WireVector vectorlist: all arguments are WireVectors of length 1 :return: WireVector of length 1 Returns a 1-bit WireVector which will hold a '1' if any of the inputs are '1' (i.e. it is a big ol' OR gate) """ if len(vectorlist) <= 0: raise
python
{ "resource": "" }
q3057
rtl_all
train
def rtl_all(*vectorlist): """ Hardware equivalent of python native "all". :param WireVector vectorlist: all arguments are WireVectors of length 1 :return: WireVector of length 1 Returns a 1-bit WireVector which will hold a '1' only if all of the inputs are '1' (i.e. it is a big ol' AND gate) """ if len(vectorlist) <= 0: raise PyrtlError('rtl_all requires at least
python
{ "resource": "" }
q3058
_basic_mult
train
def _basic_mult(A, B): """ A stripped-down copy of the Wallace multiplier in rtllib """ if len(B) == 1: A, B = B, A # so that we can reuse the code below :) if len(A) == 1: return concat_list(list(A & b for b in B) + [Const(0)]) # keep WireVector len consistent result_bitwidth = len(A) + len(B) bits = [[] for weight in range(result_bitwidth)] for i, a in enumerate(A): for j, b in enumerate(B): bits[i + j].append(a & b) while not all(len(i) <= 2 for i in bits): deferred = [[] for weight in range(result_bitwidth + 1)] for i, w_array in enumerate(bits): # Start with low weights and start reducing while len(w_array) >= 3: # build a new full adder a, b, cin = (w_array.pop(0) for j in range(3)) deferred[i].append(a ^ b ^ cin) deferred[i + 1].append(a & b | a & cin | b & cin) if len(w_array) == 2:
python
{ "resource": "" }
q3059
_push_condition
train
def _push_condition(predicate): """As we enter new conditions, this pushes them on the predicate stack.""" global _depth _check_under_condition() _depth += 1 if predicate is not otherwise and len(predicate) > 1:
python
{ "resource": "" }
q3060
_build
train
def _build(lhs, rhs): """Stores the wire assignment details until finalize is called.""" _check_under_condition() final_predicate, pred_set = _current_select()
python
{ "resource": "" }
q3061
_pred_sets_are_in_conflict
train
def _pred_sets_are_in_conflict(pred_set_a, pred_set_b): """ Find conflict in sets, return conflict if found, else None. """ # pred_sets conflict if we cannot find one shared predicate
python
{ "resource": "" }
q3062
_finalize
train
def _finalize(): """Build the required muxes and call back to WireVector to finalize the wirevector build.""" from .memory import MemBlock from pyrtl.corecircuits import select for lhs in _predicate_map: # handle memory write ports if isinstance(lhs, MemBlock): p, (addr, data, enable) = _predicate_map[lhs][0] combined_enable = select(p, truecase=enable, falsecase=Const(0)) combined_addr = addr combined_data = data for p, (addr, data, enable) in _predicate_map[lhs][1:]: combined_enable = select(p, truecase=enable, falsecase=combined_enable) combined_addr = select(p, truecase=addr, falsecase=combined_addr) combined_data = select(p, truecase=data, falsecase=combined_data) lhs._build(combined_addr, combined_data, combined_enable)
python
{ "resource": "" }
q3063
_current_select
train
def _current_select(): """ Function to calculate the current "predicate" in the current context. Returns a tuple of information: (predicate, pred_set). The value pred_set is a set([ (predicate, bool), ... ]) as described in the _reset_conditional_state """ # helper to create the conjuction of predicates def and_with_possible_none(a, b): assert(a is not None or b is not None) if a is None: return b if b is None: return a return a & b def between_otherwise_and_current(predlist): lastother = None for i, p in enumerate(predlist[:-1]): if p is otherwise: lastother = i if lastother is None: return predlist[:-1] else: return predlist[lastother+1:-1] select = None pred_set = set() # for all conditions except the current children (which should be []) for predlist in _conditions_list_stack[:-1]: # negate all of the predicates between "otherwise" and the current one for predicate in between_otherwise_and_current(predlist): select = and_with_possible_none(select, ~predicate)
python
{ "resource": "" }
q3064
area_estimation
train
def area_estimation(tech_in_nm=130, block=None): """ Estimates the total area of the block. :param tech_in_nm: the size of the circuit technology to be estimated (for example, 65 is 65nm and 250 is 0.25um) :return: tuple of estimated areas (logic, mem) in terms of mm^2 The estimations are based off of 130nm stdcell designs for the logic, and custom memory blocks from the literature. The results are not fully validated and we do not recommend that this function be used in carrying out science for publication. """ def mem_area_estimate(tech_in_nm, bits, ports, is_rom): # http://www.cs.ucsb.edu/~sherwood/pubs/ICCD-srammodel.pdf # ROM is assumed to be 1/10th of area of SRAM tech_in_um = tech_in_nm / 1000.0 area_estimate = 0.001 * tech_in_um**2.07 * bits**0.9 * ports**0.7 + 0.0048 return area_estimate if not is_rom else area_estimate / 10.0 # Subset of the raw data gathered from yosys, mapping to vsclib 130nm library # Width Adder_Area Mult_Area (area in "tracks" as discussed below) # 8 211 2684 # 16 495 12742 # 32 1110 49319 # 64 2397 199175 # 128 4966 749828 def adder_stdcell_estimate(width): return width * 34.4 - 25.8 def multiplier_stdcell_estimate(width): if width == 1: return 5 elif width == 2: return 39 elif width == 3: return 219 else: return -958 + (150 * width) + (45 * width**2) def stdcell_estimate(net): if net.op in 'w~sc': return 0 elif net.op in '&|n': return 40/8.0 * len(net.args[0]) # 40 lambda elif net.op in '^=<>x': return 80/8.0 * len(net.args[0]) # 80 lambda elif net.op == 'r': return 144/8.0 * len(net.args[0]) # 144 lambda elif net.op in '+-': return adder_stdcell_estimate(len(net.args[0])) elif net.op == '*': return multiplier_stdcell_estimate(len(net.args[0])) elif net.op in 'm@': return 0 # memories handled elsewhere else: raise PyrtlInternalError('Unable to estimate the following net '
python
{ "resource": "" }
q3065
_bits_ports_and_isrom_from_memory
train
def _bits_ports_and_isrom_from_memory(mem): """ Helper to extract mem bits and ports for estimation. """ is_rom = False bits = 2**mem.addrwidth * mem.bitwidth read_ports = len(mem.readport_nets) try: write_ports = len(mem.writeport_nets) except AttributeError: # dealing with ROMs if not isinstance(mem, RomBlock): raise
python
{ "resource": "" }
q3066
yosys_area_delay
train
def yosys_area_delay(library, abc_cmd=None, block=None): """ Synthesize with Yosys and return estimate of area and delay. :param library: stdcell library file to target in liberty format :param abc_cmd: string of commands for yosys to pass to abc for synthesis :param block: pyrtl block to analyze :return: a tuple of numbers: area, delay The area and delay are returned in units as defined by the stdcell library. In the standard vsc 130nm library, the area is in a number of "tracks", each of which is about 1.74 square um (see area estimation for more details) and the delay is in ps. http://www.vlsitechnology.org/html/vsc_description.html May raise `PyrtlError` if yosys is not configured correctly, and `PyrtlInternalError` if the call to yosys was not able successfully """ if abc_cmd is None: abc_cmd = 'strash;scorr;ifraig;retime;dch,-f;map;print_stats;' else: # first, replace whitespace with commas as per yosys requirements re.sub(r"\s+", ',', abc_cmd) # then append with "print_stats" to generate the area and delay info abc_cmd = '%s;print_stats;' % abc_cmd def extract_area_delay_from_yosys_output(yosys_output): report_lines = [line for line in yosys_output.split('\n') if 'ABC: netlist' in line] area = re.match('.*area\s*=\s*([0-9\.]*)', report_lines[0]).group(1) delay = re.match('.*delay\s*=\s*([0-9\.]*)', report_lines[0]).group(1) return float(area), float(delay) yosys_arg_template = """-p read_verilog %s; synth -top toplevel; dfflibmap -liberty %s; abc -liberty %s -script +%s """ temp_d, temp_path = tempfile.mkstemp(suffix='.v') try:
python
{ "resource": "" }
q3067
TimingAnalysis.max_freq
train
def max_freq(self, tech_in_nm=130, ffoverhead=None): """ Estimates the max frequency of a block in MHz. :param tech_in_nm: the size of the circuit technology to be estimated (for example, 65 is 65nm and 250 is 0.25um) :param ffoverhead: setup and ff propagation delay in picoseconds :return: a number representing an estimate of the max frequency in Mhz If a timing_map has already been generated by timing_analysis, it will be used to generate the estimate (and `gate_delay_funcs` will be ignored). Regardless, all params are optional and have reasonable default values. Estimation is based on Dennard Scaling assumption and does not include wiring effect -- as a result
python
{ "resource": "" }
q3068
TimingAnalysis.critical_path
train
def critical_path(self, print_cp=True, cp_limit=100): """ Takes a timing map and returns the critical paths of the system. :param print_cp: Whether to print the critical path to the terminal after calculation :return: a list containing tuples with the 'first' wire as the first value and the critical paths (which themselves are lists of nets) as the second """ critical_paths = [] # storage of all completed critical paths wire_src_map, dst_map = self.block.net_connections() def critical_path_pass(old_critical_path, first_wire): if isinstance(first_wire, (Input, Const, Register)): critical_paths.append((first_wire, old_critical_path)) return if len(critical_paths) >= cp_limit: raise self._TooManyCPsError() source = wire_src_map[first_wire] critical_path = [source] critical_path.extend(old_critical_path) arg_max_time = max(self.timing_map[arg_wire] for arg_wire in source.args) for arg_wire in source.args:
python
{ "resource": "" }
q3069
Client._post
train
def _post(self, endpoint, data, **kwargs): """ Method to perform POST request on the API. :param endpoint: Endpoint of the API. :param data: POST DATA for the request. :param kwargs: Other keyword arguments for requests.
python
{ "resource": "" }
q3070
Client._request
train
def _request(self, endpoint, method, data=None, **kwargs): """ Method to hanle both GET and POST requests. :param endpoint: Endpoint of the API. :param method: Method of HTTP request. :param data: POST DATA for the request. :param kwargs: Other keyword arguments. :return: Response for the request. """ final_url = self.url + endpoint if not self._is_authenticated: raise LoginRequired rq = self.session if method == 'get': request = rq.get(final_url, **kwargs)
python
{ "resource": "" }
q3071
Client.login
train
def login(self, username='admin', password='admin'): """ Method to authenticate the qBittorrent Client. Declares a class attribute named ``session`` which stores the authenticated session if the login is correct. Else, shows the login error. :param username: Username. :param password: Password. :return: Response to login request to the API. """ self.session = requests.Session() login = self.session.post(self.url+'login',
python
{ "resource": "" }
q3072
Client.torrents
train
def torrents(self, **filters): """ Returns a list of torrents matching the supplied filters. :param filter: Current status of the torrents. :param category: Fetch all torrents with the supplied label. :param sort: Sort torrents by. :param reverse: Enable reverse sorting. :param limit: Limit the number of torrents returned. :param offset: Set offset (if less than 0, offset from end). :return: list() of torrent with matching filter. """ params = {}
python
{ "resource": "" }
q3073
Client.preferences
train
def preferences(self): """ Get the current qBittorrent preferences. Can also be used to assign individual preferences. For setting multiple preferences at once, see ``set_preferences`` method. Note: Even if this is a ``property``, to fetch the current preferences dict, you are required to call it like a bound method. Wrong:: qb.preferences Right:: qb.preferences() """ prefs = self._get('query/preferences') class Proxy(Client): """ Proxy class to to allow assignment of individual preferences. this class overrides some methods to ease things. Because of this, settings can be assigned like:: In [5]: prefs = qb.preferences() In [6]: prefs['autorun_enabled'] Out[6]: True In [7]: prefs['autorun_enabled'] = False In [8]: prefs['autorun_enabled']
python
{ "resource": "" }
q3074
Client.download_from_link
train
def download_from_link(self, link, **kwargs): """ Download torrent using a link. :param link: URL Link or list of. :param savepath: Path to download the torrent. :param category: Label or Category of the torrent(s). :return: Empty JSON data. """ # old:new format old_arg_map = {'save_path': 'savepath'} # , 'label': 'category'} # convert old option names to new option names options = kwargs.copy() for old_arg, new_arg in old_arg_map.items(): if options.get(old_arg) and not options.get(new_arg): options[new_arg] = options[old_arg]
python
{ "resource": "" }
q3075
Client.download_from_file
train
def download_from_file(self, file_buffer, **kwargs): """ Download torrent using a file. :param file_buffer: Single file() buffer or list of. :param save_path: Path to download the torrent. :param label: Label of the torrent(s). :return: Empty JSON data. """ if isinstance(file_buffer, list): torrent_files = {} for i, f in enumerate(file_buffer): torrent_files.update({'torrents%s' % i: f})
python
{ "resource": "" }
q3076
Client.add_trackers
train
def add_trackers(self, infohash, trackers): """ Add trackers to a torrent. :param infohash: INFO HASH of torrent.
python
{ "resource": "" }
q3077
Client._process_infohash_list
train
def _process_infohash_list(infohash_list): """ Method to convert the infohash_list to qBittorrent API friendly values. :param infohash_list: List of infohash. """ if isinstance(infohash_list, list): data
python
{ "resource": "" }
q3078
Client.pause_multiple
train
def pause_multiple(self, infohash_list): """ Pause multiple torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3079
Client.set_category
train
def set_category(self, infohash_list, category): """ Set the category on multiple torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3080
Client.resume_multiple
train
def resume_multiple(self, infohash_list): """ Resume multiple paused torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3081
Client.delete
train
def delete(self, infohash_list): """ Delete torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3082
Client.delete_permanently
train
def delete_permanently(self, infohash_list): """ Permanently delete torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3083
Client.recheck
train
def recheck(self, infohash_list): """ Recheck torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3084
Client.increase_priority
train
def increase_priority(self, infohash_list): """ Increase priority of torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3085
Client.decrease_priority
train
def decrease_priority(self, infohash_list): """ Decrease priority of torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3086
Client.set_max_priority
train
def set_max_priority(self, infohash_list): """ Set torrents to maximum priority level. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3087
Client.set_min_priority
train
def set_min_priority(self, infohash_list): """ Set torrents to minimum priority level. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3088
Client.set_file_priority
train
def set_file_priority(self, infohash, file_id, priority): """ Set file of a torrent to a supplied priority level. :param infohash: INFO HASH of torrent. :param file_id: ID of the file to set priority. :param priority: Priority level of the file.
python
{ "resource": "" }
q3089
Client.get_torrent_download_limit
train
def get_torrent_download_limit(self, infohash_list): """ Get download speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes.
python
{ "resource": "" }
q3090
Client.set_torrent_download_limit
train
def set_torrent_download_limit(self, infohash_list, limit): """ Set download speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. :param limit: Speed limit in bytes. """ data
python
{ "resource": "" }
q3091
Client.get_torrent_upload_limit
train
def get_torrent_upload_limit(self, infohash_list): """ Get upoload speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3092
Client.set_torrent_upload_limit
train
def set_torrent_upload_limit(self, infohash_list, limit): """ Set upload speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. :param limit: Speed limit in bytes. """ data
python
{ "resource": "" }
q3093
Client.toggle_sequential_download
train
def toggle_sequential_download(self, infohash_list): """ Toggle sequential download in supplied torrents. :param infohash_list: Single or list() of infohashes. """
python
{ "resource": "" }
q3094
Client.force_start
train
def force_start(self, infohash_list, value=True): """ Force start selected torrents. :param infohash_list: Single or list() of infohashes.
python
{ "resource": "" }
q3095
humantime
train
def humantime(time): """Converts a time in seconds to a reasonable human readable time Parameters ---------- t : float The number of seconds Returns ------- time : string The human readable formatted value of the given time """ try: time = float(time) except (ValueError, TypeError): raise ValueError("Input must be numeric") # weeks if time >= 7 * 60 * 60 * 24: weeks = math.floor(time / (7 * 60 * 60 * 24)) timestr = "{:g} weeks, ".format(weeks) + humantime(time % (7 * 60 * 60 * 24)) # days elif time >= 60 * 60 * 24: days = math.floor(time / (60 * 60 * 24)) timestr = "{:g} days, ".format(days) + humantime(time % (60 * 60 * 24)) # hours elif time >= 60 * 60: hours = math.floor(time / (60 * 60)) timestr = "{:g} hours, ".format(hours) + humantime(time % (60 * 60)) # minutes elif time >= 60: minutes = math.floor(time / 60.) timestr
python
{ "resource": "" }
q3096
ansi_len
train
def ansi_len(string): """Extra length due to any ANSI sequences in the string.""" return len(string)
python
{ "resource": "" }
q3097
format_line
train
def format_line(data, linestyle): """Formats a list of elements using the given line style"""
python
{ "resource": "" }
q3098
parse_width
train
def parse_width(width, n): """Parses an int or array of widths Parameters ---------- width : int or array_like n : int """ if isinstance(width, int): widths = [width] * n else:
python
{ "resource": "" }
q3099
table
train
def table(data, headers=None, format_spec=FMT, width=WIDTH, align=ALIGN, style=STYLE, out=sys.stdout): """Print a table with the given data Parameters ---------- data : array_like An (m x n) array containing the data to print (m rows of n columns) headers : list, optional A list of n strings consisting of the header of each of the n columns (Default: None) format_spec : string, optional Format specification for formatting numbers (Default: '5g') width : int or array_like, optional The width of each column in the table (Default: 11) align : string The alignment to use ('left', 'center', or 'right'). (Default: 'right') style : string or tuple, optional A formatting style. (Default: 'fancy_grid') out : writer, optional A file handle or object that has write() and flush() methods (Default: sys.stdout) """ # Number
python
{ "resource": "" }