code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not position: position = (2. / 5 + offset, 3. / 5, 0) self._labels["right"] = (label, position, rotation, kwargs)
def right_axis_label(self, label, position=None, rotation=-60, offset=0.08, **kwargs)
Sets the label on the right axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, -60 The angle of rotation of the label offset: float, Us...
5.013289
6.144981
0.815835
if not position: position = (0.5, -offset / 2., 0.5) self._labels["bottom"] = (label, position, rotation, kwargs)
def bottom_axis_label(self, label, position=None, rotation=0, offset=0.02, **kwargs)
Sets the label on the bottom axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 0 The angle of rotation of the label offset: float, Use...
4.981016
6.563703
0.758873
if not position: position = (1, offset / 2, 0) self._corner_labels["right"] = (label, position, rotation, kwargs)
def right_corner_label(self, label, position=None, rotation=0, offset=0.08, **kwargs)
Sets the label on the right corner (complements left axis). Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 0 The angle of rotation of the label offse...
5.23683
6.743186
0.776611
if not position: position = (-offset / 2, offset / 2, 0) self._corner_labels["left"] = (label, position, rotation, kwargs)
def left_corner_label(self, label, position=None, rotation=0, offset=0.08, **kwargs)
Sets the label on the left corner (complements right axis.) Parameters ---------- label: string The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 0 The angle of rotation of the label offse...
4.34592
5.552965
0.782631
if not position: position = (-offset / 2, 1 + offset, 0) self._corner_labels["top"] = (label, position, rotation, kwargs)
def top_corner_label(self, label, position=None, rotation=0, offset=0.2, **kwargs)
Sets the label on the bottom axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 0 The angle of rotation of the label offset: float, Use...
4.642789
5.769115
0.804766
ax = self.get_axes() plotting.clear_matplotlib_ticks(ax=ax, axis=axis)
def clear_matplotlib_ticks(self, axis="both")
Clears the default matplotlib ticks.
4.701805
4.075795
1.153592
for k in ['b', 'l', 'r']: self._ticks[k] = numpy.linspace( self._axis_limits[k][0], self._axis_limits[k][1], self._boundary_scale / float(multiple) + 1 ).tolist()
def get_ticks_from_axis_limits(self, multiple=1)
Taking self._axis_limits and self._boundary_scale get the scaled ticks for all three axes and store them in self._ticks under the keys 'b' for bottom, 'l' for left and 'r' for right axes.
4.473866
2.42248
1.846812
for k in ['b', 'l', 'r']: self.ticks(ticks=self._ticks[k], locations=locations, axis=k, clockwise=clockwise, multiple=multiple, axes_colors=axes_colors, tick_formats=tick_formats, **kwargs)
def set_custom_ticks(self, locations=None, clockwise=False, multiple=1, axes_colors=None, tick_formats=None, **kwargs)
Having called get_ticks_from_axis_limits, set the custom ticks on the plot.
3.097377
3.226574
0.959958
ax = self.get_axes() # Remove any previous labels for mpl_object in self._to_remove: mpl_object.remove() self._to_remove = [] # Redraw the labels with the appropriate angles label_data = list(self._labels.values()) label_data.extend(self._corn...
def _redraw_labels(self)
Redraw axis labels, typically after draw or resize events.
3.513057
3.42688
1.025147
return convert_coordinates_sequence(points,self._boundary_scale, self._axis_limits, axisorder)
def convert_coordinates(self, points, axisorder='blr')
Convert data coordinates to simplex coordinates for plotting in the case that axis limits have been applied.
15.999428
16.233688
0.985569
if isinstance(cmap, matplotlib.colors.Colormap): return cmap if isinstance(cmap, str): cmap_name = cmap else: cmap_name = DEFAULT_COLOR_MAP_NAME return plt.get_cmap(cmap_name)
def get_cmap(cmap=None)
Loads a matplotlib colormap if specified or supplies the default. Parameters ---------- cmap: string or matplotlib.colors.Colormap instance The name of the Matplotlib colormap to look up. Returns ------- The desired Matplotlib colormap Raises ------ ValueError if colormap ...
2.632056
3.003437
0.876348
cmap = get_cmap(cmap) if upper - lower == 0: rgba = cmap(0) else: rgba = cmap((value - lower) / float(upper - lower)) hex_ = rgb2hex(rgba) return hex_
def colormapper(value, lower=0, upper=1, cmap=None)
Maps values to colors by normalizing within [a,b], obtaining rgba from the given matplotlib color map for heatmap polygon coloring. Parameters ---------- value: float The value to be colormapped lower: float Lower bound of colors upper: float Upper bound of colors cm...
3.175906
3.466409
0.916195
# http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots norm = plt.Normalize(vmin=vmin, vmax=vmax) sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm._A = [] cb = plt.colorbar(sm, ax=ax, **kwargs) if cbarlabel is not None: cb.set_label(cbarl...
def colorbar_hack(ax, vmin, vmax, cmap, scientific=False, cbarlabel=None, **kwargs)
Colorbar hack to insert colorbar on ternary plot. Called by heatmap, not intended for direct usage. Parameters ---------- vmin: float Minimum value to portray in colorbar vmax: float Maximum value to portray in colorbar cmap: Matplotlib colormap Matplotlib colo...
1.912824
2.093921
0.913513
key_size = len(list(data.keys())[0]) if not keys: keys = triangle_coordinates(i, j, k) # Reduce key from (i, j, k) to (i, j) if necessary keys = [tuple(key[:key_size]) for key in keys] # Sum over the values of the points to blend try: s = sum(data[key] for key in keys) ...
def blend_value(data, i, j, k, keys=None)
Computes the average value of the three vertices of a triangle in the simplex triangulation, where two of the vertices are on the lower horizontal.
4.926064
4.625726
1.064928
keys = alt_triangle_coordinates(i, j, k) return blend_value(data, i, j, k, keys=keys)
def alt_blend_value(data, i, j, k)
Computes the average value of the three vertices of a triangle in the simplex triangulation, where two of the vertices are on the upper horizontal.
6.012591
6.920155
0.868852
return [(i, j, k), (i + 1, j, k - 1), (i, j + 1, k - 1)]
def triangle_coordinates(i, j, k)
Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangules are parallel to the lower axis on the lower side. Parameters ---------- i,j,k: enumeration of the desired triangle Returns ------- A numpy array of coordinates of the hexagon (unprojected...
2.773155
4.531641
0.611954
return [(i, j + 1, k - 1), (i + 1, j, k - 1), (i + 1, j + 1, k - 2)]
def alt_triangle_coordinates(i, j, k)
Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangules are parallel to the lower axis on the upper side. Parameters ---------- i,j,k: enumeration of the desired triangle Returns ------- A numpy array of coordinates of the hexagon (unprojected...
2.75353
3.648213
0.754761
zero = numpy.array([0, 0, 0]) alpha = numpy.array([-1./3, 2./3, 0]) deltaup = numpy.array([1./3, 1./3, 0]) deltadown = numpy.array([2./3, -1./3, 0]) i_vec = numpy.array([0, 1./2, -1./2]) i_vec_down = numpy.array([1./2, -1./2, 0]) deltaX_vec = numpy.array([1./2, 0, -1./2]) d = dict...
def generate_hexagon_deltas()
Generates a dictionary of the necessary additive vectors to generate the hexagon points for the hexagonal heatmap.
2.562848
2.46174
1.041072
signature = "" for x in [i, j, k]: if x == 0: signature += "0" else: signature += "1" deltas = hexagon_deltas[signature] center = numpy.array([i, j, k]) return numpy.array([center + x for x in deltas])
def hexagon_coordinates(i, j, k)
Computes coordinates of the constituent hexagons of a hexagonal heatmap. Parameters ---------- i, j, k: enumeration of the desired hexagon Returns ------- A numpy array of coordinates of the hexagon (unprojected)
3.5945
4.248951
0.845973
# We'll project the coordinates inside this function to prevent # passing around permutation more than necessary project = functools.partial(project_point, permutation=permutation) if isinstance(data, dict): data_gen = data.items() else: # Only works with style == 'h' ...
def polygon_generator(data, scale, style, permutation=None)
Generator for the vertices of the polygon to be colored and its color, depending on style. Called by heatmap.
2.893037
2.857077
1.012586
if not ax: fig, ax = pyplot.subplots() # If use_rgba, make the RGBA values numpy arrays so that they can # be averaged. if use_rgba: for k, v in data.items(): data[k] = numpy.array(v) else: cmap = get_cmap(cmap) if vmin is None: vmin = mi...
def heatmap(data, scale, vmin=None, vmax=None, cmap=None, ax=None, scientific=False, style='triangular', colorbar=True, permutation=None, use_rgba=False, cbarlabel=None, cb_kwargs=None)
Plots heatmap of given color values. Parameters ---------- data: dictionary A dictionary mapping the i, j polygon to the heatmap color, where i + j + k = scale. scale: Integer The scale used to partition the simplex. vmin: float, None The minimum color value, used to...
3.477262
3.288613
1.057364
# Apply the function to a simplex partition data = dict() for i, j, k in simplex_iterator(scale=scale, boundary=boundary): data[(i, j)] = func(normalize([i, j, k])) # Pass everything to the heatmapper ax = heatmap(data, scale, cmap=cmap, ax=ax, style=style, scientific=...
def heatmapf(func, scale=10, boundary=True, cmap=None, ax=None, scientific=False, style='triangular', colorbar=True, permutation=None, vmin=None, vmax=None, cbarlabel=None, cb_kwargs=None)
Computes func on heatmap partition coordinates and plots heatmap. In other words, computes the function on lattice points of the simplex (normalized points) and creates a heatmap from the values. Parameters ---------- func: Function A function of 3-tuples to be heatmapped scale: Integer...
3.456018
3.429278
1.007798
coord_str = [] for c in coordinates: coord_str.append(",".join(map(str, c))) coord_str = " ".join(coord_str) polygon = '<polygon points="%s" style="fill:%s;stroke:%s;stroke-width:0"/>\n' % (coord_str, color, color) return polygon
def svg_polygon(coordinates, color)
Create an svg triangle for the stationary heatmap. Parameters ---------- coordinates: list The coordinates defining the polygon color: string RGB color value e.g. #26ffd1 Returns ------- string, the svg string for the polygon
2.317237
2.380141
0.973571
style = style.lower()[0] if style not in ["t", "h", 'd']: raise ValueError("Heatmap style must be 'triangular', 'dual-triangular', or 'hexagonal'") if not isinstance(data, dict): if not style == 'h': raise ValueError("Data can only be given as a generator for hexagonal sty...
def svg_heatmap(data, scale, filename, vmax=None, vmin=None, style='h', permutation=None, cmap=None)
Create a heatmap in SVG format. Intended for use with very large datasets, which would require large amounts of RAM using matplotlib. You can convert the image to another format with e.g. ImageMagick: convert -density 1200 -resize -rotate 180 1000x1000 your.svg your.png Parameters ---------- ...
3.726393
3.344691
1.114122
pp1 = project_point(p1, permutation=permutation) pp2 = project_point(p2, permutation=permutation) ax.add_line(Line2D((pp1[0], pp2[0]), (pp1[1], pp2[1]), **kwargs))
def line(ax, p1, p2, permutation=None, **kwargs)
Draws a line on `ax` from p1 to p2. Parameters ---------- ax: Matplotlib AxesSubplot, None The subplot to draw on. p1: 2-tuple The (x,y) starting coordinates p2: 2-tuple The (x,y) ending coordinates kwargs: Any kwargs to pass through to Matplotlib.
2.168669
2.361858
0.918205
p1 = (0, i, scale - i) p2 = (scale - i, i, 0) line(ax, p1, p2, **kwargs)
def horizontal_line(ax, scale, i, **kwargs)
Draws the i-th horizontal line parallel to the lower axis. Parameters ---------- ax: Matplotlib AxesSubplot The subplot to draw on. scale: float, 1.0 Simplex scale size. i: float The index of the line to draw kwargs: Dictionary Any kwargs to pass through to Matpl...
3.955693
4.303259
0.919232
p1 = (i, scale - i, 0) p2 = (i, 0, scale - i) line(ax, p1, p2, **kwargs)
def left_parallel_line(ax, scale, i, **kwargs)
Draws the i-th line parallel to the left axis. Parameters ---------- ax: Matplotlib AxesSubplot The subplot to draw on. scale: float Simplex scale size. i: float The index of the line to draw kwargs: Dictionary Any kwargs to pass through to Matplotlib.
3.861351
4.240463
0.910597
p1 = (0, scale - i, i) p2 = (scale - i, 0, i) line(ax, p1, p2, **kwargs)
def right_parallel_line(ax, scale, i, **kwargs)
Draws the i-th line parallel to the right axis. Parameters ---------- ax: Matplotlib AxesSubplot The subplot to draw on. scale: float Simplex scale size. i: float The index of the line to draw kwargs: Dictionary Any kwargs to pass through to Matplotlib.
4.089645
4.33649
0.943077
# Set default color as black. if axes_colors is None: axes_colors = dict() for _axis in ['l', 'r', 'b']: if _axis not in axes_colors.keys(): axes_colors[_axis] = 'black' horizontal_line(ax, scale, 0, color=axes_colors['b'], **kwargs) left_parallel_line(ax, scale, 0...
def boundary(ax, scale, axes_colors=None, **kwargs)
Plots the boundary of the simplex. Creates and returns matplotlib axis if none given. Parameters ---------- ax: Matplotlib AxesSubplot, None The subplot to draw on. scale: float Simplex scale size. kwargs: Any kwargs to pass through to matplotlib. axes_colors: dict ...
2.476812
2.553336
0.97003
if not base: base = dict() if not updates: updates = dict() z = base.copy() z.update(updates) return z
def merge_dicts(base, updates)
Given two dicts, merge them into a new dict as a shallow copy. Parameters ---------- base: dict The base dictionary. updates: dict Secondary dictionary whose values override the base.
2.922514
3.111161
0.939365
if 'linewidth' not in kwargs: kwargs["linewidth"] = 0.5 if 'linestyle' not in kwargs: kwargs["linestyle"] = ':' horizontal_kwargs = merge_dicts(kwargs, horizontal_kwargs) left_kwargs = merge_dicts(kwargs, left_kwargs) right_kwargs = merge_dicts(kwargs, right_kwargs) if not ...
def gridlines(ax, scale, multiple=None, horizontal_kwargs=None, left_kwargs=None, right_kwargs=None, **kwargs)
Plots grid lines excluding boundary. Parameters ---------- ax: Matplotlib AxesSubplot, None The subplot to draw on. scale: float Simplex scale size. multiple: float, None Specifies which inner gridelines to draw. For example, if scale=30 and multiple=6, only 5 inner ...
2.442732
2.378164
1.02715
# Solve the items. item_set = set() for candidate in prev_candidates: for item in candidate: item_set.add(item) items = sorted(item_set) # Create the temporary candidates. These will be filtered below. tmp_next_candidates = (frozenset(x) for x in combinations(items, len...
def create_next_candidates(prev_candidates, length)
Returns the apriori candidates as a list. Arguments: prev_candidates -- Previous candidates as a list. length -- The lengths of the next candidates.
4.070376
4.005435
1.016213
# Parse arguments. max_length = kwargs.get('max_length') # For testing. _create_next_candidates = kwargs.get( '_create_next_candidates', create_next_candidates) # Process. candidates = transaction_manager.initial_candidates() length = 1 while candidates: relations ...
def gen_support_records(transaction_manager, min_support, **kwargs)
Returns a generator of support records with given transactions. Arguments: transaction_manager -- Transactions as a TransactionManager instance. min_support -- A minimum support (float). Keyword arguments: max_length -- The maximum length of relations (integer).
3.317315
3.244557
1.022424
items = record.items for combination_set in combinations(sorted(items), len(items) - 1): items_base = frozenset(combination_set) items_add = frozenset(items.difference(items_base)) confidence = ( record.support / transaction_manager.calc_support(items_base)) lift...
def gen_ordered_statistics(transaction_manager, record)
Returns a generator of ordered statistics as OrderedStatistic instances. Arguments: transaction_manager -- Transactions as a TransactionManager instance. record -- A support record as a SupportRecord instance.
4.171836
4.117819
1.013118
min_confidence = kwargs.get('min_confidence', 0.0) min_lift = kwargs.get('min_lift', 0.0) for ordered_statistic in ordered_statistics: if ordered_statistic.confidence < min_confidence: continue if ordered_statistic.lift < min_lift: continue yield ordered...
def filter_ordered_statistics(ordered_statistics, **kwargs)
Filter OrderedStatistic objects. Arguments: ordered_statistics -- A OrderedStatistic iterable object. Keyword arguments: min_confidence -- The minimum confidence of relations (float). min_lift -- The minimum lift of relations (float).
2.075826
2.113262
0.982285
# Parse the arguments. min_support = kwargs.get('min_support', 0.1) min_confidence = kwargs.get('min_confidence', 0.0) min_lift = kwargs.get('min_lift', 0.0) max_length = kwargs.get('max_length', None) # Check arguments. if min_support <= 0: raise ValueError('minimum support mu...
def apriori(transactions, **kwargs)
Executes Apriori algorithm and returns a RelationRecord generator. Arguments: transactions -- A transaction iterable object (eg. [['A', 'B'], ['B', 'C']]). Keyword arguments: min_support -- The minimum support of relations (float). min_confidence -- The minimum ...
2.261325
2.187632
1.033686
output_funcs = { 'json': dump_as_json, 'tsv': dump_as_two_item_tsv, } default_output_func_key = 'json' parser = argparse.ArgumentParser() parser.add_argument( '-v', '--version', action='version', version='%(prog)s {0}'.format(__version__)) parser.add_argumen...
def parse_args(argv)
Parse commandline arguments. Arguments: argv -- An argument list without the program name.
1.919409
1.947576
0.985537
delimiter = kwargs.get('delimiter', '\t') for transaction in csv.reader(input_file, delimiter=delimiter): yield transaction if transaction else ['']
def load_transactions(input_file, **kwargs)
Load transactions and returns a generator for transactions. Arguments: input_file -- An input file. Keyword arguments: delimiter -- The delimiter of the transaction.
4.53423
6.019134
0.753303
def default_func(value): if isinstance(value, frozenset): return sorted(value) raise TypeError(repr(value) + " is not JSON serializable") converted_record = record._replace( ordered_statistics=[x._asdict() for x in record.ordered_statistics]) json.dump( ...
def dump_as_json(record, output_file)
Dump an relation record as a json value. Arguments: record -- A RelationRecord instance to dump. output_file -- A file to output.
3.720722
3.792789
0.980999
for ordered_stats in record.ordered_statistics: if len(ordered_stats.items_base) != 1: continue if len(ordered_stats.items_add) != 1: continue output_file.write('{0}\t{1}\t{2:.8f}\t{3:.8f}\t{4:.8f}{5}'.format( list(ordered_stats.items_base)[0], list(o...
def dump_as_two_item_tsv(record, output_file)
Dump a relation record as TSV only for 2 item relations. Arguments: record -- A RelationRecord instance to dump. output_file -- A file to output.
2.938244
2.993121
0.981666
# For tests. _parse_args = kwargs.get('_parse_args', parse_args) _load_transactions = kwargs.get('_load_transactions', load_transactions) _apriori = kwargs.get('_apriori', apriori) args = _parse_args(sys.argv[1:]) transactions = _load_transactions( chain(*args.input), delimiter=arg...
def main(**kwargs)
Executes Apriori algorithm and print its result.
3.10535
2.702076
1.149246
for item in transaction: if item not in self.__transaction_index_map: self.__items.append(item) self.__transaction_index_map[item] = set() self.__transaction_index_map[item].add(self.__num_transaction) self.__num_transaction += 1
def add_transaction(self, transaction)
Add a transaction. Arguments: transaction -- A transaction as an iterable object (eg. ['A', 'B']).
2.792526
3.022372
0.923951
# Empty items is supported by all transactions. if not items: return 1.0 # Empty transactions supports no items. if not self.num_transaction: return 0.0 # Create the transaction index intersection. sum_indexes = None for item in ...
def calc_support(self, items)
Returns a support for items. Arguments: items -- Items as an iterable object (eg. ['A', 'B']).
4.498247
4.552814
0.988015
self.context[self.form_context_name] = self.payment_form_cls() return TemplateResponse(self.request, self.payment_template, self.context)
def render_payment_form(self)
Display the DirectPayment for entering payment information.
4.063928
3.806342
1.067673
warn_untested() form = self.payment_form_cls(self.request.POST) if form.is_valid(): success = form.process(self.request, self.item) if success: return HttpResponseRedirect(self.success_url) else: self.context['errors'] ...
def validate_payment_form(self)
Try to validate and then process the DirectPayment form.
3.861161
3.635082
1.062194
wpp = PayPalWPP(self.request) try: nvp_obj = wpp.setExpressCheckout(self.item) except PayPalFailure: warn_untested() self.context['errors'] = self.errors['paypal'] return self.render_payment_form() else: return HttpResp...
def redirect_to_express(self)
First step of ExpressCheckout. Redirect the request to PayPal using the data returned from setExpressCheckout.
10.078469
8.789568
1.14664
warn_untested() initial = dict(token=self.request.GET['token'], PayerID=self.request.GET['PayerID']) self.context[self.form_context_name] = self.confirm_form_cls(initial=initial) return TemplateResponse(self.request, self.confirm_template, self.context)
def render_confirm_form(self)
Second step of ExpressCheckout. Display an order confirmation form which contains hidden fields with the token / PayerID from PayPal.
4.780371
3.925839
1.217668
wpp = PayPalWPP(self.request) pp_data = dict(token=self.request.POST['token'], payerid=self.request.POST['PayerID']) self.item.update(pp_data) # @@@ This check and call could be moved into PayPalWPP. try: if self.is_recurring(): warn_untested...
def validate_confirm_form(self)
Third and final step of ExpressCheckout. Request has pressed the confirmation but and we can send the final confirmation to PayPal using the data from the POST'ed form.
5.675585
5.262178
1.078562
if request is not None: from paypal.pro.helpers import strip_ip_port self.ipaddress = strip_ip_port(request.META.get('REMOTE_ADDR', '')) if (hasattr(request, "user") and request.user.is_authenticated): self.user = request.user else: ...
def init(self, request, paypal_request, paypal_response)
Initialize a PayPalNVP instance from a HttpRequest.
4.396083
4.384484
1.002646
self.flag = True self.flag_info += info if code is not None: self.flag_code = code
def set_flag(self, info, code=None)
Flag this instance for investigation.
4.288593
3.329955
1.287883
warn_untested() from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) # Change the model information into a dict that PayPal can understand. params = model_to_dict(self, exclude=self.ADMIN_FIELDS) params['acct'] = self.acct params['creditcar...
def process(self, request, item)
Do a direct payment.
6.626845
6.158909
1.075977
if not self.query: return None from django.http import QueryDict roughdecode = dict(item.split('=', 1) for item in self.query.split('&')) encoding = roughdecode.get('charset', None) if encoding is None: encoding = DEFAULT_ENCODING query = ...
def posted_data_dict(self)
All the data that PayPal posted to us, as a correctly parsed dictionary of values.
4.388509
4.186848
1.048165
self.response = self._postback().decode('ascii') self.clear_flag() self._verify_postback() if not self.flag: if self.is_transaction(): if self.payment_status not in self.PAYMENT_STATUS_CHOICES: self.set_flag("Invalid payment_status...
def verify(self)
Verifies an IPN and a PDT. Checks for obvious signs of weirdness in the payment and flags appropriately.
5.143481
4.40412
1.167879
warn_untested() if not check_secret(form_instance, secret): self.set_flag("Invalid secret. (%s)") % secret self.save()
def verify_secret(self, form_instance, secret)
Verifies an IPN payment over SSL using EWP.
13.368071
12.934469
1.033523
if request.method == 'GET': # PDT only - this data is currently unused self.query = request.META.get('QUERY_STRING', '') elif request.method == 'POST': # The following works if paypal sends an ASCII bytestring, which it does. self.query = request....
def initialize(self, request)
Store the data we'll need to make the postback from the request object.
6.941413
6.507138
1.066738
from M2Crypto import BIO, SMIME, X509 # Iterate through the fields and pull out the ones that have a value. plaintext = 'cert_id=%s\n' % self.cert_id for name, field in self.fields.items(): value = None if name in self.initial: value = se...
def _encrypt(self)
Use your key thing to encrypt things.
2.558968
2.528347
1.012111
warn_untested() if time_obj is None: time_obj = time.gmtime() return time.strftime(PayPalNVP.TIMESTAMP_FORMAT, time_obj)
def paypal_time(time_obj=None)
Returns a time suitable for PayPal time fields.
5.945
5.128236
1.159268
naive = datetime.datetime.strptime(s, PayPalNVP.TIMESTAMP_FORMAT) if not settings.USE_TZ: return naive else: # TIMESTAMP_FORMAT is UTC return timezone.make_aware(naive, timezone.utc)
def paypaltime2datetime(s)
Convert a PayPal time string to a DateTime.
5.131896
4.92305
1.042422
pp_params = dict(token=token) if commit: pp_params['useraction'] = 'commit' return express_endpoint() % urlencode(pp_params)
def express_endpoint_for_token(token, commit=False)
Returns the PayPal Express Checkout endpoint for a token. Pass 'commit=True' if you will not prompt for confirmation when the user returns to your site.
7.614001
5.921741
1.285771
# IPv4 with or without port if '.' in ip_address: cleaned_ip = ip_address.split(':')[0] # IPv6 with port elif ']:' in ip_address: # Remove the port following last ':', and then strip first and last chars for []. cleaned_ip = ip_address.rpartition(':')[0][1:-1] # IPv6 ...
def strip_ip_port(ip_address)
Strips the port from an IPv4 or IPv6 address, returns a unicode object.
4.585656
4.482904
1.022921
defaults = {"method": "DoDirectPayment", "paymentaction": "Sale"} required = ["creditcardtype", "acct", "expdate", "cvv2", "ipaddress", "firstname", "lastname", ...
def doDirectPayment(self, params)
Call PayPal DoDirectPayment method.
4.059707
3.853988
1.053378
if self._is_recurring(params): params = self._recurring_setExpressCheckout_adapter(params) defaults = {"method": "SetExpressCheckout", "noshipping": 1} required = ["returnurl", "cancelurl", "paymentrequest_0_amt"] nvp_obj = self._fetch(params, required, defaults) ...
def setExpressCheckout(self, params)
Initiates an Express Checkout transaction. Optionally, the SetExpressCheckout API operation can set up billing agreements for reference transactions and recurring payments. Returns a NVP instance - check for token and payerid to continue!
7.326344
6.329762
1.157444
defaults = {"method": "CreateRecurringPaymentsProfile"} required = ["profilestartdate", "billingperiod", "billingfrequency", "amt"] # Direct payments require CC data if direct: required + ["creditcardtype", "acct", "expdate", "firstname", "lastname"] else: ...
def createRecurringPaymentsProfile(self, params, direct=False)
Set direct to True to indicate that this is being called as a directPayment. Returns True PayPal successfully creates the profile otherwise False.
9.388157
8.728981
1.075516
defaults = {"method": "ManageRecurringPaymentsProfileStatus"} required = ["profileid", "action"] nvp_obj = self._fetch(params, required, defaults) # TODO: This fail silently check should be using the error code, but its not easy to access flag_info_test_string = 'Inval...
def manangeRecurringPaymentsProfileStatus(self, params, fail_silently=False)
Requires `profileid` and `action` params. Action must be either "Cancel", "Suspend", or "Reactivate".
9.284051
7.763157
1.195912
params['l_billingtype0'] = "RecurringPayments" params['l_billingagreementdescription0'] = params['desc'] REMOVE = ["billingfrequency", "billingperiod", "profilestartdate", "desc"] for k in params.keys(): if k in REMOVE: del params[k] return ...
def _recurring_setExpressCheckout_adapter(self, params)
The recurring payment interface to SEC is different than the recurring payment interface to ECP. This adapts a normal call to look like a SEC call.
9.644998
9.301783
1.036898
defaults.update(params) pp_params = self._check_and_update_params(required, defaults) pp_string = self.signature + urlencode(pp_params) response = self._request(pp_string) response_params = self._parse_response(response) log.debug('PayPal Request:\n%s\n', pprint...
def _fetch(self, params, required, defaults)
Make the NVP request and store the response.
3.548358
3.380221
1.049741
return requests.post(self.endpoint, data=data.encode("ascii")).content
def _request(self, data)
Moved out to make testing easier.
9.090006
7.339067
1.238578
for r in required: if r not in params: raise PayPalError("Missing required param: %s" % r) # Upper case all the parameters for PayPal. return (dict((k.upper(), v) for k, v in params.items()))
def _check_and_update_params(self, required, params)
Ensure all required parameters were passed to the API call and format them correctly.
4.459238
4.347729
1.025648
q = QueryDict(response, encoding='UTF-8').dict() return {k.lower(): v for k, v in q.items()}
def _parse_response(self, response)
Turn the PayPal response into a dict
6.851712
4.892966
1.400319
return requests.post(self.get_endpoint(), data=dict(cmd="_notify-synch", at=IDENTITY_TOKEN, tx=self.tx)).content
def _postback(self)
Perform PayPal PDT Postback validation. Sends the transaction ID and business token to PayPal which responses with SUCCESS or FAILED.
36.319828
21.130991
1.718794
# get latest similar transaction(s) similars = (ipn_obj.__class__._default_manager .filter(txn_id=ipn_obj.txn_id) .exclude(id=ipn_obj.id) .exclude(flag=True) .order_by('-created_at')[:1]) if len(similars) > 0: # we have a similar...
def duplicate_txn_id(ipn_obj)
Returns True if a record with this transaction id exists and its payment_status has not changed. This function has been completely changed from its previous implementation where it used to specifically only check for a Pending->Completed transition.
3.551808
3.252006
1.09219
warn_untested() # @@@ Moved here as temporary fix to avoid dependancy on auth.models. # @@@ amount is mc_gross on the IPN - where should mapping logic go? # @@@ amount / mc_gross is not nessecarily returned as it was sent - how to use it? 10.00 vs. 10.0 # @@@ the secret should be based on the i...
def make_secret(form_instance, secret_fields=None)
Returns a secret for use in a EWP form or an IPN verification based on a selection of variables in params. Should only be used with SSL.
7.592196
7.126224
1.065388
pdt_obj = None txn_id = request.GET.get('tx') failed = False if txn_id is not None: # If an existing transaction with the id tx exists: use it try: pdt_obj = PayPalPDT.objects.get(txn_id=txn_id) except PayPalPDT.DoesNotExist: # This is a new transact...
def process_pdt(request)
Payment data transfer implementation: https://developer.paypal.com/webapps/developer/docs/classic/products/payment-data-transfer/ This function returns a tuple of (pdt_obj, failed) pdt_obj is an object of type PayPalPDT failed is a flag that is True if the input data didn't pass basic validation. ...
3.823407
3.461971
1.104402
self.number = re.sub(r'[^\d]', '', self.number) return self.number.isdigit()
def is_number(self)
True if there is at least one digit in number.
4.886489
3.15454
1.549034
double = 0 total = 0 for i in range(len(self.number) - 1, -1, -1): for c in str((double + 1) * int(self.number[i])): total = total + int(c) double = (double + 1) % 2 return (total % 10) == 0
def is_mod10(self)
Returns True if number is valid according to mod10.
3.169503
2.973481
1.065923
for card, pattern in CARDS.items(): if pattern.match(self.number): return card return None
def get_type(self)
Return the type if it matches one of the cards.
9.961981
5.695068
1.74923
if self.is_number() and not self.is_test() and self.is_mod10(): return self.get_type() return None
def verify(self)
Returns the card type if valid else None.
8.179981
4.84149
1.689559
if value: value = value.replace('-', '').replace(' ', '') self.card_type = verify_credit_card(value) if self.card_type is None: raise forms.ValidationError("Invalid credit card number.") return value
def clean(self, value)
Raises a ValidationError if the card is not valid and stashes card type.
3.941182
3.154361
1.249439
# TODO: Clean up code so that we don't need to set None here and have a lot # of if checks just to determine if flag is set. flag = None ipn_obj = None # Avoid the RawPostDataException. See original issue for details: # https://github.com/spookylukey/django-paypal/issues/79 if no...
def ipn(request)
PayPal IPN endpoint (notify_url). Used by both PayPal Payments Pro and Payments Standard to confirm transactions. http://tinyurl.com/d9vu9d PayPal IPN Simulator: https://developer.paypal.com/cgi-bin/devscr?cmd=_ipn-link-session
4.400817
4.446222
0.989788
warn_untested() from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) params = self.cleaned_data params['creditcardtype'] = self.fields['acct'].card_type params['expdate'] = self.cleaned_data['expdate'].strftime("%m%Y") params['ipaddress'] = ...
def process(self, request, item)
Process a PayPal direct payment.
6.554373
6.018354
1.089064
return requests.post(self.get_endpoint(), data=b"cmd=_notify-validate&" + self.query.encode("ascii")).content
def _postback(self)
Perform PayPal Postback validation.
16.683668
8.915154
1.871383
if self.flag: invalid_ipn_received.send(sender=self) return else: valid_ipn_received.send(sender=self)
def send_signals(self)
Shout for the world to hear whether a txn was successful.
7.029922
5.833211
1.205155
if isinstance(root, (Delete, BinaryExpression, BooleanClauseList)): for child in root.get_children(): yc = gen_columns_from_children(child) for it in yc: yield it elif isinstance(root, sa.Column): yield root
def gen_columns_from_children(root)
Generates columns that are being used in child elements of the delete query this will be used to determine tables for the using clause. :param root: the delete query :return: a generator of columns
4.727725
4.655375
1.015541
# Set empty strings for the default where clause and using clause whereclause = '' usingclause = '' # determine if the delete query needs a ``USING`` injected # by inspecting the whereclause's children & their children... # first, the where clause text is buit, if applicable # then, t...
def visit_delete_stmt(element, compiler, **kwargs)
Adds redshift-dialect specific compilation rule for the delete statement. Redshift DELETE syntax can be found here: https://docs.aws.amazon.com/redshift/latest/dg/r_DELETE.html .. :code-block: sql DELETE [ FROM ] table_name [ { USING } table_name, ...] [ WHERE condition ] ...
4.394636
4.519215
0.972433
key = str(self) if key.startswith('"') and key.endswith('"'): return key[1:-1] return key
def unquoted(self)
Return *key* with one level of double quotes removed. Redshift stores some identifiers without quotes in internal tables, even though the name must be quoted elsewhere. In particular, this happens for tables named as a keyword.
3.624329
3.285135
1.103251
cols = self._get_redshift_columns(connection, table_name, schema, **kw) if not self._domains: self._domains = self._load_domains(connection) domains = self._domains columns = [] for col in cols: column_info = self._get_column_info( ...
def get_columns(self, connection, table_name, schema=None, **kw)
Return information about columns in `table_name`. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.get_columns`.
3.548943
3.942072
0.900273
constraints = self._get_redshift_constraints(connection, table_name, schema, **kw) pk_constraints = [c for c in constraints if c.contype == 'p'] if not pk_constraints: return {'constrained_columns': [], 'name': ''} ...
def get_pk_constraint(self, connection, table_name, schema=None, **kw)
Return information about the primary key constraint on `table_name`. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.get_pk_constraint`.
2.767156
2.895914
0.955538
constraints = self._get_redshift_constraints(connection, table_name, schema, **kw) fk_constraints = [c for c in constraints if c.contype == 'f'] uniques = defaultdict(lambda: defaultdict(dict)) for con in fk_constraints: ...
def get_foreign_keys(self, connection, table_name, schema=None, **kw)
Return information about foreign keys in `table_name`. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.get_pk_constraint`.
2.54669
2.613147
0.974568
return self._get_table_or_view_names('r', connection, schema, **kw)
def get_table_names(self, connection, schema=None, **kw)
Return a list of table names for `schema`. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.get_table_names`.
6.522583
8.054289
0.809827
return self._get_table_or_view_names('v', connection, schema, **kw)
def get_view_names(self, connection, schema=None, **kw)
Return a list of view names for `schema`. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.get_view_names`.
5.210397
7.111248
0.732698
view = self._get_redshift_relation(connection, view_name, schema, **kw) return sa.text(view.view_definition)
def get_view_definition(self, connection, view_name, schema=None, **kw)
Return view definition. Given a :class:`.Connection`, a string `view_name`, and an optional string `schema`, return the view definition. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.get_view_definition`.
6.797515
9.387239
0.724123
constraints = self._get_redshift_constraints(connection, table_name, schema, **kw) constraints = [c for c in constraints if c.contype == 'u'] uniques = defaultdict(lambda: defaultdict(dict)) for con in constraints: ...
def get_unique_constraints(self, connection, table_name, schema=None, **kw)
Return information about unique constraints in `table_name`. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.get_unique_constraints`.
3.755239
3.926428
0.956401
def keyfunc(column): num = int(column.sortkey) # If sortkey is interleaved, column numbers alternate # negative values, so take abs. return abs(num) table = self._get_redshift_relation(connection, table_name, ...
def get_table_options(self, connection, table_name, schema, **kw)
Return a dictionary of options specified when the table of the given name was created. Overrides interface :meth:`~sqlalchemy.engine.Inspector.get_table_options`.
2.970525
3.059241
0.971001
default_args = { 'sslmode': 'verify-full', 'sslrootcert': pkg_resources.resource_filename( __name__, 'redshift-ca-bundle.crt' ), } cargs, cparams = super(RedshiftDialect, self).create_connect_args( *args, **...
def create_connect_args(self, *args, **kwargs)
Build DB-API compatible connection arguments. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.create_connect_args`.
2.911794
2.748935
1.059245
template = el = element qs = template.format( manifest='MANIFEST' if el.manifest else '', header='HEADER' if el.header else '', delimiter=( 'DELIMITER AS :delimiter' if el.delimiter is not None else '' ), encrypted='ENCRYPTED' if el.encrypted else ...
def visit_unload_from_select(element, compiler, **kw)
Returns the actual sql query for the UnloadFromSelect class.
2.286668
2.181612
1.048155
query = bindparams = [ sa.bindparam( 'location', value=element.location, type_=sa.String, ), sa.bindparam( 'credentials', value=element.credentials, type_=sa.String, ), ] if element.region is n...
def visit_create_library_command(element, compiler, **kw)
Returns the actual sql query for the CreateLibraryCommand class.
3.522597
3.203548
1.099592
try: with open(pacfile) as f: pac_script = f.read() _pacparser.parse_pac_string(pac_script) except IOError: raise IOError('Could not read the pacfile: {}'.format(pacfile))
def parse_pac_file(pacfile)
Reads the pacfile and evaluates it in the Javascript engine created by init().
3.811482
3.639482
1.047259
if host is None: m = _URL_REGEX.match(url) if not m: raise URLError(url) if len(m.groups()) is 1: host = m.groups()[0] else: raise URLError(url) return _pacparser.find_proxy(url, host)
def find_proxy(url, host=None)
Finds proxy string for the given url and host. If host is not defined, it's extracted from the url.
3.595976
3.319255
1.083368
if not os.path.isfile(pacfile): raise IOError('Pac file does not exist: {}'.format(pacfile)) init() parse_pac(pacfile) proxy = find_proxy(url,host) cleanup() return proxy
def just_find_proxy(pacfile, url, host=None)
This function is a wrapper around init, parse_pac, find_proxy and cleanup. This is the function to call if you want to find proxy just for one url.
3.983006
2.881187
1.382418
yes, no = [], [] for d in iterable: if pred(d): yes.append(d) else: no.append(d) return yes, no
def split_data(iterable, pred)
Split data from ``iterable`` into two lists. Each element is passed to function ``pred``; elements for which ``pred`` returns True are put into ``yes`` list, other elements are put into ``no`` list. >>> split_data(["foo", "Bar", "Spam", "egg"], lambda t: t.istitle()) (['Bar', 'Spam'], ['foo', 'egg'...
2.134564
3.081086
0.692796