_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q2900
Asset.new_withdraw_ong_transaction
train
def new_withdraw_ong_transaction(self, b58_claimer_address: str, b58_recv_address: str, amount: int, b58_payer_address: str, gas_limit: int, gas_price: int) -> Transaction: """ This interface is used to generate a Transaction object that allow one account to ...
python
{ "resource": "" }
q2901
Asset.transfer
train
def transfer(self, asset: str, from_acct: Account, b58_to_address: str, amount: int, payer: Account, gas_limit: int, gas_price: int): """ This interface is used to send a transfer transaction that only for ONT or ONG. :param asset: a string which is used to indicate which asset...
python
{ "resource": "" }
q2902
Asset.withdraw_ong
train
def withdraw_ong(self, claimer: Account, b58_recv_address: str, amount: int, payer: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to withdraw a amount of ong and transfer them to receive address. :param claimer: the owner of ong that remained t...
python
{ "resource": "" }
q2903
Asset.approve
train
def approve(self, asset, sender: Account, b58_recv_address: str, amount: int, payer: Account, gas_limit: int, gas_price: int) -> str: """ This is an interface used to send an approve transaction which allow receiver to spend a amount of ONT or ONG asset in sender's account. ...
python
{ "resource": "" }
q2904
WalletData.remove_account
train
def remove_account(self, address: str): """ This interface is used to remove account from WalletData. :param address: a string address. """ account = self.get_account_by_b58_address(address) if account is None: raise SDKException(ErrorCode.get_account_by_addr...
python
{ "resource": "" }
q2905
WalletData.set_default_account_by_index
train
def set_default_account_by_index(self, index: int): """ This interface is used to set default account by given index. :param index: an int value that indicate the account object in account list. """ if index >= len(self.accounts): raise SDKException(ErrorCode.param_e...
python
{ "resource": "" }
q2906
WalletData.set_default_account_by_address
train
def set_default_account_by_address(self, b58_address: str): """ This interface is used to set default account by given base58 encode address. :param b58_address: a base58 encode address. """ flag = True index = -1 for acct in self.accounts: index += 1...
python
{ "resource": "" }
q2907
WalletData.set_default_identity_by_index
train
def set_default_identity_by_index(self, index: int): """ This interface is used to set default account by given an index value. :param index: an int value that indicate the position of an account object in account list. """ identities_len = len(self.identities) if index ...
python
{ "resource": "" }
q2908
read_gtf
train
def read_gtf( filepath_or_buffer, expand_attribute_column=True, infer_biotype_column=False, column_converters={}, usecols=None, features=None, chunksize=1024 * 1024): """ Parse a GTF into a dictionary mapping column names to sequences of values. Param...
python
{ "resource": "" }
q2909
create_missing_features
train
def create_missing_features( dataframe, unique_keys={}, extra_columns={}, missing_value=None): """ Helper function used to construct a missing feature such as 'transcript' or 'gene'. Some GTF files only have 'exon' and 'CDS' entries, but have transcript_id and gene_id ann...
python
{ "resource": "" }
q2910
SyncClient.get_action
train
def get_action(self, key): """ returns the action to perform on this key based on its state before the last sync. """ index_local_timestamp = self.get_index_local_timestamp(key) real_local_timestamp = self.get_real_local_timestamp(key) remote_timestamp = self.get_...
python
{ "resource": "" }
q2911
LocalSyncClient.lock
train
def lock(self, timeout=10): """ Advisory lock. Use to ensure that only one LocalSyncClient is working on the Target at the same time. """ logger.debug("Locking %s", self.lock_file) if not os.path.exists(self.lock_file): self.ensure_path(self.lock_file) ...
python
{ "resource": "" }
q2912
LocalSyncClient.unlock
train
def unlock(self): """ Unlock the active advisory lock. """ logger.debug("Releasing lock %s", self.lock_file) self._lock.release() try: os.unlink(self.lock_file) except FileNotFoundError: pass
python
{ "resource": "" }
q2913
ProxyMetaClass._no_proxy
train
def _no_proxy(method): """ Returns a wrapped version of `method`, such that proxying is turned off during the method call. """ @wraps(method) def wrapper(self, *args, **kwargs): notproxied = _oga(self, "__notproxied__") _osa(self, "__notproxied__...
python
{ "resource": "" }
q2914
Proxy._should_proxy
train
def _should_proxy(self, attr): """ Determines whether `attr` should be looked up on the proxied object, or the proxy itself. """ if attr in type(self).__notproxied__: return False if _oga(self, "__notproxied__") is True: return False retur...
python
{ "resource": "" }
q2915
Proxy.add_proxy_meth
train
def add_proxy_meth(cls, name, func, arg_pos=0): """ Add a method `name` to the class, which returns the value of `func`, called with the proxied value inserted at `arg_pos` """ @wraps(func) def proxied(self, *args, **kwargs): args = list(args) ar...
python
{ "resource": "" }
q2916
load_uri
train
def load_uri(uri, base_uri=None, loader=None, jsonschema=False, load_on_repr=True): """ Load JSON data from ``uri`` with JSON references proxied to their referent data. :param uri: URI to fetch the JSON from :param kwargs: This function takes any of the keyword arguments from :meth:`JsonRef...
python
{ "resource": "" }
q2917
JsonRef.resolve_pointer
train
def resolve_pointer(self, document, pointer): """ Resolve a json pointer ``pointer`` within the referenced ``document``. :argument document: the referent document :argument str pointer: a json pointer URI fragment to resolve within it """ # Do only split at single forwa...
python
{ "resource": "" }
q2918
dump
train
def dump(obj, fp, container_count=False, sort_keys=False, no_float32=True, default=None): """Writes the given object as UBJSON to the provided file-like object Args: obj: The object to encode fp: write([size])-able object container_count (bool): Specify length for container types (inclu...
python
{ "resource": "" }
q2919
_resolve_version
train
def _resolve_version(version): """ Resolve LATEST version """ if version is not LATEST: return version resp = urlopen('https://pypi.python.org/pypi/setuptools/json') with contextlib.closing(resp): try: charset = resp.info().get_content_charset() except Except...
python
{ "resource": "" }
q2920
load
train
def load(fp, no_bytes=False, object_hook=None, object_pairs_hook=None, intern_object_keys=False): """Decodes and returns UBJSON from the given file-like object Args: fp: read([size])-able object no_bytes (bool): If set, typed UBJSON arrays (uint8) will not be converted ...
python
{ "resource": "" }
q2921
TSRequest.check_error_code
train
def check_error_code(self): """ For CredSSP version of 3 or newer, the server can response with an NtStatus error code with details of what error occurred. This method will check if the error code exists and throws an NTStatusException if it is no STATUS_SUCCESS. """ ...
python
{ "resource": "" }
q2922
GSSAPIContext.get_mechs_available
train
def get_mechs_available(): """ Returns a list of auth mechanisms that are available to the local GSSAPI instance. Because we are interacting with Windows, we only care if SPNEGO, Kerberos and NTLM are available where NTLM is the only wildcard that may not be available by default....
python
{ "resource": "" }
q2923
CredSSPContext.wrap
train
def wrap(self, data): """ Encrypts the data in preparation for sending to the server. The data is encrypted using the TLS channel negotiated between the client and the server. :param data: a byte string of data to encrypt :return: a byte string of the encrypted data ...
python
{ "resource": "" }
q2924
CredSSPContext.unwrap
train
def unwrap(self, encrypted_data): """ Decrypts the data send by the server using the TLS channel negotiated between the client and the server. :param encrypted_data: the byte string of the encrypted data :return: a byte string of the decrypted data """ length = s...
python
{ "resource": "" }
q2925
CredSSPContext._get_subject_public_key
train
def _get_subject_public_key(cert): """ Returns the SubjectPublicKey asn.1 field of the SubjectPublicKeyInfo field of the server's certificate. This is used in the server verification steps to thwart MitM attacks. :param cert: X509 certificate from pyOpenSSL .get_peer_certificate...
python
{ "resource": "" }
q2926
_KindleCloudReaderBrowser._to_reader_home
train
def _to_reader_home(self): """Navigate to the Cloud Reader library page. Raises: BrowserError: If the KCR homepage could not be loaded. ConnectionError: If there was a connection error. """ # NOTE: Prevents QueryInterface error caused by getting a URL # while switched to an iframe s...
python
{ "resource": "" }
q2927
_KindleCloudReaderBrowser._login
train
def _login(self, max_tries=2): """Logs in to Kindle Cloud Reader. Args: max_tries: The maximum number of login attempts that will be made. Raises: BrowserError: If method called when browser not at a signin URL. LoginError: If login unsuccessful after `max_tries` attempts. """ i...
python
{ "resource": "" }
q2928
_KindleCloudReaderBrowser._to_reader_frame
train
def _to_reader_frame(self): """Navigate to the KindleReader iframe.""" reader_frame = 'KindleReaderIFrame' frame_loaded = lambda br: br.find_elements_by_id(reader_frame) self._wait().until(frame_loaded) self.switch_to.frame(reader_frame) # pylint: disable=no-member reader_loaded = lambda br:...
python
{ "resource": "" }
q2929
_KindleCloudReaderBrowser._wait_for_js
train
def _wait_for_js(self): """Wait for the Kindle Cloud Reader JS modules to initialize. These modules provide the interface used to execute API queries. """ # Wait for the Module Manager to load mod_mgr_script = ur"return window.hasOwnProperty('KindleModuleManager');" mod_mgr_loaded = lambda br: ...
python
{ "resource": "" }
q2930
KindleCloudReaderAPI._get_api_call
train
def _get_api_call(self, function_name, *args): """Runs an api call with javascript-formatted arguments. Args: function_name: The name of the KindleAPI call to run. *args: Javascript-formatted arguments to pass to the API call. Returns: The result of the API call. Raises: APIEr...
python
{ "resource": "" }
q2931
KindleCloudReaderAPI.get_book_metadata
train
def get_book_metadata(self, asin): """Returns a book's metadata. Args: asin: The ASIN of the book to be queried. Returns: A `KindleBook` instance corresponding to the book associated with `asin`. """ kbm = self._get_api_call('get_book_metadata', '"%s"' % asin) return KindleCl...
python
{ "resource": "" }
q2932
KindleCloudReaderAPI.get_book_progress
train
def get_book_progress(self, asin): """Returns the progress data available for a book. NOTE: A summary of the two progress formats can be found in the docstring for `ReadingProgress`. Args: asin: The asin of the book to be queried. Returns: A `ReadingProgress` instance corresponding to...
python
{ "resource": "" }
q2933
KindleCloudReaderAPI.get_library_progress
train
def get_library_progress(self): """Returns the reading progress for all books in the kindle library. Returns: A mapping of ASINs to `ReadingProgress` instances corresponding to the books in the current user's library. """ kbp_dict = self._get_api_call('get_library_progress') return {asi...
python
{ "resource": "" }
q2934
KindleCloudReaderAPI.get_instance
train
def get_instance(*args, **kwargs): """Context manager for an instance of `KindleCloudReaderAPI`.""" inst = KindleCloudReaderAPI(*args, **kwargs) try: yield inst except Exception: raise finally: inst.close()
python
{ "resource": "" }
q2935
load_config
train
def load_config(path): """ Loads configuration from a path. Path can be a json file, or a directory containing config.json and zero or more *.txt files with word lists or phrase lists. Returns config dict. Raises InitializationError when something is wrong. """ path = os.path.abspath(...
python
{ "resource": "" }
q2936
_load_wordlist
train
def _load_wordlist(name, stream): """ Loads list of words or phrases from file. Returns "words" or "phrases" dictionary, the same as used in config. Raises Exception if file is missing or invalid. """ items = [] max_length = None multiword = False multiword_start = None number_o...
python
{ "resource": "" }
q2937
_create_lists
train
def _create_lists(config, results, current, stack, inside_cartesian=None): """ An ugly recursive method to transform config dict into a tree of AbstractNestedList. """ # Have we done it already? try: return results[current] except KeyError: pass # Check recursion depth an...
python
{ "resource": "" }
q2938
RandomGenerator.generate
train
def generate(self, pattern=None): """ Generates and returns random name as a list of strings. """ lst = self._lists[pattern] while True: result = lst[self._randrange(lst.length)] # 1. Check that there are no duplicates # 2. Check that there are...
python
{ "resource": "" }
q2939
RandomGenerator._dump
train
def _dump(self, stream, pattern=None, object_ids=False): """Dumps current tree into a text stream.""" return self._lists[pattern]._dump(stream, '', object_ids=object_ids)
python
{ "resource": "" }
q2940
alter_column
train
def alter_column(conn, table, column_name, func, schema=None): """ Run given callable against given table and given column in activity table jsonb data columns. This function is useful when you want to reflect type changes in your schema to activity table. In the following example we change the dat...
python
{ "resource": "" }
q2941
change_column_name
train
def change_column_name( conn, table, old_column_name, new_column_name, schema=None ): """ Changes given `activity` jsonb data column key. This function is useful when you want to reflect column name changes to activity table. :: from alembic import op from postgresq...
python
{ "resource": "" }
q2942
add_column
train
def add_column(conn, table, column_name, default_value=None, schema=None): """ Adds given column to `activity` table jsonb data columns. In the following example we reflect the changes made to our schema to activity table. :: import sqlalchemy as sa from alembic import op ...
python
{ "resource": "" }
q2943
remove_column
train
def remove_column(conn, table, column_name, schema=None): """ Removes given `activity` jsonb data column key. This function is useful when you are doing schema changes that require removing a column. Let's say you've been using PostgreSQL-Audit for a while for a table called article. Now you want t...
python
{ "resource": "" }
q2944
rename_table
train
def rename_table(conn, old_table_name, new_table_name, schema=None): """ Renames given table in activity table. You should remember to call this function whenever you rename a versioned table. :: from alembic import op from postgresql_audit import rename_table def upgrade(): ...
python
{ "resource": "" }
q2945
VersioningManager.instrument_versioned_classes
train
def instrument_versioned_classes(self, mapper, cls): """ Collect versioned class and add it to pending_classes list. :mapper mapper: SQLAlchemy mapper object :cls cls: SQLAlchemy declarative class """ if hasattr(cls, '__versioned__') and cls not in self.pending_classes: ...
python
{ "resource": "" }
q2946
VersioningManager.configure_versioned_classes
train
def configure_versioned_classes(self): """ Configures all versioned classes that were collected during instrumentation process. """ for cls in self.pending_classes: self.audit_table(cls.__table__, cls.__versioned__.get('exclude')) assign_actor(self.base, self....
python
{ "resource": "" }
q2947
pubmed_citation
train
def pubmed_citation(args=sys.argv[1:], out=sys.stdout): """Get a citation via the command line using a PubMed ID or PubMed URL""" parser = argparse.ArgumentParser( description='Get a citation using a PubMed ID or PubMed URL') parser.add_argument('query', help='PubMed ID or PubMed URL') parser.a...
python
{ "resource": "" }
q2948
pubmed_url
train
def pubmed_url(args=sys.argv[1:], resolve_doi=True, out=sys.stdout): """ Get a publication URL via the command line using a PubMed ID or PubMed URL """ parser = argparse.ArgumentParser( description='Get a publication URL using a PubMed ID or PubMed URL') parser.add_argument('query', help='P...
python
{ "resource": "" }
q2949
Publication.authors_et_al
train
def authors_et_al(self, max_authors=5): """ Return string with a truncated author list followed by 'et al.' """ author_list = self._author_list if len(author_list) <= max_authors: authors_et_al = self.authors else: authors_et_al = ", ".join( ...
python
{ "resource": "" }
q2950
Publication.parse_abstract
train
def parse_abstract(xml_dict): """ Parse PubMed XML dictionary to retrieve abstract. """ key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation', 'Article', 'Abstract', 'AbstractText'] abstract_xml = reduce(dict.get, key_path, xml_dict) abst...
python
{ "resource": "" }
q2951
Publication.get_pubmed_xml
train
def get_pubmed_xml(self): """ Use a PubMed ID to retrieve PubMed metadata in XML form. """ url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/' \ 'efetch.fcgi?db=pubmed&rettype=abstract&id={}' \ .format(self.pmid) try: response = urlopen(...
python
{ "resource": "" }
q2952
Publication.set_abstract
train
def set_abstract(self, xml_dict): """ If record has an abstract, extract it from PubMed's XML data """ if self.record.get('HasAbstract') == 1 and xml_dict: self.abstract = self.parse_abstract(xml_dict) else: self.abstract = ''
python
{ "resource": "" }
q2953
Publication.set_article_url
train
def set_article_url(self, resolve_doi=True): """ If record has a DOI, set article URL based on where the DOI points. """ if 'DOI' in self.record: doi_url = "/".join(['http://dx.doi.org', self.record['DOI']]) if resolve_doi: try: ...
python
{ "resource": "" }
q2954
Publication.set_pub_year_month_day
train
def set_pub_year_month_day(self, xml_dict): """ Set publication year, month, day from PubMed's XML data """ key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation', 'Article', 'Journal', 'JournalIssue', 'PubDate'] pubdate_xml = reduce(dict.get, key_...
python
{ "resource": "" }
q2955
PubMedLookup.get_pubmed_record
train
def get_pubmed_record(pmid): """Get PubMed record from PubMed ID.""" handle = Entrez.esummary(db="pubmed", id=pmid) record = Entrez.read(handle) return record
python
{ "resource": "" }
q2956
Simulation._initialize
train
def _initialize(self, register_value_map=None, memory_value_map=None, default_value=None): """ Sets the wire, register, and memory values to default or as specified. :param register_value_map: is a map of {Register: value}. :param memory_value_map: is a map of maps {Memory: {address: Value}}. ...
python
{ "resource": "" }
q2957
Simulation.step
train
def step(self, provided_inputs): """ Take the simulation forward one cycle :param provided_inputs: a dictionary mapping wirevectors to their values for this step All input wires must be in the provided_inputs in order for the simulation to accept these values Example: if we ha...
python
{ "resource": "" }
q2958
Simulation._execute
train
def _execute(self, net): """Handle the combinational logic update rules for the given net. This function, along with edge_update, defined the semantics of the primitive ops. Function updates self.value accordingly. """ if net.op in 'r@': return # registers and memor...
python
{ "resource": "" }
q2959
FastSimulation.step
train
def step(self, provided_inputs): """ Run the simulation for a cycle :param provided_inputs: a dictionary mapping WireVectors (or their names) to their values for this step eg: {wire: 3, "wire_name": 17} """ # validate_inputs for wire, value in provided_inputs...
python
{ "resource": "" }
q2960
FastSimulation.inspect_mem
train
def inspect_mem(self, mem): """ Get the values in a map during the current simulation cycle. :param mem: the memory to inspect :return: {address: value} Note that this returns the current memory state. Modifying the dictonary will also modify the state in the simulator ...
python
{ "resource": "" }
q2961
FastSimulation._arg_varname
train
def _arg_varname(self, wire): """ Input, Const, and Registers have special input values """ if isinstance(wire, (Input, Register)): return 'd[' + repr(wire.name) + ']' # passed in elif isinstance(wire, Const): return str(wire.val) # hardcoded els...
python
{ "resource": "" }
q2962
_WaveRendererBase._render_val_with_prev
train
def _render_val_with_prev(self, w, n, current_val, symbol_len): """Return a string encoding the given value in a waveform. :param w: The WireVector we are rendering to a waveform :param n: An integer from 0 to segment_len-1 :param current_val: the value to be rendered :param sym...
python
{ "resource": "" }
q2963
SimulationTrace.add_step
train
def add_step(self, value_map): """ Add the values in value_map to the end of the trace. """ if len(self.trace) == 0: raise PyrtlError('error, simulation trace needs at least 1 signal to track ' '(by default, unnamed signals are not traced -- try either passing ' ...
python
{ "resource": "" }
q2964
SimulationTrace.add_fast_step
train
def add_fast_step(self, fastsim): """ Add the fastsim context to the trace. """ for wire_name in self.trace: self.trace[wire_name].append(fastsim.context[wire_name])
python
{ "resource": "" }
q2965
SimulationTrace.print_vcd
train
def print_vcd(self, file=sys.stdout, include_clock=False): """ Print the trace out as a VCD File for use in other tools. :param file: file to open and output vcd dump to. :param include_clock: boolean specifying if the implicit clk should be included. Dumps the current trace to file as...
python
{ "resource": "" }
q2966
SimulationTrace.render_trace
train
def render_trace( self, trace_list=None, file=sys.stdout, render_cls=default_renderer(), symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True): """ Render the trace to a file using unicode and ASCII escape sequences. :param trace_list: A list of signals to be output...
python
{ "resource": "" }
q2967
prioritized_mux
train
def prioritized_mux(selects, vals): """ Returns the value in the first wire for which its select bit is 1 :param [WireVector] selects: a list of WireVectors signaling whether a wire should be chosen :param [WireVector] vals: values to return when the corresponding select value is 1 ...
python
{ "resource": "" }
q2968
demux
train
def demux(select): """ Demultiplexes a wire of arbitrary bitwidth :param WireVector select: indicates which wire to set on :return (WireVector, ...): a tuple of wires corresponding to each demultiplexed wire """ if len(select) == 1: return _demux_2(select) wires = demux(select[:-1]...
python
{ "resource": "" }
q2969
MultiSelector.finalize
train
def finalize(self): """ Connects the wires. """ self._check_finalized() self._final = True for dest_w, values in self.dest_instrs_info.items(): mux_vals = dict(zip(self.instructions, values)) dest_w <<= sparse_mux(self.signal_wire, mux_vals)
python
{ "resource": "" }
q2970
WireVector.bitmask
train
def bitmask(self): """ A property holding a bitmask of the same length as this WireVector. Specifically it is an integer with a number of bits set to 1 equal to the bitwidth of the WireVector. It is often times useful to "mask" an integer such that it fits in the the number of b...
python
{ "resource": "" }
q2971
log_middleware
train
def log_middleware(store): """log all actions to console as they are dispatched""" def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dispatch return wrapper
python
{ "resource": "" }
q2972
CompiledSimulation.inspect
train
def inspect(self, w): """Get the latest value of the wire given, if possible.""" if isinstance(w, WireVector): w = w.name try: vals = self.tracer.trace[w] except KeyError: pass else: if not vals: raise PyrtlError('No...
python
{ "resource": "" }
q2973
CompiledSimulation.run
train
def run(self, inputs): """Run many steps of the simulation. The argument is a list of input mappings for each step, and its length is the number of steps to be executed. """ steps = len(inputs) # create i/o arrays of the appropriate length ibuf_type = ctypes.c_ui...
python
{ "resource": "" }
q2974
CompiledSimulation._traceable
train
def _traceable(self, wv): """Check if wv is able to be traced If it is traceable due to a probe, record that probe in _probe_mapping. """ if isinstance(wv, (Input, Output)): return True for net in self.block.logic: if net.op == 'w' and net.args[0].name ==...
python
{ "resource": "" }
q2975
CompiledSimulation._remove_untraceable
train
def _remove_untraceable(self): """Remove from the tracer those wires that CompiledSimulation cannot track. Create _probe_mapping for wires only traceable via probes. """ self._probe_mapping = {} wvs = {wv for wv in self.tracer.wires_to_track if self._traceable(wv)} self....
python
{ "resource": "" }
q2976
CompiledSimulation._create_dll
train
def _create_dll(self): """Create a dynamically-linked library implementing the simulation logic.""" self._dir = tempfile.mkdtemp() with open(path.join(self._dir, 'pyrtlsim.c'), 'w') as f: self._create_code(lambda s: f.write(s+'\n')) if platform.system() == 'Darwin': ...
python
{ "resource": "" }
q2977
CompiledSimulation._makeini
train
def _makeini(self, w, v): """C initializer string for a wire with a given value.""" pieces = [] for n in range(self._limbs(w)): pieces.append(hex(v & ((1 << 64)-1))) v >>= 64 return ','.join(pieces).join('{}')
python
{ "resource": "" }
q2978
CompiledSimulation._makemask
train
def _makemask(self, dest, res, pos): """Create a bitmask. The value being masked is of width `res`. Limb number `pos` of `dest` is being assigned to. """ if (res is None or dest.bitwidth < res) and 0 < (dest.bitwidth - 64*pos) < 64: return '&0x{:X}'.format((1 << (des...
python
{ "resource": "" }
q2979
CompiledSimulation._getarglimb
train
def _getarglimb(self, arg, n): """Get the nth limb of the given wire. Returns '0' when the wire does not have sufficient limbs. """ return '{vn}[{n}]'.format(vn=self.varname[arg], n=n) if arg.bitwidth > 64*n else '0'
python
{ "resource": "" }
q2980
CompiledSimulation._clean_name
train
def _clean_name(self, prefix, obj): """Create a C variable name with the given prefix based on the name of obj.""" return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum()))
python
{ "resource": "" }
q2981
_trivial_mult
train
def _trivial_mult(A, B): """ turns a multiplication into an And gate if one of the wires is a bitwidth of 1 :param A: :param B: :return: """ if len(B) == 1: A, B = B, A # so that we can reuse the code below :) if len(A) == 1: a_vals = A.sign_extended(len(B)) ...
python
{ "resource": "" }
q2982
tree_multiplier
train
def tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): """ Build an fast unclocked multiplier for inputs A and B using a Wallace or Dada Tree. :param WireVector A, B: two input wires for the multiplication :param function reducer: Reduce the tree using either a Dada recud...
python
{ "resource": "" }
q2983
signed_tree_multiplier
train
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): """Same as tree_multiplier, but uses two's-complement signed integers""" if len(A) == 1 or len(B) == 1: raise pyrtl.PyrtlError("sign bit required, one or both wires too small") aneg, bneg = A[-1], B[-1]...
python
{ "resource": "" }
q2984
generalized_fma
train
def generalized_fma(mult_pairs, add_wires, signed=False, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): """Generated an opimitized fused multiply adder. A generalized FMA unit that multiplies each pair of numbers in mult_pairs, then adds the resulting numbers and and th...
python
{ "resource": "" }
q2985
net_transform
train
def net_transform(transform_func, block=None, **kwargs): """ Maps nets to new sets of nets according to a custom function :param transform_func: Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool) :return: """ block = working_block(block) with set_working_block(blo...
python
{ "resource": "" }
q2986
all_nets
train
def all_nets(transform_func): """Decorator that wraps a net transform function""" @functools.wraps(transform_func) def t_res(**kwargs): net_transform(transform_func, **kwargs) return t_res
python
{ "resource": "" }
q2987
wire_transform
train
def wire_transform(transform_func, select_types=WireVector, exclude_types=(Input, Output, Register, Const), block=None): """ Maps Wires to new sets of nets and wires according to a custom function :param transform_func: The function you want to run on all wires Function signature...
python
{ "resource": "" }
q2988
all_wires
train
def all_wires(transform_func): """Decorator that wraps a wire transform function""" @functools.wraps(transform_func) def t_res(**kwargs): wire_transform(transform_func, **kwargs) return t_res
python
{ "resource": "" }
q2989
replace_wires
train
def replace_wires(wire_map, block=None): """ Quickly replace all wires in a block :param {old_wire: new_wire} wire_map: mapping of old wires to new wires """ block = working_block(block) src_nets, dst_nets = block.net_connections(include_virtual_nodes=False) for old_w, new_w in wire_m...
python
{ "resource": "" }
q2990
clone_wire
train
def clone_wire(old_wire, name=None): """ Makes a copy of any existing wire :param old_wire: The wire to clone :param name: a name fo rhte new wire Note that this function is mainly intended to be used when the two wires are from different blocks. Making two wires with the same name in the ...
python
{ "resource": "" }
q2991
copy_block
train
def copy_block(block=None, update_working_block=True): """ Makes a copy of an existing block :param block: The block to clone. (defaults to the working block) :return: The resulting block """ block_in = working_block(block) block_out, temp_wv_map = _clone_block_and_wires(block_in) mems ...
python
{ "resource": "" }
q2992
_clone_block_and_wires
train
def _clone_block_and_wires(block_in): """ This is a generic function to copy the WireVectors for another round of synthesis This does not split a WireVector with multiple wires. :param block_in: The block to change :param synth_name: a name to prepend to all new copies of a wire :return: the re...
python
{ "resource": "" }
q2993
_copy_net
train
def _copy_net(block_out, net, temp_wv_net, mem_map): """This function makes a copy of all nets passed to it for synth uses """ new_args = tuple(temp_wv_net[a_arg] for a_arg in net.args) new_dests = tuple(temp_wv_net[a_dest] for a_dest in net.dests) if net.op in "m@": # special stuff for copying mem...
python
{ "resource": "" }
q2994
_get_new_block_mem_instance
train
def _get_new_block_mem_instance(op_param, mem_map, block_out): """ gets the instance of the memory in the new block that is associated with a memory in a old block """ memid, old_mem = op_param if old_mem not in mem_map: new_mem = old_mem._make_copy(block_out) new_mem.id = old_mem.id...
python
{ "resource": "" }
q2995
probe
train
def probe(w, name=None): """ Print useful information about a WireVector when in debug mode. :param w: WireVector from which to get info :param name: optional name for probe (defaults to an autogenerated name) :return: original WireVector w Probe can be inserted into a existing design easily as it...
python
{ "resource": "" }
q2996
rtl_assert
train
def rtl_assert(w, exp, block=None): """ Add hardware assertions to be checked on the RTL design. :param w: should be a WireVector :param Exception exp: Exception to throw when assertion fails :param Block block: block to which the assertion should be added (default to working block) :return: the Ou...
python
{ "resource": "" }
q2997
check_rtl_assertions
train
def check_rtl_assertions(sim): """ Checks the values in sim to see if any registers assertions fail. :param sim: Simulation in which to check the assertions :return: None """ for (w, exp) in sim.block.rtl_assert_dict.items(): try: value = sim.inspect(w) if not value...
python
{ "resource": "" }
q2998
wirevector_list
train
def wirevector_list(names, bitwidth=None, wvtype=WireVector): """ Allocate and return a list of WireVectors. :param names: Names for the WireVectors. Can be a list or single comma/space-separated string :param bitwidth: The desired bitwidth for the resulting WireVectors. :param WireVector wvtype: Which...
python
{ "resource": "" }
q2999
val_to_signed_integer
train
def val_to_signed_integer(value, bitwidth): """ Return value as intrepreted as a signed integer under twos complement. :param value: a python integer holding the value to convert :param bitwidth: the length of the integer in bits to assume for conversion Given an unsigned integer (not a wirevector!) c...
python
{ "resource": "" }