code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
sel, f, t = (as_wires(w) for w in (sel, falsecase, truecase)) f, t = match_bitwidth(f, t) outwire = WireVector(bitwidth=len(f)) net = LogicNet(op='x', op_param=None, args=(sel, f, t), dests=(outwire,)) working_block().add_net(net) # this includes sanity check on the mux return outwire
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 exactl...
9.472239
10.280642
0.921367
if len(args) <= 0: raise PyrtlError('error, concat requires at least 1 argument') if len(args) == 1: return as_wires(args[0]) arg_wirevectors = tuple(as_wires(arg) for arg in args) final_width = sum(len(arg) for arg in arg_wirevectors) outwire = WireVector(bitwidth=final_width)...
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 ...
3.795377
4.255752
0.891823
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) result_len = len(a) + 1 ext_a = a.sign_extended(result_len) ext_b = b.sign_extended(result_len) # add and truncate to the correct length return (ext_a + ext_b)[0:result_len]
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 s...
4.375788
3.956464
1.105985
a, b = as_wires(a), as_wires(b) final_len = len(a) + len(b) # sign extend both inputs to the final target length a, b = a.sign_extended(final_len), b.sign_extended(final_len) # the result is the multiplication of both, but truncated # TODO: this may make estimates based on the multiplicatio...
def signed_mult(a, b)
Return a*b where a and b are treated as signed values.
7.283904
7.187953
1.013349
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) r = a - b return r[-1] ^ (~a[-1]) ^ (~b[-1])
def signed_lt(a, b)
Return a single bit result of signed less than comparison.
7.433799
6.616402
1.123541
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) r = a - b return (r[-1] ^ (~a[-1]) ^ (~b[-1])) | (a == b)
def signed_le(a, b)
Return a single bit result of signed less than or equal comparison.
7.417902
6.70383
1.106517
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) r = b - a return r[-1] ^ (~a[-1]) ^ (~b[-1])
def signed_gt(a, b)
Return a single bit result of signed greater than comparison.
7.299351
6.732351
1.08422
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) r = b - a return (r[-1] ^ (~a[-1]) ^ (~b[-1])) | (a == b)
def signed_ge(a, b)
Return a single bit result of signed greater than or equal comparison.
7.281555
6.872951
1.059451
a, shamt = _check_shift_inputs(bits_to_shift, shift_amount) bit_in = bits_to_shift[-1] # shift in sign_bit dir = Const(0) # shift right return barrel.barrel_shifter(bits_to_shift, bit_in, dir, shift_amount)
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 whe...
8.669569
9.042011
0.95881
# 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" if len(opt) == 0: signed = False else: if len(opt) > 1 or 'signed' not in opt: raise PyrtlError('error, only supported kw...
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 WireVecto...
5.132317
4.781093
1.073461
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): # conv...
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 de...
4.82141
4.624355
1.042612
from .corecircuits import concat_list w = as_wires(w) idxs = list(range(len(w))) # we make a list of integers and slice those up to use as indexes idxs_lower = idxs[0:range_start] idxs_middle = idxs[range_start:range_end] idxs_upper = idxs[range_end:] if len(idxs_middle) == 0: ...
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 writte...
2.758462
2.784818
0.990536
# 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...
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 'otherwis...
4.114855
3.913583
1.051429
if len(vectorlist) <= 0: raise PyrtlError('rtl_any requires at least 1 argument') converted_vectorlist = [as_wires(v) for v in vectorlist] if any(len(v) != 1 for v in converted_vectorlist): raise PyrtlError('only length 1 WireVectors can be inputs to rtl_any') return or_all_bits(con...
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)
3.829522
3.864932
0.990838
if len(vectorlist) <= 0: raise PyrtlError('rtl_all requires at least 1 argument') converted_vectorlist = [as_wires(v) for v in vectorlist] if any(len(v) != 1 for v in converted_vectorlist): raise PyrtlError('only length 1 WireVectors can be inputs to rtl_all') return and_all_bits(co...
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)
3.94759
3.899191
1.012413
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 enumera...
def _basic_mult(A, B)
A stripped-down copy of the Wallace multiplier in rtllib
3.373542
3.316883
1.017082
global _depth _check_under_condition() _depth += 1 if predicate is not otherwise and len(predicate) > 1: raise PyrtlError('all predicates for conditional assignments must wirevectors of len 1') _conditions_list_stack[-1].append(predicate) _conditions_list_stack.append([])
def _push_condition(predicate)
As we enter new conditions, this pushes them on the predicate stack.
10.922882
9.974934
1.095033
_check_under_condition() final_predicate, pred_set = _current_select() _check_and_add_pred_set(lhs, pred_set) _predicate_map.setdefault(lhs, []).append((final_predicate, rhs))
def _build(lhs, rhs)
Stores the wire assignment details until finalize is called.
11.124697
10.095911
1.101901
# pred_sets conflict if we cannot find one shared predicate that is "negated" in one # and "non-negated" in the other for pred_a, bool_a in pred_set_a: for pred_b, bool_b in pred_set_b: if pred_a is pred_b and bool_a != bool_b: return False return True
def _pred_sets_are_in_conflict(pred_set_a, pred_set_b)
Find conflict in sets, return conflict if found, else None.
4.325364
4.510706
0.958911
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...
def _finalize()
Build the required muxes and call back to WireVector to finalize the wirevector build.
3.603704
3.459492
1.041686
# 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 = ...
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
4.293907
3.940105
1.089795
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 PyrtlInternalError('Mem with no writeport_nets att...
def _bits_ports_and_isrom_from_memory(mem)
Helper to extract mem bits and ports for estimation.
4.822021
4.569587
1.055242
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...
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 a...
3.41592
3.280156
1.04139
cp_length = self.max_length() scale_factor = 130.0 / tech_in_nm if ffoverhead is None: clock_period_in_ps = scale_factor * (cp_length + 189 + 194) else: clock_period_in_ps = (scale_factor * cp_length) + ffoverhead return 1e6 * 1.0/clock_period_in_...
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 fre...
3.884351
4.00154
0.970714
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,...
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 ...
3.881574
3.680751
1.05456
line_indent = " " * 2 # print the critical path for cp_with_num in enumerate(critical_paths): print("Critical path", cp_with_num[0], ":") print(line_indent, "The first wire is:", cp_with_num[1][0]) for net in cp_with_num[1][1]: print(...
def print_critical_paths(critical_paths)
Prints the results of the critical path length analysis. Done by default by the `timing_critical_path()` function.
4.749564
4.937645
0.961909
return self._request(endpoint, 'post', data, **kwargs)
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. :return: Response of the POST request.
5.065988
8.362062
0.60583
final_url = self.url + endpoint if not self._is_authenticated: raise LoginRequired rq = self.session if method == 'get': request = rq.get(final_url, **kwargs) else: request = rq.post(final_url, data, **kwargs) request.raise_...
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.
2.717229
2.820813
0.963278
self.session = requests.Session() login = self.session.post(self.url+'login', data={'username': username, 'password': password}) if login.text == 'Ok.': self._is_authenticated = True else: ...
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 req...
3.341174
3.323141
1.005426
params = {} for name, value in filters.items(): # make sure that old 'status' argument still works name = 'filter' if name == 'status' else name params[name] = value return self._get('query/torrents', params=params)
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...
5.774283
6.496906
0.888774
prefs = self._get('query/preferences') class Proxy(Client): def __init__(self, url, prefs, auth, session): super(Proxy, self).__init__(url) self.prefs = prefs self._is_authenticated = auth self.session = ...
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 ...
3.160233
3.401531
0.929062
# 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): ...
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.
4.561086
4.286045
1.064171
if isinstance(file_buffer, list): torrent_files = {} for i, f in enumerate(file_buffer): torrent_files.update({'torrents%s' % i: f}) else: torrent_files = {'torrents': file_buffer} data = kwargs.copy() if data.get('save_path'...
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.
3.380543
3.077533
1.098459
data = {'hash': infohash.lower(), 'urls': trackers} return self._post('command/addTrackers', data=data)
def add_trackers(self, infohash, trackers)
Add trackers to a torrent. :param infohash: INFO HASH of torrent. :param trackers: Trackers.
7.164737
8.711897
0.822408
if isinstance(infohash_list, list): data = {'hashes': '|'.join([h.lower() for h in infohash_list])} else: data = {'hashes': infohash_list.lower()} return data
def _process_infohash_list(infohash_list)
Method to convert the infohash_list to qBittorrent API friendly values. :param infohash_list: List of infohash.
3.041124
3.393786
0.896086
data = self._process_infohash_list(infohash_list) return self._post('command/pauseAll', data=data)
def pause_multiple(self, infohash_list)
Pause multiple torrents. :param infohash_list: Single or list() of infohashes.
5.623491
6.931944
0.811243
data = self._process_infohash_list(infohash_list) data['label'] = label return self._post('command/setLabel', data=data)
def set_label(self, infohash_list, label)
Set the label on multiple torrents. IMPORTANT: OLD API method, kept as it is to avoid breaking stuffs. :param infohash_list: Single or list() of infohashes.
4.853463
6.388049
0.759772
data = self._process_infohash_list(infohash_list) data['category'] = category return self._post('command/setCategory', data=data)
def set_category(self, infohash_list, category)
Set the category on multiple torrents. :param infohash_list: Single or list() of infohashes.
4.185725
5.455164
0.767296
data = self._process_infohash_list(infohash_list) return self._post('command/resumeAll', data=data)
def resume_multiple(self, infohash_list)
Resume multiple paused torrents. :param infohash_list: Single or list() of infohashes.
6.125003
7.419909
0.825482
data = self._process_infohash_list(infohash_list) return self._post('command/delete', data=data)
def delete(self, infohash_list)
Delete torrents. :param infohash_list: Single or list() of infohashes.
4.913164
6.474936
0.758797
data = self._process_infohash_list(infohash_list) return self._post('command/deletePerm', data=data)
def delete_permanently(self, infohash_list)
Permanently delete torrents. :param infohash_list: Single or list() of infohashes.
6.200594
7.748823
0.800198
data = self._process_infohash_list(infohash_list) return self._post('command/recheck', data=data)
def recheck(self, infohash_list)
Recheck torrents. :param infohash_list: Single or list() of infohashes.
5.568675
6.675063
0.83425
data = self._process_infohash_list(infohash_list) return self._post('command/increasePrio', data=data)
def increase_priority(self, infohash_list)
Increase priority of torrents. :param infohash_list: Single or list() of infohashes.
5.599852
7.081461
0.790776
data = self._process_infohash_list(infohash_list) return self._post('command/decreasePrio', data=data)
def decrease_priority(self, infohash_list)
Decrease priority of torrents. :param infohash_list: Single or list() of infohashes.
5.863398
7.465389
0.785411
data = self._process_infohash_list(infohash_list) return self._post('command/topPrio', data=data)
def set_max_priority(self, infohash_list)
Set torrents to maximum priority level. :param infohash_list: Single or list() of infohashes.
8.818781
11.450372
0.770174
data = self._process_infohash_list(infohash_list) return self._post('command/bottomPrio', data=data)
def set_min_priority(self, infohash_list)
Set torrents to minimum priority level. :param infohash_list: Single or list() of infohashes.
9.524901
12.344785
0.771573
if priority not in [0, 1, 2, 7]: raise ValueError("Invalid priority, refer WEB-UI docs for info.") elif not isinstance(file_id, int): raise TypeError("File ID must be an int") data = {'hash': infohash.lower(), 'id': file_id, 'prio...
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.
4.770274
5.171498
0.922416
data = self._process_infohash_list(infohash_list) return self._post('command/getTorrentsDlLimit', data=data)
def get_torrent_download_limit(self, infohash_list)
Get download speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes.
7.227606
9.077096
0.796247
data = self._process_infohash_list(infohash_list) data.update({'limit': limit}) return self._post('command/setTorrentsDlLimit', data=data)
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.
5.6535
7.230676
0.781877
data = self._process_infohash_list(infohash_list) return self._post('command/getTorrentsUpLimit', data=data)
def get_torrent_upload_limit(self, infohash_list)
Get upoload speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes.
6.712256
8.952012
0.749804
data = self._process_infohash_list(infohash_list) data.update({'limit': limit}) return self._post('command/setTorrentsUpLimit', data=data)
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.
5.48728
7.227536
0.759219
json_data = "json={}".format(json.dumps(kwargs)) headers = {'content-type': 'application/x-www-form-urlencoded'} return self._post('command/setPreferences', data=json_data, headers=headers)
def set_preferences(self, **kwargs)
Set preferences of qBittorrent. Read all possible preferences @ http://git.io/vEgDQ :param kwargs: set preferences in kwargs form.
3.700757
3.657296
1.011883
data = self._process_infohash_list(infohash_list) return self._post('command/toggleSequentialDownload', data=data)
def toggle_sequential_download(self, infohash_list)
Toggle sequential download in supplied torrents. :param infohash_list: Single or list() of infohashes.
4.904469
6.415916
0.764422
data = self._process_infohash_list(infohash_list) return self._post('command/toggleFirstLastPiecePrio', data=data)
def toggle_first_last_piece_priority(self, infohash_list)
Toggle first/last piece priority of supplied torrents. :param infohash_list: Single or list() of infohashes.
5.133995
6.589214
0.779151
data = self._process_infohash_list(infohash_list) data.update({'value': json.dumps(value)}) return self._post('command/setForceStart', data=data)
def force_start(self, infohash_list, value=True)
Force start selected torrents. :param infohash_list: Single or list() of infohashes. :param value: Force start value (bool)
4.763013
5.635033
0.84525
target = list(filter(lambda x: x['name'] == name, current_app.config['VUE_CONFIGURATION'])) if not target: raise ValueError('Can not find resource from configuration.') target = target[0] use_minified = (isinstance(use_minified, bool) and use_minified) or current_app.config['VUE_USE_MINIFIE...
def vue_find_resource(name, use_minified=None)
Resource finding function, also available in templates. :param name: Script to find a URL for. :param use_minified': If set to True/False, use/don't use minified. If None, honors VUE_USE_MINIFIED. :return: A URL.
3.027352
3.153662
0.959948
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)) # ...
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
1.526649
1.537309
0.993066
return len(string) - wcswidth(re.compile(r'\x1b[^m]*m').sub('', string))
def ansi_len(string)
Extra length due to any ANSI sequences in the string.
5.514968
5.040817
1.094062
return linestyle.begin + linestyle.sep.join(data) + linestyle.end
def format_line(data, linestyle)
Formats a list of elements using the given line style
8.635626
9.448091
0.914008
if isinstance(width, int): widths = [width] * n else: assert len(width) == n, "Widths and data do not match" widths = width return widths
def parse_width(width, n)
Parses an int or array of widths Parameters ---------- width : int or array_like n : int
3.998322
4.357481
0.917576
# Number of columns in the table. ncols = len(data[0]) if headers is None else len(headers) tablestyle = STYLES[style] widths = parse_width(width, ncols) # Initialize with a hr or the header tablestr = [hrule(ncols, widths, tablestyle.top)] \ if headers is None else [header(headers...
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, option...
3.741008
4.028293
0.928683
tablestyle = STYLES[style] widths = parse_width(width, len(headers)) alignment = ALIGNMENTS[align] # string formatter data = map(lambda x: ('{:%s%d}' % (alignment, x[0] + ansi_len(x[1]))).format(x[1]), zip(widths, headers)) # build the formatted str headerstr = format_line(data, table...
def header(headers, width=WIDTH, align=ALIGN, style=STYLE, add_hr=True)
Returns a formatted row of column header strings Parameters ---------- headers : list of strings A list of n strings, the column headers width : int The width of each column (Default: 11) style : string or tuple, optional A formatting style (see STYLES) Returns --...
4.679575
4.866587
0.961572
tablestyle = STYLES[style] widths = parse_width(width, len(values)) assert isinstance(format_spec, string_types) | isinstance(format_spec, list), \ "format_spec must be a string or list of strings" if isinstance(format_spec, string_types): format_spec = [format_spec] * len(list(va...
def row(values, width=WIDTH, format_spec=FMT, align=ALIGN, style=STYLE)
Returns a formatted row of data Parameters ---------- values : array_like An iterable array of data (numbers or strings), each value is printed in a separate column width : int The width of each column (Default: 11) format_spec : string The precision format string used to ...
4.174871
4.128023
1.011349
widths = parse_width(width, n) hrstr = linestyle.sep.join([('{:%s^%i}' % (linestyle.hline, width)).format('') for width in widths]) return linestyle.begin + hrstr + linestyle.end
def hrule(n=1, width=WIDTH, linestyle=LineStyle('', '─', '─', ''))
Returns a formatted string used as a border between table rows Parameters ---------- n : int The number of columns in the table width : int The width of each column (Default: 11) linestyle : tuple A LineStyle namedtuple containing the characters for (begin, hr, sep, end). ...
9.666331
8.660334
1.116162
return hrule(n, width, linestyle=STYLES[style].top)
def top(n, width=WIDTH, style=STYLE)
Prints the top row of a table
19.987354
22.530643
0.887119
out.write(header([message], width=max(width, len(message)), style=style) + '\n') out.flush()
def banner(message, width=30, style='banner', out=sys.stdout)
Prints a banner message Parameters ---------- message : string The message to print in the banner width : int The minimum width of the banner (Default: 30) style : string A line formatting style (Default: 'banner') out : writer An object that has write() and f...
4.823862
6.772581
0.712263
table(df.values, list(df.columns), **kwargs)
def dataframe(df, **kwargs)
Print table with data from the given pandas DataFrame Parameters ---------- df : DataFrame A pandas DataFrame with the table to print
10.848034
13.438373
0.807243
self._query_params += str(QueryParam.ADVANCED) + str(QueryParam.ADDRESS) + address.replace(" ", "+").lower()
def set_address(self, address)
Set the address. :param address:
16.367613
18.529297
0.883337
self._query_params += str(QueryParam.MIN_LEASE) + str(min_lease)
def set_min_lease(self, min_lease)
Set the minimum lease period in months. :param min_lease: int
12.467407
12.028742
1.036468
self._query_params += str(QueryParam.DAYS_OLD) + str(added)
def set_added_since(self, added)
Set this to retrieve ads that are a given number of days old. For example to retrieve listings that have been been added a week ago: set_added_since(7) :param added: int
37.382473
19.710928
1.896535
self._query_params += str(QueryParam.MAX_LEASE) + str(max_lease)
def set_max_lease(self, max_lease)
Set the maximum lease period in months. :param max_lease: int
12.755933
12.367872
1.031377
if availability >= 5: availability = '5%2B' self._query_params += str(QueryParam.AVALIABILITY) + str(availability)
def set_availability(self, availability)
Set the maximum lease period in months. :param availability:
17.136461
21.409325
0.80042
if not isinstance(room_type, RoomType): raise DaftException("room_type should be an instance of RoomType.") self._query_params += str(QueryParam.ROOM_TYPE) + str(room_type)
def set_room_type(self, room_type)
Set the room type. :param room_type:
6.383217
6.631351
0.962582
self._query_params += str(QueryParam.KEYWORDS) + '+'.join(keywords)
def set_keywords(self, keywords)
Pass an array to filter the result by keywords. :param keywords
27.186144
31.236244
0.87034
self._area = area.replace(" ", "-").lower() if isinstance(area, str) else ','.join( map(lambda x: x.lower().replace(' ', '-'), area))
def set_area(self, area)
The area to retrieve listings from. Use an array to search multiple areas. :param area: :return:
5.225183
4.661112
1.121016
if open_viewing: self._open_viewing = open_viewing self._query_params += str(QueryParam.OPEN_VIEWING)
def set_open_viewing(self, open_viewing)
Set to True to only search for properties that have upcoming 'open for viewing' dates. :param open_viewing: :return:
5.83337
6.163843
0.946385
if not isinstance(offset, int) or offset < 0: raise DaftException("Offset should be a positive integer.") self._offset = str(offset)
def set_offset(self, offset)
The page number which is in increments of 10. The default page number is 0. :param offset: :return:
5.825535
5.704303
1.021253
if not isinstance(min_price, int): raise DaftException("Min price should be an integer.") self._min_price = str(min_price) self._price += str(QueryParam.MIN_PRICE) + self._min_price
def set_min_price(self, min_price)
The minimum price. :param min_price: :return:
5.812325
5.627678
1.03281
if not isinstance(max_price, int): raise DaftException("Max price should be an integer.") self._max_price = str(max_price) self._price += str(QueryParam.MAX_PRICE) + self._max_price
def set_max_price(self, max_price)
The maximum price. :param max_price: :return:
5.934095
5.822236
1.019213
if not isinstance(listing_type, SaleType) and not isinstance(listing_type, RentType): raise DaftException("listing_type should be an instance of SaleType or RentType.") self._listing_type = listing_type
def set_listing_type(self, listing_type)
The listings you'd like to scrape i.e houses, properties, auction, commercial or apartments. Use the SaleType or RentType enum to select the listing type. i.e set_listing_type(SaleType.PROPERTIES) :param listing_type: :return:
4.299635
3.428326
1.25415
if not isinstance(min_beds, int): raise DaftException("Minimum number of beds should be an integer.") self._min_beds = str(min_beds) self._query_params += str(QueryParam.MIN_BEDS) + self._min_beds
def set_min_beds(self, min_beds)
The minimum number of beds. :param min_beds: :return:
4.785684
4.558824
1.049763
if not isinstance(max_beds, int): raise DaftException("Maximum number of beds should be an integer.") self._max_beds = str(max_beds) self._query_params += str(QueryParam.MAX_BEDS) + self._max_beds
def set_max_beds(self, max_beds)
The maximum number of beds. :param max_beds: :return:
4.584907
4.775801
0.960029
if not isinstance(sort_by, SortType): raise DaftException("sort_by should be an instance of SortType.") self._sort_by = str(sort_by)
def set_sort_by(self, sort_by)
Use this method to sort by price, distance, upcoming viewing or date using the SortType object. :param sort_by: :return:
4.630876
4.766937
0.971457
if not isinstance(sort_order, SortOrder): raise DaftException("sort_order should be an instance of SortOrder.") self._sort_order = str(sort_order)
def set_sort_order(self, sort_order)
Use the SortOrder object to sort the listings descending or ascending. :param sort_order: :return:
4.578309
4.622444
0.990452
if not isinstance(commercial_property_type, CommercialType): raise DaftException("commercial_property_type should be an instance of CommercialType.") self._commercial_property_type = str(commercial_property_type)
def set_commercial_property_type(self, commercial_property_type)
Use the CommercialType object to set the commercial property type. :param commercial_property_type: :return:
3.875751
3.346841
1.158033
if not isinstance(commercial_min_size, int): raise DaftException("commercial_min_size should be an integer.") self._commercial_min_size = str(commercial_min_size) self._query_params += str(QueryParam.COMMERCIAL_MIN) + self._commercial_min_size
def set_commercial_min_size(self, commercial_min_size)
The minimum size in sq ft. :param commercial_min_size: :return:
4.457711
4.531115
0.9838
if not isinstance(commercial_max_size, int): raise DaftException("commercial_max_size should be an integer.") self._commercial_max_size = str(commercial_max_size) self._query_params += str(QueryParam.COMMERCIAL_MAX) + self._commercial_max_size
def set_commercial_max_size(self, commercial_max_size)
The maximum size in sq ft. :param commercial_max_size: :return:
4.533268
4.570607
0.991831
if not isinstance(student_accommodation_type, StudentAccommodationType): raise DaftException("student_accommodation_type should be an instance of StudentAccommodationType.") self._student_accommodation_type = str(student_accommodation_type)
def set_student_accommodation_type(self, student_accommodation_type)
Set the student accomodation type. :param student_accommodation_type: StudentAccomodationType
2.904191
3.193361
0.909447
self._query_params += str(QueryParam.NUM_OCCUPANTS) + str(num_occupants)
def set_num_occupants(self, num_occupants)
Set the max number of occupants living in the property for rent. :param num_occupants: int
8.768801
8.550938
1.025478
self._query_params += str(QueryParam.ROUTE_ID) + str(public_transport_route)
def set_public_transport_route(self, public_transport_route)
Set the public transport route. :param public_transport_route: TransportRoute
12.937896
17.661486
0.732549
query_add = '' for property_type in property_types: if not isinstance(property_type, PropertyType): raise DaftException("property_types should be an instance of PropertyType.") query_add += str(property_type) self._query_params += query_add
def set_property_type(self, property_types)
Set the property type for rents. :param property_types: Array of Enum PropertyType
4.825181
5.143664
0.938083
self.set_url() listings = [] request = Request(debug=self._debug) url = self.get_url() soup = request.get(url) divs = soup.find_all("div", {"class": "box"}) [listings.append(Listing(div, debug=self._debug)) for div in divs] return listings
def search(self)
The search function returns an array of Listing objects. :return: Listing object
4.216974
3.747396
1.125308
try: if self._data_from_search: return self._data_from_search.find('div', {'class': 'price-changes-sr'}).text else: return self._ad_page_content.find('div', {'class': 'price-changes-sr'}).text except Exception as e: if self._de...
def price_change(self)
This method returns any price change. :return:
3.988734
3.898333
1.02319
upcoming_viewings = [] try: if self._data_from_search: viewings = self._data_from_search.find_all( 'div', {'class': 'smi-onview-text'}) else: viewings = [] except Exception as e: if self._debug: ...
def upcoming_viewings(self)
Returns an array of upcoming viewings for a property. :return:
3.87794
3.921945
0.98878
facilities = [] try: list_items = self._ad_page_content.select("#facilities li") except Exception as e: if self._debug: logging.error( "Error getting facilities. Error message: " + e.args[0]) return for li ...
def facilities(self)
This method returns the properties facilities. :return:
5.024544
5.173619
0.971186
overviews = [] try: list_items = self._ad_page_content.select("#overview li") except Exception as e: if self._debug: logging.error( "Error getting overviews. Error message: " + e.args[0]) return for li in l...
def overviews(self)
This method returns the properties overviews. :return:
4.890062
5.024737
0.973198
features = [] try: list_items = self._ad_page_content.select("#features li") except Exception as e: if self._debug: logging.error( "Error getting features. Error message: " + e.args[0]) return for li in lis...
def features(self)
This method returns the properties features. :return:
5.309292
5.239774
1.013267
try: if self._data_from_search: t = self._data_from_search.find('a').contents[0] else: t = self._ad_page_content.find( 'div', {'class': 'smi-object-header'}).find( 'h1').text.strip() except Exceptio...
def formalised_address(self)
This method returns the formalised address. :return:
4.843636
4.781
1.013101
formalised_address = self.formalised_address if formalised_address is None: return try: address = formalised_address.split(',') except Exception as e: if self._debug: logging.error( "Error getting address_li...
def address_line_1(self)
This method returns the first line of the address. :return:
4.263002
4.046046
1.053622
try: uls = self._ad_page_content.find( "ul", {"class": "smi-gallery-list"}) except Exception as e: if self._debug: logging.error( "Error getting images. Error message: " + e.args[0]) return images = ...
def images(self)
This method returns the listing image. :return:
4.272308
4.162261
1.026439