_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q239800
percent_pareto_recharges
train
def percent_pareto_recharges(recharges, percentage=0.8): """ Percentage of recharges that account for 80% of total recharged amount. """ amounts = sorted([r.amount for r in recharges], reverse=True) total_sum = sum(amounts) partial_sum = 0 for count, a in enumerate(amounts): partial...
python
{ "resource": "" }
q239801
average_balance_recharges
train
def average_balance_recharges(user, **kwargs): """ Return the average daily balance estimated from all recharges. We assume a linear usage between two recharges, and an empty balance before a recharge. The average balance can be seen as the area under the curve delimited by all recharges. """ ...
python
{ "resource": "" }
q239802
_round_half_hour
train
def _round_half_hour(record): """ Round a time DOWN to half nearest half-hour. """ k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30)) return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)
python
{ "resource": "" }
q239803
matrix_index
train
def matrix_index(user): """ Returns the keys associated with each axis of the matrices. The first key is always the name of the current user, followed by the sorted names of all the correspondants. """ other_keys = sorted([k for k in user.network.keys() if k != user.name]) return [user.nam...
python
{ "resource": "" }
q239804
matrix_directed_unweighted
train
def matrix_directed_unweighted(user): """ Returns a directed, unweighted matrix where an edge exists if there is at least one call or text. """ matrix = _interaction_matrix(user, interaction=None) for a in range(len(matrix)): for b in range(len(matrix)): if matrix[a][b] is no...
python
{ "resource": "" }
q239805
matrix_undirected_weighted
train
def matrix_undirected_weighted(user, interaction=None): """ Returns an undirected, weighted matrix for call, text and call duration where an edge exists if the relationship is reciprocated. """ matrix = _interaction_matrix(user, interaction=interaction) result = [[0 for _ in range(len(matrix))] ...
python
{ "resource": "" }
q239806
matrix_undirected_unweighted
train
def matrix_undirected_unweighted(user): """ Returns an undirected, unweighted matrix where an edge exists if the relationship is reciprocated. """ matrix = matrix_undirected_weighted(user, interaction=None) for a, b in combinations(range(len(matrix)), 2): if matrix[a][b] is None or matri...
python
{ "resource": "" }
q239807
clustering_coefficient_unweighted
train
def clustering_coefficient_unweighted(user): """ The clustering coefficient of the user in the unweighted, undirected ego network. It is defined by counting the number of closed triplets including the current user: .. math:: C = \\frac{2 * \\text{closed triplets}}{ \\text{degree} \, (\...
python
{ "resource": "" }
q239808
clustering_coefficient_weighted
train
def clustering_coefficient_weighted(user, interaction=None): """ The clustering coefficient of the user's weighted, undirected network. It is defined the same way as :meth`~bandicoot.network.clustering_coefficient_unweighted`, except that closed triplets are weighted by the number of interactions. For ...
python
{ "resource": "" }
q239809
assortativity_indicators
train
def assortativity_indicators(user): """ Computes the assortativity of indicators. This indicator measures the similarity of the current user with his correspondants, for all bandicoot indicators. For each one, it calculates the variance of the current user's value with the values for all his co...
python
{ "resource": "" }
q239810
assortativity_attributes
train
def assortativity_attributes(user): """ Computes the assortativity of the nominal attributes. This indicator measures the homophily of the current user with his correspondants, for each attributes. It returns a value between 0 (no assortativity) and 1 (all the contacts share the same value): th...
python
{ "resource": "" }
q239811
network_sampling
train
def network_sampling(n, filename, directory=None, snowball=False, user=None): """ Selects a few users and exports a CSV of indicators for them. TODO: Returns the network/graph between the selected users. Parameters ---------- n : int Number of users to select. filename : string ...
python
{ "resource": "" }
q239812
export
train
def export(user, directory=None, warnings=True): """ Build a temporary directory with the visualization. Returns the local path where files have been written. Examples -------- >>> bandicoot.visualization.export(U) Successfully exported the visualization to /tmp/tmpsIyncS """ ...
python
{ "resource": "" }
q239813
run
train
def run(user, port=4242): """ Build a temporary directory with a visualization and serve it over HTTP. Examples -------- >>> bandicoot.visualization.run(U) Successfully exported the visualization to /tmp/tmpsIyncS Serving bandicoot visualization at http://0.0.0.0:4242 """ ...
python
{ "resource": "" }
q239814
to_csv
train
def to_csv(objects, filename, digits=5, warnings=True): """ Export the flatten indicators of one or several users to CSV. Parameters ---------- objects : list List of objects to be exported. filename : string File to export to. digits : int Precision of floats. ...
python
{ "resource": "" }
q239815
to_json
train
def to_json(objects, filename, warnings=True): """ Export the indicators of one or several users to JSON. Parameters ---------- objects : list List of objects to be exported. filename : string File to export to. Examples -------- This function can be use to export t...
python
{ "resource": "" }
q239816
_parse_record
train
def _parse_record(data, duration_format='seconds'): """ Parse a raw data dictionary and return a Record object. """ def _map_duration(s): if s == '': return None elif duration_format.lower() == 'seconds': return int(s) else: t = time.strptime(...
python
{ "resource": "" }
q239817
filter_record
train
def filter_record(records): """ Filter records and remove items with missing or inconsistent fields Parameters ---------- records : list A list of Record objects Returns ------- records, ignored : (Record list, dict) A tuple of filtered records, and a dictionary counti...
python
{ "resource": "" }
q239818
read_csv
train
def read_csv(user_id, records_path, antennas_path=None, attributes_path=None, recharges_path=None, network=False, duration_format='seconds', describe=True, warnings=True, errors=False, drop_duplicates=False): """ Load user records from a CSV file. Parameters ---------- us...
python
{ "resource": "" }
q239819
interevent_time
train
def interevent_time(records): """ The interevent time between two records of the user. """ inter_events = pairwise(r.datetime for r in records) inter = [(new - old).total_seconds() for old, new in inter_events] return summary_stats(inter)
python
{ "resource": "" }
q239820
number_of_contacts
train
def number_of_contacts(records, direction=None, more=0): """ The number of contacts the user interacted with. Parameters ---------- direction : str, optional Filters the records by their direction: ``None`` for all records, ``'in'`` for incoming, and ``'out'`` for outgoing. more...
python
{ "resource": "" }
q239821
entropy_of_contacts
train
def entropy_of_contacts(records, normalize=False): """ The entropy of the user's contacts. Parameters ---------- normalize: boolean, default is False Returns a normalized entropy between 0 and 1. """ counter = Counter(r.correspondent_id for r in records) raw_entropy = entropy(...
python
{ "resource": "" }
q239822
interactions_per_contact
train
def interactions_per_contact(records, direction=None): """ The number of interactions a user had with each of its contacts. Parameters ---------- direction : str, optional Filters the records by their direction: ``None`` for all records, ``'in'`` for incoming, and ``'out'`` for outg...
python
{ "resource": "" }
q239823
percent_initiated_interactions
train
def percent_initiated_interactions(records, user): """ The percentage of calls initiated by the user. """ if len(records) == 0: return 0 initiated = sum(1 for r in records if r.direction == 'out') return initiated / len(records)
python
{ "resource": "" }
q239824
percent_nocturnal
train
def percent_nocturnal(records, user): """ The percentage of interactions the user had at night. By default, nights are 7pm-7am. Nightimes can be set in ``User.night_start`` and ``User.night_end``. """ if len(records) == 0: return 0 if user.night_start < user.night_end: nigh...
python
{ "resource": "" }
q239825
call_duration
train
def call_duration(records, direction=None): """ The duration of the user's calls. Parameters ---------- direction : str, optional Filters the records by their direction: ``None`` for all records, ``'in'`` for incoming, and ``'out'`` for outgoing. """ if direction is None: ...
python
{ "resource": "" }
q239826
_conversations
train
def _conversations(group, delta=datetime.timedelta(hours=1)): """ Group texts into conversations. The function returns an iterator over records grouped by conversations. See :ref:`Using bandicoot <conversations-label>` for a definition of conversations. A conversation begins when one person se...
python
{ "resource": "" }
q239827
percent_initiated_conversations
train
def percent_initiated_conversations(records): """ The percentage of conversations that have been initiated by the user. Each call and each text conversation is weighted as a single interaction. See :ref:`Using bandicoot <conversations-label>` for a definition of conversations. """ interact...
python
{ "resource": "" }
q239828
active_days
train
def active_days(records): """ The number of days during which the user was active. A user is considered active if he sends a text, receives a text, initiates a call, receives a call, or has a mobility point. """ days = set(r.datetime.date() for r in records) return len(days)
python
{ "resource": "" }
q239829
percent_pareto_interactions
train
def percent_pareto_interactions(records, percentage=0.8): """ The percentage of user's contacts that account for 80% of its interactions. """ if len(records) == 0: return None user_count = Counter(r.correspondent_id for r in records) target = int(math.ceil(sum(user_count.values()) * pe...
python
{ "resource": "" }
q239830
number_of_interactions
train
def number_of_interactions(records, direction=None): """ The number of interactions. Parameters ---------- direction : str, optional Filters the records by their direction: ``None`` for all records, ``'in'`` for incoming, and ``'out'`` for outgoing. """ if direction is None:...
python
{ "resource": "" }
q239831
to_csv
train
def to_csv(weekmatrices, filename, digits=5): """ Exports a list of week-matrices to a specified filename in the CSV format. Parameters ---------- weekmatrices : list The week-matrices to export. filename : string Path for the exported CSV file. """ with open(filename, ...
python
{ "resource": "" }
q239832
read_csv
train
def read_csv(filename): """ Read a list of week-matrices from a CSV file. """ with open(filename, 'r') as f: r = csv.reader(f) next(r) # remove header wm = list(r) # remove header and convert to numeric for i, row in enumerate(wm): row[1:4] = map(int, row[1:4])...
python
{ "resource": "" }
q239833
_extract_list_from_generator
train
def _extract_list_from_generator(generator): """ Iterates over a generator to extract all the objects and add them to a list. Useful when the objects have to be used multiple times. """ extracted = [] for i in generator: extracted.append(list(i)) return extracted
python
{ "resource": "" }
q239834
_seconds_to_section_split
train
def _seconds_to_section_split(record, sections): """ Finds the seconds to the next section from the datetime of a record. """ next_section = sections[ bisect_right(sections, _find_weektime(record.datetime))] * 60 return next_section - _find_weektime(record.datetime, time_type='sec')
python
{ "resource": "" }
q239835
get_neighbors
train
def get_neighbors(distance_matrix, source, eps): """ Given a matrix of distance between couples of points, return the list of every point closer than eps from a certain point. """ return [dest for dest, distance in enumerate(distance_matrix[source]) if distance < eps]
python
{ "resource": "" }
q239836
fix_location
train
def fix_location(records, max_elapsed_seconds=300): """ Update position of all records based on the position of the closest GPS record. .. note:: Use this function when call and text records are missing a location, but you have access to accurate GPS traces. """ groups = itertool...
python
{ "resource": "" }
q239837
fetch
train
def fetch(cert, issuer, hash_algo='sha1', nonce=True, user_agent=None, timeout=10): """ Fetches an OCSP response for a certificate :param cert: An asn1cyrpto.x509.Certificate object to get an OCSP reponse for :param issuer: An asn1crypto.x509.Certificate object that is the issuer of ce...
python
{ "resource": "" }
q239838
CertificateRegistry._walk_issuers
train
def _walk_issuers(self, path, paths, failed_paths): """ Recursively looks through the list of known certificates for the issuer of the certificate specified, stopping once the certificate in question is one contained within the CA certs list :param path: A Validation...
python
{ "resource": "" }
q239839
CertificateRegistry._possible_issuers
train
def _possible_issuers(self, cert): """ Returns a generator that will list all possible issuers for the cert :param cert: An asn1crypto.x509.Certificate object to find the issuer of """ issuer_hashable = cert.issuer.hashable if issuer_hashable not in self._su...
python
{ "resource": "" }
q239840
ValidationPath.find_issuer
train
def find_issuer(self, cert): """ Return the issuer of the cert specified, as defined by this path :param cert: An asn1crypto.x509.Certificate object to get the issuer of :raises: LookupError - when the issuer of the certificate could not be found :retur...
python
{ "resource": "" }
q239841
ValidationPath.truncate_to
train
def truncate_to(self, cert): """ Remove all certificates in the path after the cert specified :param cert: An asn1crypto.x509.Certificate object to find :raises: LookupError - when the certificate could not be found :return: The current Vali...
python
{ "resource": "" }
q239842
ValidationPath.truncate_to_issuer
train
def truncate_to_issuer(self, cert): """ Remove all certificates in the path after the issuer of the cert specified, as defined by this path :param cert: An asn1crypto.x509.Certificate object to find the issuer of :raises: LookupError - when the issuer of...
python
{ "resource": "" }
q239843
ValidationPath.copy
train
def copy(self): """ Creates a copy of this path :return: A ValidationPath object """ copy = self.__class__() copy._certs = self._certs[:] copy._cert_hashes = self._cert_hashes.copy() return copy
python
{ "resource": "" }
q239844
ValidationPath.pop
train
def pop(self): """ Removes the last certificate from the path :return: The current ValidationPath object, for chaining """ last_cert = self._certs.pop() self._cert_hashes.remove(last_cert.issuer_serial) return self
python
{ "resource": "" }
q239845
fetch
train
def fetch(cert, use_deltas=True, user_agent=None, timeout=10): """ Fetches the CRLs for a certificate :param cert: An asn1cyrpto.x509.Certificate object to get the CRL for :param use_deltas: A boolean indicating if delta CRLs should be fetched :param user_agent: The HTTP u...
python
{ "resource": "" }
q239846
_grab_crl
train
def _grab_crl(user_agent, url, timeout): """ Fetches a CRL and parses it :param user_agent: A unicode string of the user agent to use when fetching the URL :param url: A unicode string of the URL to fetch the CRL from :param timeout: The number of seconds after which an HT...
python
{ "resource": "" }
q239847
fetch_certs
train
def fetch_certs(certificate_list, user_agent=None, timeout=10): """ Fetches certificates from the authority information access extension of an asn1crypto.crl.CertificateList object and places them into the cert registry. :param certificate_list: An asn1crypto.crl.CertificateList object ...
python
{ "resource": "" }
q239848
CertificateValidator.validate_usage
train
def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=False): """ Validates the certificate path and that the certificate is valid for the key usage and extended key usage purposes specified. :param key_usage: A set of unicode strings of the required...
python
{ "resource": "" }
q239849
CertificateValidator.validate_tls
train
def validate_tls(self, hostname): """ Validates the certificate path, that the certificate is valid for the hostname provided and that the certificate is valid for the purpose of a TLS connection. :param hostname: A unicode string of the TLS server hostname ...
python
{ "resource": "" }
q239850
ValidationContext.crls
train
def crls(self): """ A list of all cached asn1crypto.crl.CertificateList objects """ if not self._allow_fetching: return self._crls output = [] for issuer_serial in self._fetched_crls: output.extend(self._fetched_crls[issuer_serial]) retur...
python
{ "resource": "" }
q239851
ValidationContext.ocsps
train
def ocsps(self): """ A list of all cached asn1crypto.ocsp.OCSPResponse objects """ if not self._allow_fetching: return self._ocsps output = [] for issuer_serial in self._fetched_ocsps: output.extend(self._fetched_ocsps[issuer_serial]) ret...
python
{ "resource": "" }
q239852
ValidationContext._extract_ocsp_certs
train
def _extract_ocsp_certs(self, ocsp_response): """ Extracts any certificates included with an OCSP response and adds them to the certificate registry :param ocsp_response: An asn1crypto.ocsp.OCSPResponse object to look for certs inside of """ status = ocsp_re...
python
{ "resource": "" }
q239853
ValidationContext.check_validation
train
def check_validation(self, cert): """ Checks to see if a certificate has been validated, and if so, returns the ValidationPath used to validate it. :param cert: An asn1crypto.x509.Certificate object :return: None if not validated, or a certvalidator.path...
python
{ "resource": "" }
q239854
ValidationContext.clear_validation
train
def clear_validation(self, cert): """ Clears the record that a certificate has been validated :param cert: An ans1crypto.x509.Certificate object """ if cert.signature in self._validate_map: del self._validate_map[cert.signature]
python
{ "resource": "" }
q239855
_find_cert_in_list
train
def _find_cert_in_list(cert, issuer, certificate_list, crl_issuer): """ Looks for a cert in the list of revoked certificates :param cert: An asn1crypto.x509.Certificate object of the cert being checked :param issuer: An asn1crypto.x509.Certificate object of the cert issuer :param ...
python
{ "resource": "" }
q239856
PolicyTreeRoot.add_child
train
def add_child(self, valid_policy, qualifier_set, expected_policy_set): """ Creates a new PolicyTreeNode as a child of this node :param valid_policy: A unicode string of a policy name or OID :param qualifier_set: An instance of asn1crypto.x509.PolicyQualifierInfo...
python
{ "resource": "" }
q239857
PolicyTreeRoot.at_depth
train
def at_depth(self, depth): """ Returns a generator yielding all nodes in the tree at a specific depth :param depth: An integer >= 0 of the depth of nodes to yield :return: A generator yielding PolicyTreeNode objects """ for child in list(self.ch...
python
{ "resource": "" }
q239858
PolicyTreeRoot.walk_up
train
def walk_up(self, depth): """ Returns a generator yielding all nodes in the tree at a specific depth, or above. Yields nodes starting with leaves and traversing up to the root. :param depth: An integer >= 0 of the depth of nodes to walk up from :return: ...
python
{ "resource": "" }
q239859
MemcachePool.clear
train
def clear(self): """Clear pool connections.""" while not self._pool.empty(): conn = yield from self._pool.get() self._do_close(conn)
python
{ "resource": "" }
q239860
MemcachePool.acquire
train
def acquire(self): """Acquire connection from the pool, or spawn new one if pool maxsize permits. :return: ``tuple`` (reader, writer) """ while self.size() == 0 or self.size() < self._minsize: _conn = yield from self._create_new_conn() if _conn is None: ...
python
{ "resource": "" }
q239861
MemcachePool.release
train
def release(self, conn): """Releases connection back to the pool. :param conn: ``namedtuple`` (reader, writer) """ self._in_use.remove(conn) if conn.reader.at_eof() or conn.reader.exception(): self._do_close(conn) else: self._pool.put_nowait(conn)
python
{ "resource": "" }
q239862
Client.get
train
def get(self, conn, key, default=None): """Gets a single value from the server. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, is the data for this specified key. """ values, _ = yield ...
python
{ "resource": "" }
q239863
Client.gets
train
def gets(self, conn, key, default=None): """Gets a single value from the server together with the cas token. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, ``bytes tuple with the value and the cas ...
python
{ "resource": "" }
q239864
Client.multi_get
train
def multi_get(self, conn, *keys): """Takes a list of keys and returns a list of values. :param keys: ``list`` keys for the item being fetched. :return: ``list`` of values for the specified keys. :raises:``ValidationException``, ``ClientException``, and socket errors """ ...
python
{ "resource": "" }
q239865
Client.stats
train
def stats(self, conn, args=None): """Runs a stats command on the server.""" # req - stats [additional args]\r\n # resp - STAT <name> <value>\r\n (one per result) # END\r\n if args is None: args = b'' conn.writer.write(b''.join((b'stats ', args, b'\r\n...
python
{ "resource": "" }
q239866
Client.append
train
def append(self, conn, key, value, exptime=0): """Add data to an existing key after existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :retur...
python
{ "resource": "" }
q239867
Client.prepend
train
def prepend(self, conn, key, value, exptime=0): """Add data to an existing key before existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :retu...
python
{ "resource": "" }
q239868
Client.incr
train
def incr(self, conn, key, increment=1): """Command is used to change data for some item in-place, incrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change ...
python
{ "resource": "" }
q239869
Client.decr
train
def decr(self, conn, key, decrement=1): """Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change ...
python
{ "resource": "" }
q239870
Client.touch
train
def touch(self, conn, key, exptime): """The command is used to update the expiration time of an existing item without fetching it. :param key: ``bytes``, is the key to update expiration time :param exptime: ``int``, is expiration time. This replaces the existing expiration time....
python
{ "resource": "" }
q239871
Client.version
train
def version(self, conn): """Current version of the server. :return: ``bytes``, memcached version for current the server. """ command = b'version\r\n' response = yield from self._execute_simple_command( conn, command) if not response.startswith(const.VERSION)...
python
{ "resource": "" }
q239872
Client.flush_all
train
def flush_all(self, conn): """Its effect is to invalidate all existing items immediately""" command = b'flush_all\r\n' response = yield from self._execute_simple_command( conn, command) if const.OK != response: raise ClientException('Memcached flush_all failed', ...
python
{ "resource": "" }
q239873
Telegraph.create_account
train
def create_account(self, short_name, author_name=None, author_url=None, replace_token=True): """ Create a new Telegraph account :param short_name: Account name, helps users with several accounts remember which they are currently using. ...
python
{ "resource": "" }
q239874
Telegraph.edit_account_info
train
def edit_account_info(self, short_name=None, author_name=None, author_url=None): """ Update information about a Telegraph account. Pass only the parameters that you want to edit :param short_name: Account name, helps users with several ac...
python
{ "resource": "" }
q239875
Telegraph.revoke_access_token
train
def revoke_access_token(self): """ Revoke access_token and generate a new one, for example, if the user would like to reset all connected sessions, or you have reasons to believe the token was compromised. On success, returns dict with new access_token and auth_url fields ...
python
{ "resource": "" }
q239876
Telegraph.get_page
train
def get_page(self, path, return_content=True, return_html=True): """ Get a Telegraph page :param path: Path to the Telegraph page (in the format Title-12-31, i.e. everything that comes after https://telegra.ph/) :param return_content: If true, content field will be returne...
python
{ "resource": "" }
q239877
Telegraph.create_page
train
def create_page(self, title, content=None, html_content=None, author_name=None, author_url=None, return_content=False): """ Create a new Telegraph page :param title: Page title :param content: Content in nodes list format (see doc) :param html_content: Content in H...
python
{ "resource": "" }
q239878
Telegraph.get_account_info
train
def get_account_info(self, fields=None): """ Get information about a Telegraph account :param fields: List of account fields to return. Available fields: short_name, author_name, author_url, auth_url, page_count Default: [“short_name”,“author_name”,“author...
python
{ "resource": "" }
q239879
Telegraph.get_views
train
def get_views(self, path, year=None, month=None, day=None, hour=None): """ Get the number of views for a Telegraph article :param path: Path to the Telegraph page :param year: Required if month is passed. If passed, the number of page views for the requested year will be r...
python
{ "resource": "" }
q239880
upload_file
train
def upload_file(f): """ Upload file to Telegra.ph's servers. Returns a list of links. Allowed only .jpg, .jpeg, .png, .gif and .mp4 files. :param f: filename or file-like object. :type f: file, str or list """ with FilesOpener(f) as files: response = requests.post( 'http...
python
{ "resource": "" }
q239881
NaturalKeyModelManager.get_by_natural_key
train
def get_by_natural_key(self, *args): """ Return the object corresponding to the provided natural key. (This is a generic implementation of the standard Django function) """ kwargs = self.natural_key_kwargs(*args) # Since kwargs already has __ lookups in it, we could ju...
python
{ "resource": "" }
q239882
NaturalKeyModelManager.create_by_natural_key
train
def create_by_natural_key(self, *args): """ Create a new object from the provided natural key values. If the natural key contains related objects, recursively get or create them by their natural keys. """ kwargs = self.natural_key_kwargs(*args) for name, rel_to ...
python
{ "resource": "" }
q239883
NaturalKeyModelManager.get_or_create_by_natural_key
train
def get_or_create_by_natural_key(self, *args): """ get_or_create + get_by_natural_key """ try: return self.get_by_natural_key(*args), False except self.model.DoesNotExist: return self.create_by_natural_key(*args), True
python
{ "resource": "" }
q239884
NaturalKeyModelManager.resolve_keys
train
def resolve_keys(self, keys, auto_create=False): """ Resolve the list of given keys into objects, if possible. Returns a mapping and a success indicator. """ resolved = {} success = True for key in keys: if auto_create: resolved[key] = ...
python
{ "resource": "" }
q239885
NaturalKeyModel.get_natural_key_info
train
def get_natural_key_info(cls): """ Derive natural key from first unique_together definition, noting which fields are related objects vs. regular fields. """ fields = cls.get_natural_key_def() info = [] for name in fields: field = cls._meta.get_field(na...
python
{ "resource": "" }
q239886
NaturalKeyModel.get_natural_key_fields
train
def get_natural_key_fields(cls): """ Determine actual natural key field list, incorporating the natural keys of related objects as needed. """ natural_key = [] for name, rel_to in cls.get_natural_key_info(): if not rel_to: natural_key.append(na...
python
{ "resource": "" }
q239887
NaturalKeyModel.natural_key
train
def natural_key(self): """ Return the natural key for this object. (This is a generic implementation of the standard Django function) """ # Recursively extract properties from related objects if needed vals = [reduce(getattr, name.split('__'), self) for n...
python
{ "resource": "" }
q239888
SourceRef.derive_coordinates
train
def derive_coordinates(self): """ Depending on the compilation source, some members of the SourceRef object may be incomplete. Calling this function performs the necessary derivations to complete the object. """ if self._coordinates_resolved: # Coordi...
python
{ "resource": "" }
q239889
MessagePrinter.format_message
train
def format_message(self, severity, text, src_ref): """ Formats the message prior to emitting it. Parameters ---------- severity: :class:`Severity` Message severity. text: str Body of message src_ref: :class:`SourceRef` Referenc...
python
{ "resource": "" }
q239890
MessagePrinter.emit_message
train
def emit_message(self, lines): """ Emit message. Default printer emits messages to stderr Parameters ---------- lines: list List of strings containing each line of the message """ for line in lines: print(line, file=sys.stderr)
python
{ "resource": "" }
q239891
Parameter.get_value
train
def get_value(self): """ Evaluate self.expr to get the parameter's value """ if (self._value is None) and (self.expr is not None): self._value = self.expr.get_value() return self._value
python
{ "resource": "" }
q239892
is_castable
train
def is_castable(src, dst): """ Check if src type can be cast to dst type """ if ((src in [int, bool]) or rdltypes.is_user_enum(src)) and (dst in [int, bool]): # Pure numeric or enum can be cast to a numeric return True elif (src == rdltypes.ArrayPlaceholder) and (dst == rdltypes.Arra...
python
{ "resource": "" }
q239893
InstRef.predict_type
train
def predict_type(self): """ Traverse the ref_elements path and determine the component type being referenced. Also do some checks on the array indexes """ current_comp = self.ref_root for name, array_suffixes, name_src_ref in self.ref_elements: # find...
python
{ "resource": "" }
q239894
InstRef.get_value
train
def get_value(self, eval_width=None): """ Build a resolved ComponentRef container that describes the relative path """ resolved_ref_elements = [] for name, array_suffixes, name_src_ref in self.ref_elements: idx_list = [ suffix.get_value() for suffix in array_suffixe...
python
{ "resource": "" }
q239895
PropRef.predict_type
train
def predict_type(self): """ Predict the type of the inst_ref, and make sure the property being referenced is allowed """ inst_type = self.inst_ref.predict_type() if self.prop_ref_type.allowed_inst_type != inst_type: self.msg.fatal( "'%s' is no...
python
{ "resource": "" }
q239896
get_group_node_size
train
def get_group_node_size(node): """ Shared getter for AddrmapNode and RegfileNode's "size" property """ # After structural placement, children are sorted if( not node.inst.children or (not isinstance(node.inst.children[-1], comp.AddressableComponent)) ): # No addressable child exi...
python
{ "resource": "" }
q239897
Node.add_derived_property
train
def add_derived_property(cls, getter_function, name=None): """ Register a user-defined derived property Parameters ---------- getter_function : function Function that fetches the result of the user-defined derived property name : str Derived prope...
python
{ "resource": "" }
q239898
Node.children
train
def children(self, unroll=False, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate children of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_presen...
python
{ "resource": "" }
q239899
Node.descendants
train
def descendants(self, unroll=False, skip_not_present=True, in_post_order=False): """ Returns an iterator that provides nodes for all descendants of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. ...
python
{ "resource": "" }