Search is not available for this dataset
text
stringlengths
75
104k
def __normalize(self): """ Adjusts the values of the filters to be correct. For example, if you set grade 'B' to True, then 'All' should be set to False """ # Don't normalize if we're already normalizing or intializing if self.__normalizing is True or self.__init...
def validate_one(self, loan): """ Validate a single loan result record against the filters Parameters ---------- loan : dict A single loan note record Returns ------- boolean True or raises FilterValidationError Raises ...
def search_string(self): """" Returns the JSON string that LendingClub expects for it's search """ self.__normalize() # Get the template tmpl_source = unicode(open(self.tmpl_file).read()) # Process template compiler = Compiler() template = compil...
def all_filters(lc): """ Get a list of all your saved filters Parameters ---------- lc : :py:class:`lendingclub.LendingClub` An instance of the authenticated LendingClub class Returns ------- list A list of lendingclub.filters.Sav...
def load(self): """ Load the filter from the server """ # Attempt to load the saved filter payload = { 'id': self.id } response = self.lc.session.get('/browse/getSavedFilterAj.action', query=payload) self.response = response json_respo...
def __analyze(self): """ Analyze the filter JSON and attempt to parse out the individual filters. """ filter_values = {} # ID to filter name mapping name_map = { 10: 'grades', 11: 'loan_purpose', 13: 'approved', 15: 'fundin...
def _float_copy_to_out(out, origin): """ Copy origin to out and return it. If ``out`` is None, a new copy (casted to floating point) is used. If ``out`` and ``origin`` are the same, we simply return it. Otherwise we copy the values. """ if out is None: out = origin / 1 # The divis...
def _double_centered_imp(a, out=None): """ Real implementation of :func:`double_centered`. This function is used to make parameter ``out`` keyword-only in Python 2. """ out = _float_copy_to_out(out, a) dim = np.size(a, 0) mu = np.sum(a) / (dim * dim) sum_cols = np.sum(a, 0, keepd...
def _u_centered_imp(a, out=None): """ Real implementation of :func:`u_centered`. This function is used to make parameter ``out`` keyword-only in Python 2. """ out = _float_copy_to_out(out, a) dim = np.size(a, 0) u_mu = np.sum(a) / ((dim - 1) * (dim - 2)) sum_cols = np.sum(a, 0, k...
def u_product(a, b): r""" Inner product in the Hilbert space of :math:`U`-centered distance matrices. This inner product is defined as .. math:: \frac{1}{n(n-3)} \sum_{i,j=1}^n a_{i, j} b_{i, j} Parameters ---------- a: array_like First input array to be multiplied. b:...
def u_projection(a): r""" Return the orthogonal projection function over :math:`a`. The function returned computes the orthogonal projection over :math:`a` in the Hilbert space of :math:`U`-centered distance matrices. The projection of a matrix :math:`B` over a matrix :math:`A` is defined ...
def u_complementary_projection(a): r""" Return the orthogonal projection function over :math:`a^{\perp}`. The function returned computes the orthogonal projection over :math:`a^{\perp}` (the complementary projection over a) in the Hilbert space of :math:`U`-centered distance matrices. The proj...
def _distance_matrix_generic(x, centering, exponent=1): """Compute a centered distance matrix given a matrix.""" _check_valid_dcov_exponent(exponent) x = _transform_to_2d(x) # Calculate distance matrices a = distances.pairwise_distances(x, exponent=exponent) # Double centering a = centeri...
def _af_inv_scaled(x): """Scale a random vector for using the affinely invariant measures""" x = _transform_to_2d(x) cov_matrix = np.atleast_2d(np.cov(x, rowvar=False)) cov_matrix_power = _mat_sqrt_inv(cov_matrix) return x.dot(cov_matrix_power)
def partial_distance_covariance(x, y, z): """ Partial distance covariance estimator. Compute the estimator for the partial distance covariance of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------...
def partial_distance_correlation(x, y, z): # pylint:disable=too-many-locals """ Partial distance correlation estimator. Compute the estimator for the partial distance correlation of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :ma...
def _energy_distance_from_distance_matrices( distance_xx, distance_yy, distance_xy): """Compute energy distance with precalculated distance matrices.""" return (2 * np.mean(distance_xy) - np.mean(distance_xx) - np.mean(distance_yy))
def _energy_distance_imp(x, y, exponent=1): """ Real implementation of :func:`energy_distance`. This function is used to make parameter ``exponent`` keyword-only in Python 2. """ x = _transform_to_2d(x) y = _transform_to_2d(y) _check_valid_energy_exponent(exponent) distance_xx = ...
def _distance_covariance_sqr_naive(x, y, exponent=1): """ Naive biased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _distance_matrix(x, exponent=exponent) b = _distance_matrix(y, e...
def _u_distance_covariance_sqr_naive(x, y, exponent=1): """ Naive unbiased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _u_distance_matrix(x, exponent=exponent) b = _u_distance_mat...
def _distance_sqr_stats_naive_generic(x, y, matrix_centered, product, exponent=1): """Compute generic squared stats.""" a = matrix_centered(x, exponent=exponent) b = matrix_centered(y, exponent=exponent) covariance_xy_sqr = product(a, b) variance_x_sqr = produc...
def _distance_correlation_sqr_naive(x, y, exponent=1): """Biased distance correlation estimator between two matrices.""" return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_distance_matrix, product=mean_product, exponent=exponent).correlation_xy
def _u_distance_correlation_sqr_naive(x, y, exponent=1): """Bias-corrected distance correlation estimator between two matrices.""" return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_u_distance_matrix, product=u_product, exponent=exponent).correlation_xy
def _can_use_fast_algorithm(x, y, exponent=1): """ Check if the fast algorithm for distance stats can be used. The fast algorithm has complexity :math:`O(NlogN)`, better than the complexity of the naive algorithm (:math:`O(N^2)`). The algorithm can only be used for random variables (not vectors) w...
def _dyad_update(y, c): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """ Inner function of the fast distance covariance. This function is compiled because otherwise it would become a bottleneck. """ n = y.shape[0...
def _distance_covariance_sqr_fast_generic( x, y, unbiased=False): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """Fast algorithm for the squared distance covariance.""" x = np.asarray(x) y = np.asarray(y) x = np.r...
def _distance_stats_sqr_fast_generic(x, y, dcov_function): """Compute the distance stats using the fast algorithm.""" covariance_xy_sqr = dcov_function(x, y) variance_x_sqr = dcov_function(x, x) variance_y_sqr = dcov_function(y, y) denominator_sqr_signed = variance_x_sqr * variance_y_sqr denomin...
def distance_covariance_sqr(x, y, **kwargs): """ distance_covariance_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with t...
def u_distance_covariance_sqr(x, y, **kwargs): """ u_distance_covariance_sqr(x, y, *, exponent=1) Computes the unbiased estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the...
def distance_stats_sqr(x, y, **kwargs): """ distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- ...
def u_distance_stats_sqr(x, y, **kwargs): """ u_distance_stats_sqr(x, y, *, exponent=1) Computes the unbiased estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- ...
def distance_stats(x, y, **kwargs): """ distance_stats(x, y, *, exponent=1) Computes the usual (biased) estimators for the distance covariance and distance correlation between two random vectors, and the individual distance variances. Parameters ---------- x: array_like First r...
def distance_correlation_sqr(x, y, **kwargs): """ distance_correlation_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond wit...
def u_distance_correlation_sqr(x, y, **kwargs): """ u_distance_correlation_sqr(x, y, *, exponent=1) Computes the bias-corrected estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond...
def distance_correlation_af_inv_sqr(x, y): """ Square of the affinely invariant distance correlation. Computes the estimator for the square of the affinely invariant distance correlation between two random vectors. .. warning:: The return value of this function is undefined when the ...
def pairwise(function, x, y=None, **kwargs): """ pairwise(function, x, y=None, *, pool=None, is_symmetric=None, **kwargs) Computes a dependency measure between each pair of elements. Parameters ---------- function: Dependency measure function. x: iterable of array_like First list o...
def _pairwise_imp(function, x, y=None, pool=None, is_symmetric=None, **kwargs): """ Real implementation of :func:`pairwise`. This function is used to make several parameters keyword-only in Python 2. """ map_function = pool.map if pool else map if is_symmetric is None: is_symmetri...
def _jit(function): """ Compile a function using a jit compiler. The function is always compiled to check errors, but is only used outside tests, so that code coverage analysis can be performed in jitted functions. The tests set sys._called_from_test in conftest.py. """ import sys co...
def _sqrt(x): """ Return square root of an ndarray. This sqrt function for ndarrays tries to use the exponentiation operator if the objects stored do not supply a sqrt method. """ x = np.clip(x, a_min=0, a_max=None) try: return np.sqrt(x) except AttributeError: exponen...
def _transform_to_2d(t): """Convert vectors to column matrices, to always have a 2d shape.""" t = np.asarray(t) dim = len(t.shape) assert dim <= 2 if dim < 2: t = np.atleast_2d(t).T return t
def _can_be_double(x): """ Return if the array can be safely converted to double. That happens when the dtype is a float with the same size of a double or narrower, or when is an integer that can be safely converted to double (if the roundtrip conversion works). """ return ((np.issubdtype(...
def _cdist_naive(x, y, exponent=1): """Pairwise distance, custom implementation.""" squared_norms = ((x[_np.newaxis, :, :] - y[:, _np.newaxis, :]) ** 2).sum(2) exponent = exponent / 2 try: exponent = squared_norms.take(0).from_float(exponent) except AttributeError: pass return ...
def _pdist_scipy(x, exponent=1): """Pairwise distance between points in a set.""" metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.pdist(x, metric=metric) distances = _spatial.distance.squareform(distances) if exponent != 1: distances...
def _cdist_scipy(x, y, exponent=1): """Pairwise distance between the points in two sets.""" metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.cdist(x, y, metric=metric) if exponent != 1: distances **= exponent / 2 return distances
def _pdist(x, exponent=1): """ Pairwise distance between points in a set. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. """ if _can_be_double(x): return _pdist_scipy(x, exponent) ...
def _cdist(x, y, exponent=1): """ Pairwise distance between points in two sets. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. """ if _can_be_double(x) and _can_be_double(y): return _c...
def pairwise_distances(x, y=None, **kwargs): r""" pairwise_distances(x, y=None, *, exponent=1) Pairwise distance between points. Return the pairwise distance between points in two sets, or in the same set if only one set is passed. Parameters ---------- x: array_like An :math:...
def respond(self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None): """ Respond to the request. This generates the :attr:`mohawk.Receiver.response_header` attribute. :param content=E...
def calculate_payload_hash(payload, algorithm, content_type): """Calculates a hash for a given payload.""" p_hash = hashlib.new(algorithm) parts = [] parts.append('hawk.' + str(HAWK_VER) + '.payload\n') parts.append(parse_content_type(content_type) + '\n') parts.append(payload or '') parts....
def calculate_mac(mac_type, resource, content_hash): """Calculates a message authorization code (MAC).""" normalized = normalize_string(mac_type, resource, content_hash) log.debug(u'normalized resource for mac calc: {norm}' .format(norm=normalized)) digestmod = getattr(hashlib, resource.cr...
def calculate_ts_mac(ts, credentials): """Calculates a message authorization code (MAC) for a timestamp.""" normalized = ('hawk.{hawk_ver}.ts\n{ts}\n' .format(hawk_ver=HAWK_VER, ts=ts)) log.debug(u'normalized resource for ts mac calc: {norm}' .format(norm=normalized)) dig...
def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string.""" normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(res...
def parse_authorization_header(auth_header): """ Example Authorization header: 'Hawk id="dh37fgj492je", ts="1367076201", nonce="NPHgnG", ext="and welcome!", mac="CeWHy4d9kbLGhDlkyw2Nh3PJ7SDOdZDa267KH4ZaNMY="' """ if len(auth_header) > MAX_LENGTH: raise BadHeaderValue('Header exc...
def get_bewit(resource): """ Returns a bewit identifier for the resource as a string. :param resource: Resource to generate a bewit for :type resource: `mohawk.base.Resource` """ if resource.method != 'GET': raise ValueError('bewits can only be generated for GET requests') i...
def parse_bewit(bewit): """ Returns a `bewittuple` representing the parts of an encoded bewit string. This has the following named attributes: (id, expiration, mac, ext) :param bewit: A base64 encoded bewit string :type bewit: str """ decoded_bewit = b64decode(bewit).decode(...
def strip_bewit(url): """ Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str """ m = re.search('[?&]bewit=([^&]+)', url) if not m: rai...
def check_bewit(url, credential_lookup, now=None): """ Validates the given bewit. Returns True if the resource has a valid bewit parameter attached, or raises a subclass of HawkFail otherwise. :param credential_lookup: Callable to look up the credentials dict by sender ID. The cred...
def accept_response(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds...
def current_state(self): """ Returns a ``field -> value`` dict of the current state of the instance. """ field_names = set() [field_names.add(f.name) for f in self._meta.local_fields] [field_names.add(f.attname) for f in self._meta.local_fields] return dict([(fiel...
def was_persisted(self): """ Returns true if the instance was persisted (saved) in its old state. Examples:: >>> user = User() >>> user.save() >>> user.was_persisted() False >>> user = User.objects.get(pk=1) >>> u...
def _trim(cls, s): """ Remove trailing colons from the URI back to the first non-colon. :param string s: input URI string :returns: URI string with trailing colons removed :rtype: string TEST: trailing colons necessary >>> s = '1:2::::' >>> CPE._trim(s)...
def _create_cpe_parts(self, system, components): """ Create the structure to store the input type of system associated with components of CPE Name (hardware, operating system and software). :param string system: type of system associated with CPE Name :param dict components: CPE...
def _get_attribute_components(self, att): """ Returns the component list of input attribute. :param string att: Attribute name to get :returns: List of Component objects of the attribute in CPE Name :rtype: list :exception: ValueError - invalid attribute name """...
def _pack_edition(self): """ Pack the values of the five arguments into the simple edition component. If all the values are blank, just return a blank. :returns: "edition", "sw_edition", "target_sw", "target_hw" and "other" attributes packed in a only value :rtype: s...
def as_uri_2_3(self): """ Returns the CPE Name as URI string of version 2.3. :returns: CPE Name as URI string of version 2.3 :rtype: string :exception: TypeError - incompatible version """ uri = [] uri.append("cpe:/") ordered_comp_parts = { ...
def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ from .cpe2_3_wfn import CPE2_3_WFN wfn = [] wfn.append(CPE2_3_W...
def as_fs(self): """ Returns the CPE Name as formatted string of version 2.3. :returns: CPE Name as formatted string :rtype: string :exception: TypeError - incompatible version """ fs = [] fs.append("cpe:2.3:") for i in range(0, len(CPEComponent...
def _is_alphanum(cls, c): """ Returns True if c is an uppercase letter, a lowercase letter, a digit or an underscore, otherwise False. :param string c: Character to check :returns: True if char is alphanumeric or an underscore, False otherwise :rtype: boolean...
def _pct_encode_uri(cls, c): """ Return the appropriate percent-encoding of character c (URI string). Certain characters are returned without encoding. :param string c: Character to check :returns: Encoded character as URI :rtype: string TEST: >>> c = '...
def _is_valid_language(self): """ Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() lang_rxc = re.comp...
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() part_rxc = re...
def _parse(self, comp_att): """ Check if the value of component is correct in the attribute "comp_att". :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component """ errmsg = "Invali...
def as_fs(self): """ Returns the value of component encoded as formatted string. Inspect each character in value of component. Certain nonalpha characters pass thru without escaping into the result, but most retain escaping. :returns: Formatted string associated with co...
def as_uri_2_3(self): """ Returns the value of component encoded as URI string. Scans an input string s and applies the following transformations: - Pass alphanumeric characters thru untouched - Percent-encode quoted non-alphanumerics as needed - Unquoted special charac...
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_str: new value of component :param string comp_att: attribute associated with value of component :returns: None :exception: V...
def _decode(self): """ Convert the characters of string s to standard value (WFN value). Inspect each character in value of component. Copy quoted characters, with their escaping, into the result. Look for unquoted non alphanumerics and if not "*" or "?", add escaping. :...
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self.cpe_str.find(" ") != -1): errmsg = "Bad-formed CPE Name: it must not have whitespaces...
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - in...
def set_value(self, comp_str): """ Set the value of component. :param string comp_str: value of component :returns: None :exception: ValueError - incorrect value of component """ self._is_negated = False self._encoded_value = comp_str self._stand...
def _decode(self): """ Convert the encoded value of component to standard value (WFN value). """ s = self._encoded_value elements = s.replace('~', '').split('!') dec_elements = [] for elem in elements: result = [] idx = 0 whil...
def _is_valid_value(self): """ Return True if the value of component in generic attribute is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value value_pattern = [] valu...
def as_wfn(self): r""" Returns the value of compoment encoded as Well-Formed Name (WFN) string. :returns: WFN string :rtype: string TEST: >>> val = 'xp!vista' >>> comp1 = CPEComponent1_1(val, CPEComponentSimple.ATT_VERSION) >>> comp1.as_wfn() ...
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component TEST:...
def _create_component(cls, att, value): """ Returns a component with value "value". :param string att: Attribute name :param string value: Attribute value :returns: Component object created :rtype: CPEComponent :exception: ValueError - invalid value of attribute ...
def _unpack_edition(cls, value): """ Unpack its elements and set the attributes in wfn accordingly. Parse out the five elements: ~ edition ~ software edition ~ target sw ~ target hw ~ other :param string value: Value of edition attribute :returns: Dictionary with parts ...
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" ...
def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. If edition component is not packed, only shows the first seven components, otherwise shows all. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatib...
def _decode(self): """ Convert the characters of character in value of component to standard value (WFN value). This function scans the value of component and returns a copy with all percent-encoded characters decoded. :exception: ValueError - invalid character in value ...
def _is_valid_edition(self): """ Return True if the input value of attribute "edition" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._standard_value[0] packed = [] packed.app...
def _is_valid_language(self): """ Return True if the value of component in attribute "language" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean CASE 1: Language part with/without region part CASE 2: Language part ...
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value # Check if value of ...
def _compare(cls, source, target): """ Compares two values associated with a attribute of two WFNs, which may be logical values (ANY or NA) or string values. :param string source: First attribute value :param string target: Second attribute value :returns: The attribute ...
def _compare_strings(cls, source, target): """ Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) ...
def _contains_wildcards(cls, s): """ Return True if the string contains any unquoted special characters (question-mark or asterisk), otherwise False. Ex: _contains_wildcards("foo") => FALSE Ex: _contains_wildcards("foo\?") => FALSE Ex: _contains_wildcards("foo?") => TRUE...
def _is_even_wildcards(cls, str, idx): """ Returns True if an even number of escape (backslash) characters precede the character at index idx in string str. :param string str: string to check :returns: True if an even number of escape characters precede the character...
def _is_string(cls, arg): """ Return True if arg is a string value, and False if arg is a logical value (ANY or NA). :param string arg: string to check :returns: True if value is a string, False if it is a logical value. :rtype: boolean This function is a suppor...
def compare_wfns(cls, source, target): """ Compares two WFNs and returns a generator of pairwise attribute-value comparison results. It provides full access to the individual comparison results to enable use-case specific implementations of novel name-comparison algorithms. ...
def cpe_disjoint(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is DISJOINT. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation betwe...
def cpe_equal(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is EQUAL. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between sou...
def cpe_subset(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUBSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relat...