repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ymoch/apyori | apyori.py | filter_ordered_statistics | 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).
"""
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_statistic | python | 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).
"""
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_statistic | [
"def",
"filter_ordered_statistics",
"(",
"ordered_statistics",
",",
"*",
"*",
"kwargs",
")",
":",
"min_confidence",
"=",
"kwargs",
".",
"get",
"(",
"'min_confidence'",
",",
"0.0",
")",
"min_lift",
"=",
"kwargs",
".",
"get",
"(",
"'min_lift'",
",",
"0.0",
")"... | 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). | [
"Filter",
"OrderedStatistic",
"objects",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L225-L244 | train | 200,100 |
ymoch/apyori | apyori.py | apriori | 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 confidence of relations (float).
min_lift -- The minimum lift of relations (float).
max_length -- The maximum length of the relation (integer).
"""
# 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 must be > 0')
# For testing.
_gen_support_records = kwargs.get(
'_gen_support_records', gen_support_records)
_gen_ordered_statistics = kwargs.get(
'_gen_ordered_statistics', gen_ordered_statistics)
_filter_ordered_statistics = kwargs.get(
'_filter_ordered_statistics', filter_ordered_statistics)
# Calculate supports.
transaction_manager = TransactionManager.create(transactions)
support_records = _gen_support_records(
transaction_manager, min_support, max_length=max_length)
# Calculate ordered stats.
for support_record in support_records:
ordered_statistics = list(
_filter_ordered_statistics(
_gen_ordered_statistics(transaction_manager, support_record),
min_confidence=min_confidence,
min_lift=min_lift,
)
)
if not ordered_statistics:
continue
yield RelationRecord(
support_record.items, support_record.support, ordered_statistics) | python | 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 confidence of relations (float).
min_lift -- The minimum lift of relations (float).
max_length -- The maximum length of the relation (integer).
"""
# 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 must be > 0')
# For testing.
_gen_support_records = kwargs.get(
'_gen_support_records', gen_support_records)
_gen_ordered_statistics = kwargs.get(
'_gen_ordered_statistics', gen_ordered_statistics)
_filter_ordered_statistics = kwargs.get(
'_filter_ordered_statistics', filter_ordered_statistics)
# Calculate supports.
transaction_manager = TransactionManager.create(transactions)
support_records = _gen_support_records(
transaction_manager, min_support, max_length=max_length)
# Calculate ordered stats.
for support_record in support_records:
ordered_statistics = list(
_filter_ordered_statistics(
_gen_ordered_statistics(transaction_manager, support_record),
min_confidence=min_confidence,
min_lift=min_lift,
)
)
if not ordered_statistics:
continue
yield RelationRecord(
support_record.items, support_record.support, ordered_statistics) | [
"def",
"apriori",
"(",
"transactions",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse the arguments.",
"min_support",
"=",
"kwargs",
".",
"get",
"(",
"'min_support'",
",",
"0.1",
")",
"min_confidence",
"=",
"kwargs",
".",
"get",
"(",
"'min_confidence'",
",",
"0... | 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 confidence of relations (float).
min_lift -- The minimum lift of relations (float).
max_length -- The maximum length of the relation (integer). | [
"Executes",
"Apriori",
"algorithm",
"and",
"returns",
"a",
"RelationRecord",
"generator",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L250-L299 | train | 200,101 |
ymoch/apyori | apyori.py | load_transactions | 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.
"""
delimiter = kwargs.get('delimiter', '\t')
for transaction in csv.reader(input_file, delimiter=delimiter):
yield transaction if transaction else [''] | python | 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.
"""
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",
")",
":",
"delimiter",
"=",
"kwargs",
".",
"get",
"(",
"'delimiter'",
",",
"'\\t'",
")",
"for",
"transaction",
"in",
"csv",
".",
"reader",
"(",
"input_file",
",",
"delimiter",
"=",
"... | Load transactions and returns a generator for transactions.
Arguments:
input_file -- An input file.
Keyword arguments:
delimiter -- The delimiter of the transaction. | [
"Load",
"transactions",
"and",
"returns",
"a",
"generator",
"for",
"transactions",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L361-L373 | train | 200,102 |
ymoch/apyori | apyori.py | dump_as_json | 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.
"""
def default_func(value):
"""
Default conversion for JSON 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(
converted_record._asdict(), output_file,
default=default_func, ensure_ascii=False)
output_file.write(os.linesep) | python | 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.
"""
def default_func(value):
"""
Default conversion for JSON 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(
converted_record._asdict(), output_file,
default=default_func, ensure_ascii=False)
output_file.write(os.linesep) | [
"def",
"dump_as_json",
"(",
"record",
",",
"output_file",
")",
":",
"def",
"default_func",
"(",
"value",
")",
":",
"\"\"\"\n Default conversion for JSON value.\n \"\"\"",
"if",
"isinstance",
"(",
"value",
",",
"frozenset",
")",
":",
"return",
"sorted",
... | Dump an relation record as a json value.
Arguments:
record -- A RelationRecord instance to dump.
output_file -- A file to output. | [
"Dump",
"an",
"relation",
"record",
"as",
"a",
"json",
"value",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L376-L397 | train | 200,103 |
ymoch/apyori | apyori.py | dump_as_two_item_tsv | 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.
"""
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(ordered_stats.items_add)[0],
record.support, ordered_stats.confidence, ordered_stats.lift,
os.linesep)) | python | 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.
"""
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(ordered_stats.items_add)[0],
record.support, ordered_stats.confidence, ordered_stats.lift,
os.linesep)) | [
"def",
"dump_as_two_item_tsv",
"(",
"record",
",",
"output_file",
")",
":",
"for",
"ordered_stats",
"in",
"record",
".",
"ordered_statistics",
":",
"if",
"len",
"(",
"ordered_stats",
".",
"items_base",
")",
"!=",
"1",
":",
"continue",
"if",
"len",
"(",
"orde... | Dump a relation record as TSV only for 2 item relations.
Arguments:
record -- A RelationRecord instance to dump.
output_file -- A file to output. | [
"Dump",
"a",
"relation",
"record",
"as",
"TSV",
"only",
"for",
"2",
"item",
"relations",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L400-L416 | train | 200,104 |
ymoch/apyori | apyori.py | main | def main(**kwargs):
"""
Executes Apriori algorithm and print its result.
"""
# 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=args.delimiter)
result = _apriori(
transactions,
max_length=args.max_length,
min_support=args.min_support,
min_confidence=args.min_confidence)
for record in result:
args.output_func(record, args.output) | python | def main(**kwargs):
"""
Executes Apriori algorithm and print its result.
"""
# 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=args.delimiter)
result = _apriori(
transactions,
max_length=args.max_length,
min_support=args.min_support,
min_confidence=args.min_confidence)
for record in result:
args.output_func(record, args.output) | [
"def",
"main",
"(",
"*",
"*",
"kwargs",
")",
":",
"# For tests.",
"_parse_args",
"=",
"kwargs",
".",
"get",
"(",
"'_parse_args'",
",",
"parse_args",
")",
"_load_transactions",
"=",
"kwargs",
".",
"get",
"(",
"'_load_transactions'",
",",
"load_transactions",
")... | Executes Apriori algorithm and print its result. | [
"Executes",
"Apriori",
"algorithm",
"and",
"print",
"its",
"result",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L419-L437 | train | 200,105 |
ymoch/apyori | apyori.py | TransactionManager.add_transaction | def add_transaction(self, transaction):
"""
Add a transaction.
Arguments:
transaction -- A transaction as an iterable object (eg. ['A', 'B']).
"""
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 | python | def add_transaction(self, transaction):
"""
Add a transaction.
Arguments:
transaction -- A transaction as an iterable object (eg. ['A', 'B']).
"""
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",
")",
":",
"for",
"item",
"in",
"transaction",
":",
"if",
"item",
"not",
"in",
"self",
".",
"__transaction_index_map",
":",
"self",
".",
"__items",
".",
"append",
"(",
"item",
")",
"self",
".",
"_... | Add a transaction.
Arguments:
transaction -- A transaction as an iterable object (eg. ['A', 'B']). | [
"Add",
"a",
"transaction",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L46-L58 | train | 200,106 |
ymoch/apyori | apyori.py | TransactionManager.calc_support | def calc_support(self, items):
"""
Returns a support for items.
Arguments:
items -- Items as an iterable object (eg. ['A', 'B']).
"""
# 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 items:
indexes = self.__transaction_index_map.get(item)
if indexes is None:
# No support for any set that contains a not existing item.
return 0.0
if sum_indexes is None:
# Assign the indexes on the first time.
sum_indexes = indexes
else:
# Calculate the intersection on not the first time.
sum_indexes = sum_indexes.intersection(indexes)
# Calculate and return the support.
return float(len(sum_indexes)) / self.__num_transaction | python | def calc_support(self, items):
"""
Returns a support for items.
Arguments:
items -- Items as an iterable object (eg. ['A', 'B']).
"""
# 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 items:
indexes = self.__transaction_index_map.get(item)
if indexes is None:
# No support for any set that contains a not existing item.
return 0.0
if sum_indexes is None:
# Assign the indexes on the first time.
sum_indexes = indexes
else:
# Calculate the intersection on not the first time.
sum_indexes = sum_indexes.intersection(indexes)
# Calculate and return the support.
return float(len(sum_indexes)) / self.__num_transaction | [
"def",
"calc_support",
"(",
"self",
",",
"items",
")",
":",
"# 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",
"# ... | Returns a support for items.
Arguments:
items -- Items as an iterable object (eg. ['A', 'B']). | [
"Returns",
"a",
"support",
"for",
"items",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L60-L91 | train | 200,107 |
spookylukey/django-paypal | paypal/pro/views.py | PayPalPro.render_payment_form | def render_payment_form(self):
"""Display the DirectPayment for entering payment information."""
self.context[self.form_context_name] = self.payment_form_cls()
return TemplateResponse(self.request, self.payment_template, self.context) | python | def render_payment_form(self):
"""Display the DirectPayment for entering payment information."""
self.context[self.form_context_name] = self.payment_form_cls()
return TemplateResponse(self.request, self.payment_template, self.context) | [
"def",
"render_payment_form",
"(",
"self",
")",
":",
"self",
".",
"context",
"[",
"self",
".",
"form_context_name",
"]",
"=",
"self",
".",
"payment_form_cls",
"(",
")",
"return",
"TemplateResponse",
"(",
"self",
".",
"request",
",",
"self",
".",
"payment_tem... | Display the DirectPayment for entering payment information. | [
"Display",
"the",
"DirectPayment",
"for",
"entering",
"payment",
"information",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/views.py#L126-L129 | train | 200,108 |
spookylukey/django-paypal | paypal/pro/views.py | PayPalPro.validate_payment_form | def validate_payment_form(self):
"""Try to validate and then process the DirectPayment form."""
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'] = self.errors['processing']
self.context[self.form_context_name] = form
self.context.setdefault("errors", self.errors['form'])
return TemplateResponse(self.request, self.payment_template, self.context) | python | def validate_payment_form(self):
"""Try to validate and then process the DirectPayment form."""
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'] = self.errors['processing']
self.context[self.form_context_name] = form
self.context.setdefault("errors", self.errors['form'])
return TemplateResponse(self.request, self.payment_template, self.context) | [
"def",
"validate_payment_form",
"(",
"self",
")",
":",
"warn_untested",
"(",
")",
"form",
"=",
"self",
".",
"payment_form_cls",
"(",
"self",
".",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"success",
"=",
"form",
".",
"p... | Try to validate and then process the DirectPayment form. | [
"Try",
"to",
"validate",
"and",
"then",
"process",
"the",
"DirectPayment",
"form",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/views.py#L131-L144 | train | 200,109 |
spookylukey/django-paypal | paypal/pro/views.py | PayPalPro.redirect_to_express | def redirect_to_express(self):
"""
First step of ExpressCheckout. Redirect the request to PayPal using the
data returned from setExpressCheckout.
"""
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 HttpResponseRedirect(express_endpoint_for_token(nvp_obj.token)) | python | def redirect_to_express(self):
"""
First step of ExpressCheckout. Redirect the request to PayPal using the
data returned from setExpressCheckout.
"""
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 HttpResponseRedirect(express_endpoint_for_token(nvp_obj.token)) | [
"def",
"redirect_to_express",
"(",
"self",
")",
":",
"wpp",
"=",
"PayPalWPP",
"(",
"self",
".",
"request",
")",
"try",
":",
"nvp_obj",
"=",
"wpp",
".",
"setExpressCheckout",
"(",
"self",
".",
"item",
")",
"except",
"PayPalFailure",
":",
"warn_untested",
"(... | First step of ExpressCheckout. Redirect the request to PayPal using the
data returned from setExpressCheckout. | [
"First",
"step",
"of",
"ExpressCheckout",
".",
"Redirect",
"the",
"request",
"to",
"PayPal",
"using",
"the",
"data",
"returned",
"from",
"setExpressCheckout",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/views.py#L146-L159 | train | 200,110 |
spookylukey/django-paypal | paypal/pro/views.py | PayPalPro.validate_confirm_form | 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.
"""
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()
nvp = wpp.createRecurringPaymentsProfile(self.item)
else:
nvp = wpp.doExpressCheckoutPayment(self.item)
self.handle_nvp(nvp)
except PayPalFailure:
self.context['errors'] = self.errors['processing']
return self.render_payment_form()
else:
return HttpResponseRedirect(self.success_url) | python | 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.
"""
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()
nvp = wpp.createRecurringPaymentsProfile(self.item)
else:
nvp = wpp.doExpressCheckoutPayment(self.item)
self.handle_nvp(nvp)
except PayPalFailure:
self.context['errors'] = self.errors['processing']
return self.render_payment_form()
else:
return HttpResponseRedirect(self.success_url) | [
"def",
"validate_confirm_form",
"(",
"self",
")",
":",
"wpp",
"=",
"PayPalWPP",
"(",
"self",
".",
"request",
")",
"pp_data",
"=",
"dict",
"(",
"token",
"=",
"self",
".",
"request",
".",
"POST",
"[",
"'token'",
"]",
",",
"payerid",
"=",
"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. | [
"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",... | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/views.py#L171-L192 | train | 200,111 |
spookylukey/django-paypal | paypal/pro/models.py | PayPalNVP.init | def init(self, request, paypal_request, paypal_response):
"""Initialize a PayPalNVP instance from a HttpRequest."""
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:
self.ipaddress = ''
# No storing credit card info.
query_data = dict((k, v) for k, v in paypal_request.items() if k not in self.RESTRICTED_FIELDS)
self.query = urlencode(query_data)
self.response = urlencode(paypal_response)
# Was there a flag on the play?
ack = paypal_response.get('ack', False)
if ack != "Success":
if ack == "SuccessWithWarning":
warn_untested()
self.flag_info = paypal_response.get('l_longmessage0', '')
else:
self.set_flag(paypal_response.get('l_longmessage0', ''), paypal_response.get('l_errorcode', '')) | python | def init(self, request, paypal_request, paypal_response):
"""Initialize a PayPalNVP instance from a HttpRequest."""
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:
self.ipaddress = ''
# No storing credit card info.
query_data = dict((k, v) for k, v in paypal_request.items() if k not in self.RESTRICTED_FIELDS)
self.query = urlencode(query_data)
self.response = urlencode(paypal_response)
# Was there a flag on the play?
ack = paypal_response.get('ack', False)
if ack != "Success":
if ack == "SuccessWithWarning":
warn_untested()
self.flag_info = paypal_response.get('l_longmessage0', '')
else:
self.set_flag(paypal_response.get('l_longmessage0', ''), paypal_response.get('l_errorcode', '')) | [
"def",
"init",
"(",
"self",
",",
"request",
",",
"paypal_request",
",",
"paypal_response",
")",
":",
"if",
"request",
"is",
"not",
"None",
":",
"from",
"paypal",
".",
"pro",
".",
"helpers",
"import",
"strip_ip_port",
"self",
".",
"ipaddress",
"=",
"strip_i... | Initialize a PayPalNVP instance from a HttpRequest. | [
"Initialize",
"a",
"PayPalNVP",
"instance",
"from",
"a",
"HttpRequest",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/models.py#L99-L121 | train | 200,112 |
spookylukey/django-paypal | paypal/pro/models.py | PayPalNVP.set_flag | def set_flag(self, info, code=None):
"""Flag this instance for investigation."""
self.flag = True
self.flag_info += info
if code is not None:
self.flag_code = code | python | def set_flag(self, info, code=None):
"""Flag this instance for investigation."""
self.flag = True
self.flag_info += info
if code is not None:
self.flag_code = code | [
"def",
"set_flag",
"(",
"self",
",",
"info",
",",
"code",
"=",
"None",
")",
":",
"self",
".",
"flag",
"=",
"True",
"self",
".",
"flag_info",
"+=",
"info",
"if",
"code",
"is",
"not",
"None",
":",
"self",
".",
"flag_code",
"=",
"code"
] | Flag this instance for investigation. | [
"Flag",
"this",
"instance",
"for",
"investigation",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/models.py#L123-L128 | train | 200,113 |
spookylukey/django-paypal | paypal/pro/models.py | PayPalNVP.process | def process(self, request, item):
"""Do a direct payment."""
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['creditcardtype'] = self.creditcardtype
params['expdate'] = self.expdate
params['cvv2'] = self.cvv2
params.update(item)
# Create recurring payment:
if 'billingperiod' in params:
return wpp.createRecurringPaymentsProfile(params, direct=True)
# Create single payment:
else:
return wpp.doDirectPayment(params) | python | def process(self, request, item):
"""Do a direct payment."""
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['creditcardtype'] = self.creditcardtype
params['expdate'] = self.expdate
params['cvv2'] = self.cvv2
params.update(item)
# Create recurring payment:
if 'billingperiod' in params:
return wpp.createRecurringPaymentsProfile(params, direct=True)
# Create single payment:
else:
return wpp.doDirectPayment(params) | [
"def",
"process",
"(",
"self",
",",
"request",
",",
"item",
")",
":",
"warn_untested",
"(",
")",
"from",
"paypal",
".",
"pro",
".",
"helpers",
"import",
"PayPalWPP",
"wpp",
"=",
"PayPalWPP",
"(",
"request",
")",
"# Change the model information into a dict that P... | Do a direct payment. | [
"Do",
"a",
"direct",
"payment",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/models.py#L130-L150 | train | 200,114 |
spookylukey/django-paypal | paypal/standard/models.py | PayPalStandardBase.posted_data_dict | def posted_data_dict(self):
"""
All the data that PayPal posted to us, as a correctly parsed dictionary of values.
"""
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 = self.query.encode('ascii')
data = QueryDict(query, encoding=encoding)
return data.dict() | python | def posted_data_dict(self):
"""
All the data that PayPal posted to us, as a correctly parsed dictionary of values.
"""
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 = self.query.encode('ascii')
data = QueryDict(query, encoding=encoding)
return data.dict() | [
"def",
"posted_data_dict",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"query",
":",
"return",
"None",
"from",
"django",
".",
"http",
"import",
"QueryDict",
"roughdecode",
"=",
"dict",
"(",
"item",
".",
"split",
"(",
"'='",
",",
"1",
")",
"for",
... | All the data that PayPal posted to us, as a correctly parsed dictionary of values. | [
"All",
"the",
"data",
"that",
"PayPal",
"posted",
"to",
"us",
"as",
"a",
"correctly",
"parsed",
"dictionary",
"of",
"values",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/models.py#L247-L260 | train | 200,115 |
spookylukey/django-paypal | paypal/standard/models.py | PayPalStandardBase.verify | def verify(self):
"""
Verifies an IPN and a PDT.
Checks for obvious signs of weirdness in the payment and flags appropriately.
"""
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. (%s)" % self.payment_status)
if duplicate_txn_id(self):
self.set_flag("Duplicate txn_id. (%s)" % self.txn_id)
self.save() | python | def verify(self):
"""
Verifies an IPN and a PDT.
Checks for obvious signs of weirdness in the payment and flags appropriately.
"""
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. (%s)" % self.payment_status)
if duplicate_txn_id(self):
self.set_flag("Duplicate txn_id. (%s)" % self.txn_id)
self.save() | [
"def",
"verify",
"(",
"self",
")",
":",
"self",
".",
"response",
"=",
"self",
".",
"_postback",
"(",
")",
".",
"decode",
"(",
"'ascii'",
")",
"self",
".",
"clear_flag",
"(",
")",
"self",
".",
"_verify_postback",
"(",
")",
"if",
"not",
"self",
".",
... | Verifies an IPN and a PDT.
Checks for obvious signs of weirdness in the payment and flags appropriately. | [
"Verifies",
"an",
"IPN",
"and",
"a",
"PDT",
".",
"Checks",
"for",
"obvious",
"signs",
"of",
"weirdness",
"in",
"the",
"payment",
"and",
"flags",
"appropriately",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/models.py#L350-L365 | train | 200,116 |
spookylukey/django-paypal | paypal/standard/models.py | PayPalStandardBase.verify_secret | def verify_secret(self, form_instance, secret):
"""Verifies an IPN payment over SSL using EWP."""
warn_untested()
if not check_secret(form_instance, secret):
self.set_flag("Invalid secret. (%s)") % secret
self.save() | python | def verify_secret(self, form_instance, secret):
"""Verifies an IPN payment over SSL using EWP."""
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",
")",
":",
"warn_untested",
"(",
")",
"if",
"not",
"check_secret",
"(",
"form_instance",
",",
"secret",
")",
":",
"self",
".",
"set_flag",
"(",
"\"Invalid secret. (%s)\"",
")",
"%",
"se... | Verifies an IPN payment over SSL using EWP. | [
"Verifies",
"an",
"IPN",
"payment",
"over",
"SSL",
"using",
"EWP",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/models.py#L367-L372 | train | 200,117 |
spookylukey/django-paypal | paypal/standard/models.py | PayPalStandardBase.initialize | def initialize(self, request):
"""Store the data we'll need to make the postback from the request object."""
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.body.decode('ascii')
self.ipaddress = request.META.get('REMOTE_ADDR', '') | python | def initialize(self, request):
"""Store the data we'll need to make the postback from the request object."""
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.body.decode('ascii')
self.ipaddress = request.META.get('REMOTE_ADDR', '') | [
"def",
"initialize",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"# PDT only - this data is currently unused",
"self",
".",
"query",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'QUERY_STRING'",
",",
"''",
")"... | Store the data we'll need to make the postback from the request object. | [
"Store",
"the",
"data",
"we",
"ll",
"need",
"to",
"make",
"the",
"postback",
"from",
"the",
"request",
"object",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/models.py#L385-L393 | train | 200,118 |
spookylukey/django-paypal | paypal/standard/forms.py | PayPalEncryptedPaymentsForm._encrypt | def _encrypt(self):
"""Use your key thing to encrypt things."""
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 = self.initial[name]
elif field.initial is not None:
value = field.initial
if value is not None:
plaintext += u'%s=%s\n' % (name, value)
plaintext = plaintext.encode('utf-8')
# Begin crypto weirdness.
s = SMIME.SMIME()
s.load_key_bio(BIO.openfile(self.private_cert), BIO.openfile(self.public_cert))
p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
x509 = X509.load_cert_bio(BIO.openfile(self.paypal_cert))
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)
s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
tmp = BIO.MemoryBuffer()
p7.write_der(tmp)
p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
out = BIO.MemoryBuffer()
p7.write(out)
return out.read().decode() | python | def _encrypt(self):
"""Use your key thing to encrypt things."""
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 = self.initial[name]
elif field.initial is not None:
value = field.initial
if value is not None:
plaintext += u'%s=%s\n' % (name, value)
plaintext = plaintext.encode('utf-8')
# Begin crypto weirdness.
s = SMIME.SMIME()
s.load_key_bio(BIO.openfile(self.private_cert), BIO.openfile(self.public_cert))
p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
x509 = X509.load_cert_bio(BIO.openfile(self.paypal_cert))
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)
s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
tmp = BIO.MemoryBuffer()
p7.write_der(tmp)
p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
out = BIO.MemoryBuffer()
p7.write(out)
return out.read().decode() | [
"def",
"_encrypt",
"(",
"self",
")",
":",
"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",
",",
"... | Use your key thing to encrypt things. | [
"Use",
"your",
"key",
"thing",
"to",
"encrypt",
"things",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/forms.py#L197-L227 | train | 200,119 |
spookylukey/django-paypal | paypal/pro/helpers.py | paypal_time | def paypal_time(time_obj=None):
"""Returns a time suitable for PayPal time fields."""
warn_untested()
if time_obj is None:
time_obj = time.gmtime()
return time.strftime(PayPalNVP.TIMESTAMP_FORMAT, time_obj) | python | def paypal_time(time_obj=None):
"""Returns a time suitable for PayPal time fields."""
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",
")",
":",
"warn_untested",
"(",
")",
"if",
"time_obj",
"is",
"None",
":",
"time_obj",
"=",
"time",
".",
"gmtime",
"(",
")",
"return",
"time",
".",
"strftime",
"(",
"PayPalNVP",
".",
"TIMESTAMP_FORMAT",
... | Returns a time suitable for PayPal time fields. | [
"Returns",
"a",
"time",
"suitable",
"for",
"PayPal",
"time",
"fields",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L37-L42 | train | 200,120 |
spookylukey/django-paypal | paypal/pro/helpers.py | paypaltime2datetime | def paypaltime2datetime(s):
"""Convert a PayPal time string to a DateTime."""
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) | python | def paypaltime2datetime(s):
"""Convert a PayPal time string to a DateTime."""
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",
")",
":",
"naive",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"s",
",",
"PayPalNVP",
".",
"TIMESTAMP_FORMAT",
")",
"if",
"not",
"settings",
".",
"USE_TZ",
":",
"return",
"naive",
"else",
":",
"# TIMESTAM... | Convert a PayPal time string to a DateTime. | [
"Convert",
"a",
"PayPal",
"time",
"string",
"to",
"a",
"DateTime",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L45-L52 | train | 200,121 |
spookylukey/django-paypal | paypal/pro/helpers.py | express_endpoint_for_token | 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.
"""
pp_params = dict(token=token)
if commit:
pp_params['useraction'] = 'commit'
return express_endpoint() % urlencode(pp_params) | python | 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.
"""
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",
")",
":",
"pp_params",
"=",
"dict",
"(",
"token",
"=",
"token",
")",
"if",
"commit",
":",
"pp_params",
"[",
"'useraction'",
"]",
"=",
"'commit'",
"return",
"express_endpoint",
"(... | 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. | [
"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",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L66-L75 | train | 200,122 |
spookylukey/django-paypal | paypal/pro/helpers.py | strip_ip_port | def strip_ip_port(ip_address):
"""
Strips the port from an IPv4 or IPv6 address, returns a unicode object.
"""
# 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 without port
else:
cleaned_ip = ip_address
return cleaned_ip | python | def strip_ip_port(ip_address):
"""
Strips the port from an IPv4 or IPv6 address, returns a unicode object.
"""
# 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 without port
else:
cleaned_ip = ip_address
return cleaned_ip | [
"def",
"strip_ip_port",
"(",
"ip_address",
")",
":",
"# IPv4 with or without port",
"if",
"'.'",
"in",
"ip_address",
":",
"cleaned_ip",
"=",
"ip_address",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"# IPv6 with port",
"elif",
"']:'",
"in",
"ip_address",
":"... | Strips the port from an IPv4 or IPv6 address, returns a unicode object. | [
"Strips",
"the",
"port",
"from",
"an",
"IPv4",
"or",
"IPv6",
"address",
"returns",
"a",
"unicode",
"object",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L78-L96 | train | 200,123 |
spookylukey/django-paypal | paypal/pro/helpers.py | PayPalWPP.doDirectPayment | def doDirectPayment(self, params):
"""Call PayPal DoDirectPayment method."""
defaults = {"method": "DoDirectPayment", "paymentaction": "Sale"}
required = ["creditcardtype",
"acct",
"expdate",
"cvv2",
"ipaddress",
"firstname",
"lastname",
"street",
"city",
"state",
"countrycode",
"zip",
"amt",
]
nvp_obj = self._fetch(params, required, defaults)
if nvp_obj.flag:
raise PayPalFailure(nvp_obj.flag_info, nvp=nvp_obj)
# @@@ Could check cvv2match / avscode are both 'X' or '0'
# qd = django.http.QueryDict(nvp_obj.response)
# if qd.get('cvv2match') not in ['X', '0']:
# nvp_obj.set_flag("Invalid cvv2match: %s" % qd.get('cvv2match')
# if qd.get('avscode') not in ['X', '0']:
# nvp_obj.set_flag("Invalid avscode: %s" % qd.get('avscode')
return nvp_obj | python | def doDirectPayment(self, params):
"""Call PayPal DoDirectPayment method."""
defaults = {"method": "DoDirectPayment", "paymentaction": "Sale"}
required = ["creditcardtype",
"acct",
"expdate",
"cvv2",
"ipaddress",
"firstname",
"lastname",
"street",
"city",
"state",
"countrycode",
"zip",
"amt",
]
nvp_obj = self._fetch(params, required, defaults)
if nvp_obj.flag:
raise PayPalFailure(nvp_obj.flag_info, nvp=nvp_obj)
# @@@ Could check cvv2match / avscode are both 'X' or '0'
# qd = django.http.QueryDict(nvp_obj.response)
# if qd.get('cvv2match') not in ['X', '0']:
# nvp_obj.set_flag("Invalid cvv2match: %s" % qd.get('cvv2match')
# if qd.get('avscode') not in ['X', '0']:
# nvp_obj.set_flag("Invalid avscode: %s" % qd.get('avscode')
return nvp_obj | [
"def",
"doDirectPayment",
"(",
"self",
",",
"params",
")",
":",
"defaults",
"=",
"{",
"\"method\"",
":",
"\"DoDirectPayment\"",
",",
"\"paymentaction\"",
":",
"\"Sale\"",
"}",
"required",
"=",
"[",
"\"creditcardtype\"",
",",
"\"acct\"",
",",
"\"expdate\"",
",",
... | Call PayPal DoDirectPayment method. | [
"Call",
"PayPal",
"DoDirectPayment",
"method",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L126-L152 | train | 200,124 |
spookylukey/django-paypal | paypal/pro/helpers.py | PayPalWPP.setExpressCheckout | 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!
"""
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)
if nvp_obj.flag:
raise PayPalFailure(nvp_obj.flag_info, nvp=nvp_obj)
return nvp_obj | python | 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!
"""
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)
if nvp_obj.flag:
raise PayPalFailure(nvp_obj.flag_info, nvp=nvp_obj)
return nvp_obj | [
"def",
"setExpressCheckout",
"(",
"self",
",",
"params",
")",
":",
"if",
"self",
".",
"_is_recurring",
"(",
"params",
")",
":",
"params",
"=",
"self",
".",
"_recurring_setExpressCheckout_adapter",
"(",
"params",
")",
"defaults",
"=",
"{",
"\"method\"",
":",
... | 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! | [
"Initiates",
"an",
"Express",
"Checkout",
"transaction",
".",
"Optionally",
"the",
"SetExpressCheckout",
"API",
"operation",
"can",
"set",
"up",
"billing",
"agreements",
"for",
"reference",
"transactions",
"and",
"recurring",
"payments",
".",
"Returns",
"a",
"NVP",
... | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L154-L169 | train | 200,125 |
spookylukey/django-paypal | paypal/pro/helpers.py | PayPalWPP.createRecurringPaymentsProfile | 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.
"""
defaults = {"method": "CreateRecurringPaymentsProfile"}
required = ["profilestartdate", "billingperiod", "billingfrequency", "amt"]
# Direct payments require CC data
if direct:
required + ["creditcardtype", "acct", "expdate", "firstname", "lastname"]
else:
required + ["token", "payerid"]
nvp_obj = self._fetch(params, required, defaults)
# Flag if profile_type != ActiveProfile
if nvp_obj.flag:
raise PayPalFailure(nvp_obj.flag_info, nvp=nvp_obj)
return nvp_obj | python | 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.
"""
defaults = {"method": "CreateRecurringPaymentsProfile"}
required = ["profilestartdate", "billingperiod", "billingfrequency", "amt"]
# Direct payments require CC data
if direct:
required + ["creditcardtype", "acct", "expdate", "firstname", "lastname"]
else:
required + ["token", "payerid"]
nvp_obj = self._fetch(params, required, defaults)
# Flag if profile_type != ActiveProfile
if nvp_obj.flag:
raise PayPalFailure(nvp_obj.flag_info, nvp=nvp_obj)
return nvp_obj | [
"def",
"createRecurringPaymentsProfile",
"(",
"self",
",",
"params",
",",
"direct",
"=",
"False",
")",
":",
"defaults",
"=",
"{",
"\"method\"",
":",
"\"CreateRecurringPaymentsProfile\"",
"}",
"required",
"=",
"[",
"\"profilestartdate\"",
",",
"\"billingperiod\"",
",... | Set direct to True to indicate that this is being called as a directPayment.
Returns True PayPal successfully creates the profile otherwise False. | [
"Set",
"direct",
"to",
"True",
"to",
"indicate",
"that",
"this",
"is",
"being",
"called",
"as",
"a",
"directPayment",
".",
"Returns",
"True",
"PayPal",
"successfully",
"creates",
"the",
"profile",
"otherwise",
"False",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L182-L201 | train | 200,126 |
spookylukey/django-paypal | paypal/pro/helpers.py | PayPalWPP.manangeRecurringPaymentsProfileStatus | def manangeRecurringPaymentsProfileStatus(self, params, fail_silently=False):
"""
Requires `profileid` and `action` params.
Action must be either "Cancel", "Suspend", or "Reactivate".
"""
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 = 'Invalid profile status for cancel action; profile should be active or suspended'
if nvp_obj.flag and not (fail_silently and nvp_obj.flag_info == flag_info_test_string):
raise PayPalFailure(nvp_obj.flag_info, nvp=nvp_obj)
return nvp_obj | python | def manangeRecurringPaymentsProfileStatus(self, params, fail_silently=False):
"""
Requires `profileid` and `action` params.
Action must be either "Cancel", "Suspend", or "Reactivate".
"""
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 = 'Invalid profile status for cancel action; profile should be active or suspended'
if nvp_obj.flag and not (fail_silently and nvp_obj.flag_info == flag_info_test_string):
raise PayPalFailure(nvp_obj.flag_info, nvp=nvp_obj)
return nvp_obj | [
"def",
"manangeRecurringPaymentsProfileStatus",
"(",
"self",
",",
"params",
",",
"fail_silently",
"=",
"False",
")",
":",
"defaults",
"=",
"{",
"\"method\"",
":",
"\"ManageRecurringPaymentsProfileStatus\"",
"}",
"required",
"=",
"[",
"\"profileid\"",
",",
"\"action\""... | Requires `profileid` and `action` params.
Action must be either "Cancel", "Suspend", or "Reactivate". | [
"Requires",
"profileid",
"and",
"action",
"params",
".",
"Action",
"must",
"be",
"either",
"Cancel",
"Suspend",
"or",
"Reactivate",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L249-L263 | train | 200,127 |
spookylukey/django-paypal | paypal/pro/helpers.py | PayPalWPP._recurring_setExpressCheckout_adapter | 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.
"""
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 params | python | 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.
"""
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 params | [
"def",
"_recurring_setExpressCheckout_adapter",
"(",
"self",
",",
"params",
")",
":",
"params",
"[",
"'l_billingtype0'",
"]",
"=",
"\"RecurringPayments\"",
"params",
"[",
"'l_billingagreementdescription0'",
"]",
"=",
"params",
"[",
"'desc'",
"]",
"REMOVE",
"=",
"[",... | 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. | [
"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",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L288-L301 | train | 200,128 |
spookylukey/django-paypal | paypal/pro/helpers.py | PayPalWPP._fetch | def _fetch(self, params, required, defaults):
"""Make the NVP request and store the response."""
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.pformat(defaults))
log.debug('PayPal Response:\n%s\n', pprint.pformat(response_params))
# Gather all NVP parameters to pass to a new instance.
nvp_params = {}
tmpd = defaults.copy()
tmpd.update(response_params)
for k, v in tmpd.items():
if k in self.NVP_FIELDS:
nvp_params[str(k)] = v
# PayPal timestamp has to be formatted.
if 'timestamp' in nvp_params:
nvp_params['timestamp'] = paypaltime2datetime(nvp_params['timestamp'])
nvp_obj = PayPalNVP(**nvp_params)
nvp_obj.init(self.request, params, response_params)
nvp_obj.save()
return nvp_obj | python | def _fetch(self, params, required, defaults):
"""Make the NVP request and store the response."""
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.pformat(defaults))
log.debug('PayPal Response:\n%s\n', pprint.pformat(response_params))
# Gather all NVP parameters to pass to a new instance.
nvp_params = {}
tmpd = defaults.copy()
tmpd.update(response_params)
for k, v in tmpd.items():
if k in self.NVP_FIELDS:
nvp_params[str(k)] = v
# PayPal timestamp has to be formatted.
if 'timestamp' in nvp_params:
nvp_params['timestamp'] = paypaltime2datetime(nvp_params['timestamp'])
nvp_obj = PayPalNVP(**nvp_params)
nvp_obj.init(self.request, params, response_params)
nvp_obj.save()
return nvp_obj | [
"def",
"_fetch",
"(",
"self",
",",
"params",
",",
"required",
",",
"defaults",
")",
":",
"defaults",
".",
"update",
"(",
"params",
")",
"pp_params",
"=",
"self",
".",
"_check_and_update_params",
"(",
"required",
",",
"defaults",
")",
"pp_string",
"=",
"sel... | Make the NVP request and store the response. | [
"Make",
"the",
"NVP",
"request",
"and",
"store",
"the",
"response",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L303-L329 | train | 200,129 |
spookylukey/django-paypal | paypal/pro/helpers.py | PayPalWPP._request | def _request(self, data):
"""Moved out to make testing easier."""
return requests.post(self.endpoint, data=data.encode("ascii")).content | python | def _request(self, data):
"""Moved out to make testing easier."""
return requests.post(self.endpoint, data=data.encode("ascii")).content | [
"def",
"_request",
"(",
"self",
",",
"data",
")",
":",
"return",
"requests",
".",
"post",
"(",
"self",
".",
"endpoint",
",",
"data",
"=",
"data",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
".",
"content"
] | Moved out to make testing easier. | [
"Moved",
"out",
"to",
"make",
"testing",
"easier",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L331-L333 | train | 200,130 |
spookylukey/django-paypal | paypal/pro/helpers.py | PayPalWPP._check_and_update_params | def _check_and_update_params(self, required, params):
"""
Ensure all required parameters were passed to the API call and format
them correctly.
"""
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())) | python | def _check_and_update_params(self, required, params):
"""
Ensure all required parameters were passed to the API call and format
them correctly.
"""
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",
")",
":",
"for",
"r",
"in",
"required",
":",
"if",
"r",
"not",
"in",
"params",
":",
"raise",
"PayPalError",
"(",
"\"Missing required param: %s\"",
"%",
"r",
")",
"# Upper case all ... | Ensure all required parameters were passed to the API call and format
them correctly. | [
"Ensure",
"all",
"required",
"parameters",
"were",
"passed",
"to",
"the",
"API",
"call",
"and",
"format",
"them",
"correctly",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L335-L345 | train | 200,131 |
spookylukey/django-paypal | paypal/pro/helpers.py | PayPalWPP._parse_response | def _parse_response(self, response):
"""Turn the PayPal response into a dict"""
q = QueryDict(response, encoding='UTF-8').dict()
return {k.lower(): v for k, v in q.items()} | python | def _parse_response(self, response):
"""Turn the PayPal response into a dict"""
q = QueryDict(response, encoding='UTF-8').dict()
return {k.lower(): v for k, v in q.items()} | [
"def",
"_parse_response",
"(",
"self",
",",
"response",
")",
":",
"q",
"=",
"QueryDict",
"(",
"response",
",",
"encoding",
"=",
"'UTF-8'",
")",
".",
"dict",
"(",
")",
"return",
"{",
"k",
".",
"lower",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in... | Turn the PayPal response into a dict | [
"Turn",
"the",
"PayPal",
"response",
"into",
"a",
"dict"
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L347-L350 | train | 200,132 |
spookylukey/django-paypal | paypal/standard/pdt/models.py | PayPalPDT._postback | def _postback(self):
"""
Perform PayPal PDT Postback validation.
Sends the transaction ID and business token to PayPal which responses with
SUCCESS or FAILED.
"""
return requests.post(self.get_endpoint(),
data=dict(cmd="_notify-synch", at=IDENTITY_TOKEN, tx=self.tx)).content | python | def _postback(self):
"""
Perform PayPal PDT Postback validation.
Sends the transaction ID and business token to PayPal which responses with
SUCCESS or FAILED.
"""
return requests.post(self.get_endpoint(),
data=dict(cmd="_notify-synch", at=IDENTITY_TOKEN, tx=self.tx)).content | [
"def",
"_postback",
"(",
"self",
")",
":",
"return",
"requests",
".",
"post",
"(",
"self",
".",
"get_endpoint",
"(",
")",
",",
"data",
"=",
"dict",
"(",
"cmd",
"=",
"\"_notify-synch\"",
",",
"at",
"=",
"IDENTITY_TOKEN",
",",
"tx",
"=",
"self",
".",
"... | Perform PayPal PDT Postback validation.
Sends the transaction ID and business token to PayPal which responses with
SUCCESS or FAILED. | [
"Perform",
"PayPal",
"PDT",
"Postback",
"validation",
".",
"Sends",
"the",
"transaction",
"ID",
"and",
"business",
"token",
"to",
"PayPal",
"which",
"responses",
"with",
"SUCCESS",
"or",
"FAILED",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/pdt/models.py#L43-L51 | train | 200,133 |
spookylukey/django-paypal | paypal/standard/helpers.py | duplicate_txn_id | 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.
"""
# 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 transaction, has the payment_status changed?
return similars[0].payment_status == ipn_obj.payment_status
return False | python | 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.
"""
# 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 transaction, has the payment_status changed?
return similars[0].payment_status == ipn_obj.payment_status
return False | [
"def",
"duplicate_txn_id",
"(",
"ipn_obj",
")",
":",
"# get latest similar transaction(s)",
"similars",
"=",
"(",
"ipn_obj",
".",
"__class__",
".",
"_default_manager",
".",
"filter",
"(",
"txn_id",
"=",
"ipn_obj",
".",
"txn_id",
")",
".",
"exclude",
"(",
"id",
... | 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. | [
"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",... | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/helpers.py#L16-L37 | train | 200,134 |
spookylukey/django-paypal | paypal/standard/helpers.py | make_secret | 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.
"""
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 invoice or custom fields as well - otherwise its always the same.
# Build the secret with fields availible in both PaymentForm and the IPN. Order matters.
if secret_fields is None:
secret_fields = ['business', 'item_name']
data = ""
for name in secret_fields:
if hasattr(form_instance, 'cleaned_data'):
if name in form_instance.cleaned_data:
data += unicode(form_instance.cleaned_data[name])
else:
# Initial data passed into the constructor overrides defaults.
if name in form_instance.initial:
data += unicode(form_instance.initial[name])
elif name in form_instance.fields and form_instance.fields[name].initial is not None:
data += unicode(form_instance.fields[name].initial)
secret = get_sha1_hexdigest(settings.SECRET_KEY, data)
return secret | python | 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.
"""
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 invoice or custom fields as well - otherwise its always the same.
# Build the secret with fields availible in both PaymentForm and the IPN. Order matters.
if secret_fields is None:
secret_fields = ['business', 'item_name']
data = ""
for name in secret_fields:
if hasattr(form_instance, 'cleaned_data'):
if name in form_instance.cleaned_data:
data += unicode(form_instance.cleaned_data[name])
else:
# Initial data passed into the constructor overrides defaults.
if name in form_instance.initial:
data += unicode(form_instance.initial[name])
elif name in form_instance.fields and form_instance.fields[name].initial is not None:
data += unicode(form_instance.fields[name].initial)
secret = get_sha1_hexdigest(settings.SECRET_KEY, data)
return secret | [
"def",
"make_secret",
"(",
"form_instance",
",",
"secret_fields",
"=",
"None",
")",
":",
"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 ... | 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. | [
"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",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/helpers.py#L40-L69 | train | 200,135 |
spookylukey/django-paypal | paypal/pro/creditcard.py | CreditCard.is_number | def is_number(self):
"""True if there is at least one digit in number."""
self.number = re.sub(r'[^\d]', '', self.number)
return self.number.isdigit() | python | def is_number(self):
"""True if there is at least one digit in number."""
self.number = re.sub(r'[^\d]', '', self.number)
return self.number.isdigit() | [
"def",
"is_number",
"(",
"self",
")",
":",
"self",
".",
"number",
"=",
"re",
".",
"sub",
"(",
"r'[^\\d]'",
",",
"''",
",",
"self",
".",
"number",
")",
"return",
"self",
".",
"number",
".",
"isdigit",
"(",
")"
] | True if there is at least one digit in number. | [
"True",
"if",
"there",
"is",
"at",
"least",
"one",
"digit",
"in",
"number",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/creditcard.py#L39-L42 | train | 200,136 |
spookylukey/django-paypal | paypal/pro/creditcard.py | CreditCard.is_mod10 | def is_mod10(self):
"""Returns True if number is valid according to mod10."""
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 | python | def is_mod10(self):
"""Returns True if number is valid according to mod10."""
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",
")",
":",
"double",
"=",
"0",
"total",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"number",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"for",
"c",
"in",
"str",
"(",
"(",
... | Returns True if number is valid according to mod10. | [
"Returns",
"True",
"if",
"number",
"is",
"valid",
"according",
"to",
"mod10",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/creditcard.py#L44-L52 | train | 200,137 |
spookylukey/django-paypal | paypal/pro/creditcard.py | CreditCard.get_type | def get_type(self):
"""Return the type if it matches one of the cards."""
for card, pattern in CARDS.items():
if pattern.match(self.number):
return card
return None | python | def get_type(self):
"""Return the type if it matches one of the cards."""
for card, pattern in CARDS.items():
if pattern.match(self.number):
return card
return None | [
"def",
"get_type",
"(",
"self",
")",
":",
"for",
"card",
",",
"pattern",
"in",
"CARDS",
".",
"items",
"(",
")",
":",
"if",
"pattern",
".",
"match",
"(",
"self",
".",
"number",
")",
":",
"return",
"card",
"return",
"None"
] | Return the type if it matches one of the cards. | [
"Return",
"the",
"type",
"if",
"it",
"matches",
"one",
"of",
"the",
"cards",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/creditcard.py#L61-L66 | train | 200,138 |
spookylukey/django-paypal | paypal/pro/creditcard.py | CreditCard.verify | def verify(self):
"""Returns the card type if valid else None."""
if self.is_number() and not self.is_test() and self.is_mod10():
return self.get_type()
return None | python | def verify(self):
"""Returns the card type if valid else None."""
if self.is_number() and not self.is_test() and self.is_mod10():
return self.get_type()
return None | [
"def",
"verify",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_number",
"(",
")",
"and",
"not",
"self",
".",
"is_test",
"(",
")",
"and",
"self",
".",
"is_mod10",
"(",
")",
":",
"return",
"self",
".",
"get_type",
"(",
")",
"return",
"None"
] | Returns the card type if valid else None. | [
"Returns",
"the",
"card",
"type",
"if",
"valid",
"else",
"None",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/creditcard.py#L68-L72 | train | 200,139 |
spookylukey/django-paypal | paypal/pro/fields.py | CreditCardField.clean | def clean(self, value):
"""Raises a ValidationError if the card is not valid and stashes card type."""
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 | python | def clean(self, value):
"""Raises a ValidationError if the card is not valid and stashes card type."""
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",
")",
":",
"if",
"value",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"self",
".",
"card_type",
"=",
"verify_credit_card",
"(",
"value... | Raises a ValidationError if the card is not valid and stashes card type. | [
"Raises",
"a",
"ValidationError",
"if",
"the",
"card",
"is",
"not",
"valid",
"and",
"stashes",
"card",
"type",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/fields.py#L24-L31 | train | 200,140 |
spookylukey/django-paypal | paypal/pro/forms.py | PaymentForm.process | def process(self, request, item):
"""Process a PayPal direct payment."""
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'] = request.META.get("REMOTE_ADDR", "")
params.update(item)
try:
# Create single payment:
if 'billingperiod' not in params:
wpp.doDirectPayment(params)
# Create recurring payment:
else:
wpp.createRecurringPaymentsProfile(params, direct=True)
except PayPalFailure:
return False
return True | python | def process(self, request, item):
"""Process a PayPal direct payment."""
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'] = request.META.get("REMOTE_ADDR", "")
params.update(item)
try:
# Create single payment:
if 'billingperiod' not in params:
wpp.doDirectPayment(params)
# Create recurring payment:
else:
wpp.createRecurringPaymentsProfile(params, direct=True)
except PayPalFailure:
return False
return True | [
"def",
"process",
"(",
"self",
",",
"request",
",",
"item",
")",
":",
"warn_untested",
"(",
")",
"from",
"paypal",
".",
"pro",
".",
"helpers",
"import",
"PayPalWPP",
"wpp",
"=",
"PayPalWPP",
"(",
"request",
")",
"params",
"=",
"self",
".",
"cleaned_data"... | Process a PayPal direct payment. | [
"Process",
"a",
"PayPal",
"direct",
"payment",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/forms.py#L27-L48 | train | 200,141 |
spookylukey/django-paypal | paypal/standard/ipn/models.py | PayPalIPN._postback | def _postback(self):
"""Perform PayPal Postback validation."""
return requests.post(self.get_endpoint(), data=b"cmd=_notify-validate&" + self.query.encode("ascii")).content | python | def _postback(self):
"""Perform PayPal Postback validation."""
return requests.post(self.get_endpoint(), data=b"cmd=_notify-validate&" + self.query.encode("ascii")).content | [
"def",
"_postback",
"(",
"self",
")",
":",
"return",
"requests",
".",
"post",
"(",
"self",
".",
"get_endpoint",
"(",
")",
",",
"data",
"=",
"b\"cmd=_notify-validate&\"",
"+",
"self",
".",
"query",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
".",
"content"... | Perform PayPal Postback validation. | [
"Perform",
"PayPal",
"Postback",
"validation",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/ipn/models.py#L19-L21 | train | 200,142 |
spookylukey/django-paypal | paypal/standard/ipn/models.py | PayPalIPN.send_signals | def send_signals(self):
"""Shout for the world to hear whether a txn was successful."""
if self.flag:
invalid_ipn_received.send(sender=self)
return
else:
valid_ipn_received.send(sender=self) | python | def send_signals(self):
"""Shout for the world to hear whether a txn was successful."""
if self.flag:
invalid_ipn_received.send(sender=self)
return
else:
valid_ipn_received.send(sender=self) | [
"def",
"send_signals",
"(",
"self",
")",
":",
"if",
"self",
".",
"flag",
":",
"invalid_ipn_received",
".",
"send",
"(",
"sender",
"=",
"self",
")",
"return",
"else",
":",
"valid_ipn_received",
".",
"send",
"(",
"sender",
"=",
"self",
")"
] | Shout for the world to hear whether a txn was successful. | [
"Shout",
"for",
"the",
"world",
"to",
"hear",
"whether",
"a",
"txn",
"was",
"successful",
"."
] | b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f | https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/ipn/models.py#L27-L33 | train | 200,143 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/dialect.py | visit_delete_stmt | 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 ]
By default, SqlAlchemy compiles DELETE statements with the
syntax:
.. :code-block: sql
DELETE [ FROM ] table_name
[ WHERE condition ]
problem illustration:
>>> from sqlalchemy import Table, Column, Integer, MetaData, delete
>>> from sqlalchemy_redshift.dialect import RedshiftDialect
>>> meta = MetaData()
>>> table1 = Table(
... 'table_1',
... meta,
... Column('pk', Integer, primary_key=True)
... )
...
>>> table2 = Table(
... 'table_2',
... meta,
... Column('pk', Integer, primary_key=True)
... )
...
>>> del_stmt = delete(table1).where(table1.c.pk==table2.c.pk)
>>> str(del_stmt.compile(dialect=RedshiftDialect()))
'DELETE FROM table_1 USING table_2 WHERE table_1.pk = table_2.pk'
>>> str(del_stmt)
'DELETE FROM table_1 , table_2 WHERE table_1.pk = table_2.pk'
>>> del_stmt2 = delete(table1)
>>> str(del_stmt2)
'DELETE FROM table_1'
>>> del_stmt3 = delete(table1).where(table1.c.pk > 1000)
>>> str(del_stmt3)
'DELETE FROM table_1 WHERE table_1.pk > :pk_1'
>>> str(del_stmt3.compile(dialect=RedshiftDialect()))
'DELETE FROM table_1 WHERE table_1.pk > %(pk_1)s'
"""
# 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, the using clause text is built, if applicable
# note:
# the tables in the using clause are sorted in the order in
# which they first appear in the where clause.
delete_stmt_table = compiler.process(element.table, asfrom=True, **kwargs)
whereclause_tuple = element.get_children()
if whereclause_tuple:
usingclause_tables = []
whereclause = ' WHERE {clause}'.format(
clause=compiler.process(*whereclause_tuple, **kwargs)
)
whereclause_columns = gen_columns_from_children(element)
for col in whereclause_columns:
table = compiler.process(col.table, asfrom=True, **kwargs)
if table != delete_stmt_table and table not in usingclause_tables:
usingclause_tables.append(table)
if usingclause_tables:
usingclause = ' USING {clause}'.format(
clause=', '.join(usingclause_tables)
)
return 'DELETE FROM {table}{using}{where}'.format(
table=delete_stmt_table,
using=usingclause,
where=whereclause) | python | 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 ]
By default, SqlAlchemy compiles DELETE statements with the
syntax:
.. :code-block: sql
DELETE [ FROM ] table_name
[ WHERE condition ]
problem illustration:
>>> from sqlalchemy import Table, Column, Integer, MetaData, delete
>>> from sqlalchemy_redshift.dialect import RedshiftDialect
>>> meta = MetaData()
>>> table1 = Table(
... 'table_1',
... meta,
... Column('pk', Integer, primary_key=True)
... )
...
>>> table2 = Table(
... 'table_2',
... meta,
... Column('pk', Integer, primary_key=True)
... )
...
>>> del_stmt = delete(table1).where(table1.c.pk==table2.c.pk)
>>> str(del_stmt.compile(dialect=RedshiftDialect()))
'DELETE FROM table_1 USING table_2 WHERE table_1.pk = table_2.pk'
>>> str(del_stmt)
'DELETE FROM table_1 , table_2 WHERE table_1.pk = table_2.pk'
>>> del_stmt2 = delete(table1)
>>> str(del_stmt2)
'DELETE FROM table_1'
>>> del_stmt3 = delete(table1).where(table1.c.pk > 1000)
>>> str(del_stmt3)
'DELETE FROM table_1 WHERE table_1.pk > :pk_1'
>>> str(del_stmt3.compile(dialect=RedshiftDialect()))
'DELETE FROM table_1 WHERE table_1.pk > %(pk_1)s'
"""
# 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, the using clause text is built, if applicable
# note:
# the tables in the using clause are sorted in the order in
# which they first appear in the where clause.
delete_stmt_table = compiler.process(element.table, asfrom=True, **kwargs)
whereclause_tuple = element.get_children()
if whereclause_tuple:
usingclause_tables = []
whereclause = ' WHERE {clause}'.format(
clause=compiler.process(*whereclause_tuple, **kwargs)
)
whereclause_columns = gen_columns_from_children(element)
for col in whereclause_columns:
table = compiler.process(col.table, asfrom=True, **kwargs)
if table != delete_stmt_table and table not in usingclause_tables:
usingclause_tables.append(table)
if usingclause_tables:
usingclause = ' USING {clause}'.format(
clause=', '.join(usingclause_tables)
)
return 'DELETE FROM {table}{using}{where}'.format(
table=delete_stmt_table,
using=usingclause,
where=whereclause) | [
"def",
"visit_delete_stmt",
"(",
"element",
",",
"compiler",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set empty strings for the default where clause and using clause",
"whereclause",
"=",
"''",
"usingclause",
"=",
"''",
"# determine if the delete query needs a ``USING`` injected",... | 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 ]
By default, SqlAlchemy compiles DELETE statements with the
syntax:
.. :code-block: sql
DELETE [ FROM ] table_name
[ WHERE condition ]
problem illustration:
>>> from sqlalchemy import Table, Column, Integer, MetaData, delete
>>> from sqlalchemy_redshift.dialect import RedshiftDialect
>>> meta = MetaData()
>>> table1 = Table(
... 'table_1',
... meta,
... Column('pk', Integer, primary_key=True)
... )
...
>>> table2 = Table(
... 'table_2',
... meta,
... Column('pk', Integer, primary_key=True)
... )
...
>>> del_stmt = delete(table1).where(table1.c.pk==table2.c.pk)
>>> str(del_stmt.compile(dialect=RedshiftDialect()))
'DELETE FROM table_1 USING table_2 WHERE table_1.pk = table_2.pk'
>>> str(del_stmt)
'DELETE FROM table_1 , table_2 WHERE table_1.pk = table_2.pk'
>>> del_stmt2 = delete(table1)
>>> str(del_stmt2)
'DELETE FROM table_1'
>>> del_stmt3 = delete(table1).where(table1.c.pk > 1000)
>>> str(del_stmt3)
'DELETE FROM table_1 WHERE table_1.pk > :pk_1'
>>> str(del_stmt3.compile(dialect=RedshiftDialect()))
'DELETE FROM table_1 WHERE table_1.pk > %(pk_1)s' | [
"Adds",
"redshift",
"-",
"dialect",
"specific",
"compilation",
"rule",
"for",
"the",
"delete",
"statement",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/dialect.py#L820-L906 | train | 200,144 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/dialect.py | RedshiftDialect.get_columns | 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`.
"""
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(
name=col.name, format_type=col.format_type,
default=col.default, notnull=col.notnull, domains=domains,
enums=[], schema=col.schema, encode=col.encode)
columns.append(column_info)
return columns | python | 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`.
"""
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(
name=col.name, format_type=col.format_type,
default=col.default, notnull=col.notnull, domains=domains,
enums=[], schema=col.schema, encode=col.encode)
columns.append(column_info)
return columns | [
"def",
"get_columns",
"(",
"self",
",",
"connection",
",",
"table_name",
",",
"schema",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"cols",
"=",
"self",
".",
"_get_redshift_columns",
"(",
"connection",
",",
"table_name",
",",
"schema",
",",
"*",
"*",
"... | Return information about columns in `table_name`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_columns`. | [
"Return",
"information",
"about",
"columns",
"in",
"table_name",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/dialect.py#L419-L437 | train | 200,145 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/dialect.py | RedshiftDialect.get_pk_constraint | 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`.
"""
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': ''}
pk_constraint = pk_constraints[0]
m = PRIMARY_KEY_RE.match(pk_constraint.condef)
colstring = m.group('columns')
constrained_columns = SQL_IDENTIFIER_RE.findall(colstring)
return {
'constrained_columns': constrained_columns,
'name': pk_constraint.conname,
} | python | 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`.
"""
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': ''}
pk_constraint = pk_constraints[0]
m = PRIMARY_KEY_RE.match(pk_constraint.condef)
colstring = m.group('columns')
constrained_columns = SQL_IDENTIFIER_RE.findall(colstring)
return {
'constrained_columns': constrained_columns,
'name': pk_constraint.conname,
} | [
"def",
"get_pk_constraint",
"(",
"self",
",",
"connection",
",",
"table_name",
",",
"schema",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"constraints",
"=",
"self",
".",
"_get_redshift_constraints",
"(",
"connection",
",",
"table_name",
",",
"schema",
",",
... | Return information about the primary key constraint on `table_name`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_pk_constraint`. | [
"Return",
"information",
"about",
"the",
"primary",
"key",
"constraint",
"on",
"table_name",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/dialect.py#L440-L459 | train | 200,146 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/dialect.py | RedshiftDialect.get_foreign_keys | 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`.
"""
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:
uniques[con.conname]["key"] = con.conkey
uniques[con.conname]["condef"] = con.condef
fkeys = []
for conname, attrs in uniques.items():
m = FOREIGN_KEY_RE.match(attrs['condef'])
colstring = m.group('referred_columns')
referred_columns = SQL_IDENTIFIER_RE.findall(colstring)
referred_table = m.group('referred_table')
referred_schema = m.group('referred_schema')
colstring = m.group('columns')
constrained_columns = SQL_IDENTIFIER_RE.findall(colstring)
fkey_d = {
'name': conname,
'constrained_columns': constrained_columns,
'referred_schema': referred_schema,
'referred_table': referred_table,
'referred_columns': referred_columns,
}
fkeys.append(fkey_d)
return fkeys | python | 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`.
"""
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:
uniques[con.conname]["key"] = con.conkey
uniques[con.conname]["condef"] = con.condef
fkeys = []
for conname, attrs in uniques.items():
m = FOREIGN_KEY_RE.match(attrs['condef'])
colstring = m.group('referred_columns')
referred_columns = SQL_IDENTIFIER_RE.findall(colstring)
referred_table = m.group('referred_table')
referred_schema = m.group('referred_schema')
colstring = m.group('columns')
constrained_columns = SQL_IDENTIFIER_RE.findall(colstring)
fkey_d = {
'name': conname,
'constrained_columns': constrained_columns,
'referred_schema': referred_schema,
'referred_table': referred_table,
'referred_columns': referred_columns,
}
fkeys.append(fkey_d)
return fkeys | [
"def",
"get_foreign_keys",
"(",
"self",
",",
"connection",
",",
"table_name",
",",
"schema",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"constraints",
"=",
"self",
".",
"_get_redshift_constraints",
"(",
"connection",
",",
"table_name",
",",
"schema",
",",
... | Return information about foreign keys in `table_name`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_pk_constraint`. | [
"Return",
"information",
"about",
"foreign",
"keys",
"in",
"table_name",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/dialect.py#L462-L493 | train | 200,147 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/dialect.py | RedshiftDialect.get_table_names | 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`.
"""
return self._get_table_or_view_names('r', connection, schema, **kw) | python | 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`.
"""
return self._get_table_or_view_names('r', connection, schema, **kw) | [
"def",
"get_table_names",
"(",
"self",
",",
"connection",
",",
"schema",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_get_table_or_view_names",
"(",
"'r'",
",",
"connection",
",",
"schema",
",",
"*",
"*",
"kw",
")"
] | Return a list of table names for `schema`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_table_names`. | [
"Return",
"a",
"list",
"of",
"table",
"names",
"for",
"schema",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/dialect.py#L496-L503 | train | 200,148 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/dialect.py | RedshiftDialect.get_view_names | 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`.
"""
return self._get_table_or_view_names('v', connection, schema, **kw) | python | 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`.
"""
return self._get_table_or_view_names('v', connection, schema, **kw) | [
"def",
"get_view_names",
"(",
"self",
",",
"connection",
",",
"schema",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_get_table_or_view_names",
"(",
"'v'",
",",
"connection",
",",
"schema",
",",
"*",
"*",
"kw",
")"
] | Return a list of view names for `schema`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_view_names`. | [
"Return",
"a",
"list",
"of",
"view",
"names",
"for",
"schema",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/dialect.py#L506-L513 | train | 200,149 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/dialect.py | RedshiftDialect.get_unique_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`.
"""
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:
uniques[con.conname]["key"] = con.conkey
uniques[con.conname]["cols"][con.attnum] = con.attname
return [
{'name': None,
'column_names': [uc["cols"][i] for i in uc["key"]]}
for name, uc in uniques.items()
] | python | 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`.
"""
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:
uniques[con.conname]["key"] = con.conkey
uniques[con.conname]["cols"][con.attnum] = con.attname
return [
{'name': None,
'column_names': [uc["cols"][i] for i in uc["key"]]}
for name, uc in uniques.items()
] | [
"def",
"get_unique_constraints",
"(",
"self",
",",
"connection",
",",
"table_name",
",",
"schema",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"constraints",
"=",
"self",
".",
"_get_redshift_constraints",
"(",
"connection",
",",
"table_name",
",",
"schema",
... | Return information about unique constraints in `table_name`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_unique_constraints`. | [
"Return",
"information",
"about",
"unique",
"constraints",
"in",
"table_name",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/dialect.py#L540-L560 | train | 200,150 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/dialect.py | RedshiftDialect.get_table_options | 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`.
"""
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,
schema, **kw)
columns = self._get_redshift_columns(connection, table_name,
schema, **kw)
sortkey_cols = sorted([col for col in columns if col.sortkey],
key=keyfunc)
interleaved = any([int(col.sortkey) < 0 for col in sortkey_cols])
sortkey = [col.name for col in sortkey_cols]
interleaved_sortkey = None
if interleaved:
interleaved_sortkey = sortkey
sortkey = None
distkeys = [col.name for col in columns if col.distkey]
distkey = distkeys[0] if distkeys else None
return {
'redshift_diststyle': table.diststyle,
'redshift_distkey': distkey,
'redshift_sortkey': sortkey,
'redshift_interleaved_sortkey': interleaved_sortkey,
} | python | 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`.
"""
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,
schema, **kw)
columns = self._get_redshift_columns(connection, table_name,
schema, **kw)
sortkey_cols = sorted([col for col in columns if col.sortkey],
key=keyfunc)
interleaved = any([int(col.sortkey) < 0 for col in sortkey_cols])
sortkey = [col.name for col in sortkey_cols]
interleaved_sortkey = None
if interleaved:
interleaved_sortkey = sortkey
sortkey = None
distkeys = [col.name for col in columns if col.distkey]
distkey = distkeys[0] if distkeys else None
return {
'redshift_diststyle': table.diststyle,
'redshift_distkey': distkey,
'redshift_sortkey': sortkey,
'redshift_interleaved_sortkey': interleaved_sortkey,
} | [
"def",
"get_table_options",
"(",
"self",
",",
"connection",
",",
"table_name",
",",
"schema",
",",
"*",
"*",
"kw",
")",
":",
"def",
"keyfunc",
"(",
"column",
")",
":",
"num",
"=",
"int",
"(",
"column",
".",
"sortkey",
")",
"# If sortkey is interleaved, col... | Return a dictionary of options specified when the table of the
given name was created.
Overrides interface
:meth:`~sqlalchemy.engine.Inspector.get_table_options`. | [
"Return",
"a",
"dictionary",
"of",
"options",
"specified",
"when",
"the",
"table",
"of",
"the",
"given",
"name",
"was",
"created",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/dialect.py#L563-L595 | train | 200,151 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/dialect.py | RedshiftDialect.create_connect_args | def create_connect_args(self, *args, **kwargs):
"""
Build DB-API compatible connection arguments.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.create_connect_args`.
"""
default_args = {
'sslmode': 'verify-full',
'sslrootcert': pkg_resources.resource_filename(
__name__,
'redshift-ca-bundle.crt'
),
}
cargs, cparams = super(RedshiftDialect, self).create_connect_args(
*args, **kwargs
)
default_args.update(cparams)
return cargs, default_args | python | def create_connect_args(self, *args, **kwargs):
"""
Build DB-API compatible connection arguments.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.create_connect_args`.
"""
default_args = {
'sslmode': 'verify-full',
'sslrootcert': pkg_resources.resource_filename(
__name__,
'redshift-ca-bundle.crt'
),
}
cargs, cparams = super(RedshiftDialect, self).create_connect_args(
*args, **kwargs
)
default_args.update(cparams)
return cargs, default_args | [
"def",
"create_connect_args",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"default_args",
"=",
"{",
"'sslmode'",
":",
"'verify-full'",
",",
"'sslrootcert'",
":",
"pkg_resources",
".",
"resource_filename",
"(",
"__name__",
",",
"'redshift-... | Build DB-API compatible connection arguments.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.create_connect_args`. | [
"Build",
"DB",
"-",
"API",
"compatible",
"connection",
"arguments",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/dialect.py#L597-L615 | train | 200,152 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/commands.py | visit_unload_from_select | def visit_unload_from_select(element, compiler, **kw):
"""Returns the actual sql query for the UnloadFromSelect class."""
template = """
UNLOAD (:select) TO :unload_location
CREDENTIALS :credentials
{manifest}
{header}
{delimiter}
{encrypted}
{fixed_width}
{gzip}
{add_quotes}
{null}
{escape}
{allow_overwrite}
{parallel}
{region}
{max_file_size}
"""
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 '',
fixed_width='FIXEDWIDTH AS :fixed_width' if el.fixed_width else '',
gzip='GZIP' if el.gzip else '',
add_quotes='ADDQUOTES' if el.add_quotes else '',
escape='ESCAPE' if el.escape else '',
null='NULL AS :null_as' if el.null is not None else '',
allow_overwrite='ALLOWOVERWRITE' if el.allow_overwrite else '',
parallel='PARALLEL OFF' if not el.parallel else '',
region='REGION :region' if el.region is not None else '',
max_file_size=(
'MAXFILESIZE :max_file_size MB'
if el.max_file_size is not None else ''
),
)
query = sa.text(qs)
if el.delimiter is not None:
query = query.bindparams(sa.bindparam(
'delimiter', value=element.delimiter, type_=sa.String,
))
if el.fixed_width:
query = query.bindparams(sa.bindparam(
'fixed_width',
value=_process_fixed_width(el.fixed_width),
type_=sa.String,
))
if el.null is not None:
query = query.bindparams(sa.bindparam(
'null_as', value=el.null, type_=sa.String
))
if el.region is not None:
query = query.bindparams(sa.bindparam(
'region', value=el.region, type_=sa.String
))
if el.max_file_size is not None:
max_file_size_mib = float(el.max_file_size) / 1024 / 1024
query = query.bindparams(sa.bindparam(
'max_file_size', value=max_file_size_mib, type_=sa.Float
))
return compiler.process(
query.bindparams(
sa.bindparam('credentials', value=el.credentials, type_=sa.String),
sa.bindparam(
'unload_location', value=el.unload_location, type_=sa.String,
),
sa.bindparam(
'select',
value=compiler.process(
el.select,
literal_binds=True,
),
type_=sa.String,
),
),
**kw
) | python | def visit_unload_from_select(element, compiler, **kw):
"""Returns the actual sql query for the UnloadFromSelect class."""
template = """
UNLOAD (:select) TO :unload_location
CREDENTIALS :credentials
{manifest}
{header}
{delimiter}
{encrypted}
{fixed_width}
{gzip}
{add_quotes}
{null}
{escape}
{allow_overwrite}
{parallel}
{region}
{max_file_size}
"""
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 '',
fixed_width='FIXEDWIDTH AS :fixed_width' if el.fixed_width else '',
gzip='GZIP' if el.gzip else '',
add_quotes='ADDQUOTES' if el.add_quotes else '',
escape='ESCAPE' if el.escape else '',
null='NULL AS :null_as' if el.null is not None else '',
allow_overwrite='ALLOWOVERWRITE' if el.allow_overwrite else '',
parallel='PARALLEL OFF' if not el.parallel else '',
region='REGION :region' if el.region is not None else '',
max_file_size=(
'MAXFILESIZE :max_file_size MB'
if el.max_file_size is not None else ''
),
)
query = sa.text(qs)
if el.delimiter is not None:
query = query.bindparams(sa.bindparam(
'delimiter', value=element.delimiter, type_=sa.String,
))
if el.fixed_width:
query = query.bindparams(sa.bindparam(
'fixed_width',
value=_process_fixed_width(el.fixed_width),
type_=sa.String,
))
if el.null is not None:
query = query.bindparams(sa.bindparam(
'null_as', value=el.null, type_=sa.String
))
if el.region is not None:
query = query.bindparams(sa.bindparam(
'region', value=el.region, type_=sa.String
))
if el.max_file_size is not None:
max_file_size_mib = float(el.max_file_size) / 1024 / 1024
query = query.bindparams(sa.bindparam(
'max_file_size', value=max_file_size_mib, type_=sa.Float
))
return compiler.process(
query.bindparams(
sa.bindparam('credentials', value=el.credentials, type_=sa.String),
sa.bindparam(
'unload_location', value=el.unload_location, type_=sa.String,
),
sa.bindparam(
'select',
value=compiler.process(
el.select,
literal_binds=True,
),
type_=sa.String,
),
),
**kw
) | [
"def",
"visit_unload_from_select",
"(",
"element",
",",
"compiler",
",",
"*",
"*",
"kw",
")",
":",
"template",
"=",
"\"\"\"\n UNLOAD (:select) TO :unload_location\n CREDENTIALS :credentials\n {manifest}\n {header}\n {delimiter}\n {encrypted}\n {f... | Returns the actual sql query for the UnloadFromSelect class. | [
"Returns",
"the",
"actual",
"sql",
"query",
"for",
"the",
"UnloadFromSelect",
"class",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/commands.py#L217-L306 | train | 200,153 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/commands.py | visit_create_library_command | def visit_create_library_command(element, compiler, **kw):
"""
Returns the actual sql query for the CreateLibraryCommand class.
"""
query = """
CREATE {or_replace} LIBRARY {name}
LANGUAGE pythonplu
FROM :location
WITH CREDENTIALS AS :credentials
{region}
"""
bindparams = [
sa.bindparam(
'location',
value=element.location,
type_=sa.String,
),
sa.bindparam(
'credentials',
value=element.credentials,
type_=sa.String,
),
]
if element.region is not None:
bindparams.append(sa.bindparam(
'region',
value=element.region,
type_=sa.String,
))
quoted_lib_name = compiler.preparer.quote_identifier(element.library_name)
query = query.format(name=quoted_lib_name,
or_replace='OR REPLACE' if element.replace else '',
region='REGION :region' if element.region else '')
return compiler.process(sa.text(query).bindparams(*bindparams), **kw) | python | def visit_create_library_command(element, compiler, **kw):
"""
Returns the actual sql query for the CreateLibraryCommand class.
"""
query = """
CREATE {or_replace} LIBRARY {name}
LANGUAGE pythonplu
FROM :location
WITH CREDENTIALS AS :credentials
{region}
"""
bindparams = [
sa.bindparam(
'location',
value=element.location,
type_=sa.String,
),
sa.bindparam(
'credentials',
value=element.credentials,
type_=sa.String,
),
]
if element.region is not None:
bindparams.append(sa.bindparam(
'region',
value=element.region,
type_=sa.String,
))
quoted_lib_name = compiler.preparer.quote_identifier(element.library_name)
query = query.format(name=quoted_lib_name,
or_replace='OR REPLACE' if element.replace else '',
region='REGION :region' if element.region else '')
return compiler.process(sa.text(query).bindparams(*bindparams), **kw) | [
"def",
"visit_create_library_command",
"(",
"element",
",",
"compiler",
",",
"*",
"*",
"kw",
")",
":",
"query",
"=",
"\"\"\"\n CREATE {or_replace} LIBRARY {name}\n LANGUAGE pythonplu\n FROM :location\n WITH CREDENTIALS AS :credentials\n {region}\n \"... | Returns the actual sql query for the CreateLibraryCommand class. | [
"Returns",
"the",
"actual",
"sql",
"query",
"for",
"the",
"CreateLibraryCommand",
"class",
"."
] | b1a24872da0c8151aa60da4524605b6243d8d765 | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/commands.py#L807-L842 | train | 200,154 |
manugarg/pacparser | src/pymod/pacparser/__init__.py | find_proxy | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"if",
"host",
"is",
"None",
":",
"m",
"=",
"_URL_REGEX",
".",
"match",
"(",
"url",
")",
"if",
"not",
"m",
":",
"raise",
"URLError",
"(",
"url",
")",
"if",
"len",
"(",
"m",
"."... | Finds proxy string for the given url and host. If host is not
defined, it's extracted from the url. | [
"Finds",
"proxy",
"string",
"for",
"the",
"given",
"url",
"and",
"host",
".",
"If",
"host",
"is",
"not",
"defined",
"it",
"s",
"extracted",
"from",
"the",
"url",
"."
] | 94cf1c71fd2e35fe331c8884e723b82d1aa7b975 | https://github.com/manugarg/pacparser/blob/94cf1c71fd2e35fe331c8884e723b82d1aa7b975/src/pymod/pacparser/__init__.py#L73-L86 | train | 200,155 |
manugarg/pacparser | src/pymod/pacparser/__init__.py | just_find_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.
"""
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 | python | 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.
"""
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",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"pacfile",
")",
":",
"raise",
"IOError",
"(",
"'Pac file does not exist: {}'",
".",
"format",
"(",
"pacfile",
")... | 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. | [
"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",
"."
] | 94cf1c71fd2e35fe331c8884e723b82d1aa7b975 | https://github.com/manugarg/pacparser/blob/94cf1c71fd2e35fe331c8884e723b82d1aa7b975/src/pymod/pacparser/__init__.py#L100-L112 | train | 200,156 |
scrapinghub/adblockparser | adblockparser/utils.py | split_data | 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'])
"""
yes, no = [], []
for d in iterable:
if pred(d):
yes.append(d)
else:
no.append(d)
return yes, no | python | 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'])
"""
yes, no = [], []
for d in iterable:
if pred(d):
yes.append(d)
else:
no.append(d)
return yes, no | [
"def",
"split_data",
"(",
"iterable",
",",
"pred",
")",
":",
"yes",
",",
"no",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"d",
"in",
"iterable",
":",
"if",
"pred",
"(",
"d",
")",
":",
"yes",
".",
"append",
"(",
"d",
")",
"else",
":",
"no",
".",
"... | 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']) | [
"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... | 4089612d65018d38dbb88dd7f697bcb07814014d | https://github.com/scrapinghub/adblockparser/blob/4089612d65018d38dbb88dd7f697bcb07814014d/adblockparser/utils.py#L5-L21 | train | 200,157 |
scrapinghub/adblockparser | adblockparser/parser.py | AdblockRule.match_url | def match_url(self, url, options=None):
"""
Return if this rule matches the URL.
What to do if rule is matched is up to developer. Most likely
``.is_exception`` attribute should be taken in account.
"""
options = options or {}
for optname in self.options:
if optname == 'match-case': # TODO
continue
if optname not in options:
raise ValueError("Rule requires option %s" % optname)
if optname == 'domain':
if not self._domain_matches(options['domain']):
return False
continue
if options[optname] != self.options[optname]:
return False
return self._url_matches(url) | python | def match_url(self, url, options=None):
"""
Return if this rule matches the URL.
What to do if rule is matched is up to developer. Most likely
``.is_exception`` attribute should be taken in account.
"""
options = options or {}
for optname in self.options:
if optname == 'match-case': # TODO
continue
if optname not in options:
raise ValueError("Rule requires option %s" % optname)
if optname == 'domain':
if not self._domain_matches(options['domain']):
return False
continue
if options[optname] != self.options[optname]:
return False
return self._url_matches(url) | [
"def",
"match_url",
"(",
"self",
",",
"url",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"for",
"optname",
"in",
"self",
".",
"options",
":",
"if",
"optname",
"==",
"'match-case'",
":",
"# TODO",
"continue",
"if",
... | Return if this rule matches the URL.
What to do if rule is matched is up to developer. Most likely
``.is_exception`` attribute should be taken in account. | [
"Return",
"if",
"this",
"rule",
"matches",
"the",
"URL",
"."
] | 4089612d65018d38dbb88dd7f697bcb07814014d | https://github.com/scrapinghub/adblockparser/blob/4089612d65018d38dbb88dd7f697bcb07814014d/adblockparser/parser.py#L119-L142 | train | 200,158 |
scrapinghub/adblockparser | adblockparser/parser.py | AdblockRule.matching_supported | def matching_supported(self, options=None):
"""
Return whether this rule can return meaningful result,
given the `options` dict. If some options are missing,
then rule shouldn't be matched against, and this function
returns False.
No options:
>>> rule = AdblockRule("swf|")
>>> rule.matching_supported({})
True
Option is used in the rule, but its value is not available
at matching time:
>>> rule = AdblockRule("swf|$third-party")
>>> rule.matching_supported({})
False
Option is used in the rule, and option value is available
at matching time:
>>> rule = AdblockRule("swf|$third-party")
>>> rule.matching_supported({'domain': 'example.com', 'third-party': False})
True
Rule is a comment:
>>> rule = AdblockRule("!this is not a rule")
>>> rule.matching_supported({})
False
"""
if self.is_comment:
return False
if self.is_html_rule: # HTML rules are not supported yet
return False
options = options or {}
keys = set(options.keys())
if not keys.issuperset(self._options_keys):
# some of the required options are not given
return False
return True | python | def matching_supported(self, options=None):
"""
Return whether this rule can return meaningful result,
given the `options` dict. If some options are missing,
then rule shouldn't be matched against, and this function
returns False.
No options:
>>> rule = AdblockRule("swf|")
>>> rule.matching_supported({})
True
Option is used in the rule, but its value is not available
at matching time:
>>> rule = AdblockRule("swf|$third-party")
>>> rule.matching_supported({})
False
Option is used in the rule, and option value is available
at matching time:
>>> rule = AdblockRule("swf|$third-party")
>>> rule.matching_supported({'domain': 'example.com', 'third-party': False})
True
Rule is a comment:
>>> rule = AdblockRule("!this is not a rule")
>>> rule.matching_supported({})
False
"""
if self.is_comment:
return False
if self.is_html_rule: # HTML rules are not supported yet
return False
options = options or {}
keys = set(options.keys())
if not keys.issuperset(self._options_keys):
# some of the required options are not given
return False
return True | [
"def",
"matching_supported",
"(",
"self",
",",
"options",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_comment",
":",
"return",
"False",
"if",
"self",
".",
"is_html_rule",
":",
"# HTML rules are not supported yet",
"return",
"False",
"options",
"=",
"options",
... | Return whether this rule can return meaningful result,
given the `options` dict. If some options are missing,
then rule shouldn't be matched against, and this function
returns False.
No options:
>>> rule = AdblockRule("swf|")
>>> rule.matching_supported({})
True
Option is used in the rule, but its value is not available
at matching time:
>>> rule = AdblockRule("swf|$third-party")
>>> rule.matching_supported({})
False
Option is used in the rule, and option value is available
at matching time:
>>> rule = AdblockRule("swf|$third-party")
>>> rule.matching_supported({'domain': 'example.com', 'third-party': False})
True
Rule is a comment:
>>> rule = AdblockRule("!this is not a rule")
>>> rule.matching_supported({})
False | [
"Return",
"whether",
"this",
"rule",
"can",
"return",
"meaningful",
"result",
"given",
"the",
"options",
"dict",
".",
"If",
"some",
"options",
"are",
"missing",
"then",
"rule",
"shouldn",
"t",
"be",
"matched",
"against",
"and",
"this",
"function",
"returns",
... | 4089612d65018d38dbb88dd7f697bcb07814014d | https://github.com/scrapinghub/adblockparser/blob/4089612d65018d38dbb88dd7f697bcb07814014d/adblockparser/parser.py#L156-L198 | train | 200,159 |
scrapinghub/adblockparser | adblockparser/parser.py | AdblockRule.rule_to_regex | def rule_to_regex(cls, rule):
"""
Convert AdBlock rule to a regular expression.
"""
if not rule:
return rule
# Check if the rule isn't already regexp
if rule.startswith('/') and rule.endswith('/'):
if len(rule) > 1:
rule = rule[1:-1]
else:
raise AdblockParsingError('Invalid rule')
return rule
# escape special regex characters
rule = re.sub(r"([.$+?{}()\[\]\\])", r"\\\1", rule)
# XXX: the resulting regex must use non-capturing groups (?:
# for performance reasons; also, there is a limit on number
# of capturing groups, no using them would prevent building
# a single regex out of several rules.
# Separator character ^ matches anything but a letter, a digit, or
# one of the following: _ - . %. The end of the address is also
# accepted as separator.
rule = rule.replace("^", "(?:[^\w\d_\-.%]|$)")
# * symbol
rule = rule.replace("*", ".*")
# | in the end means the end of the address
if rule[-1] == '|':
rule = rule[:-1] + '$'
# || in the beginning means beginning of the domain name
if rule[:2] == '||':
# XXX: it is better to use urlparse for such things,
# but urlparse doesn't give us a single regex.
# Regex is based on http://tools.ietf.org/html/rfc3986#appendix-B
if len(rule) > 2:
# | | complete part |
# | scheme | of the domain |
rule = r"^(?:[^:/?#]+:)?(?://(?:[^/?#]*\.)?)?" + rule[2:]
elif rule[0] == '|':
# | in the beginning means start of the address
rule = '^' + rule[1:]
# other | symbols should be escaped
# we have "|$" in our regexp - do not touch it
rule = re.sub("(\|)[^$]", r"\|", rule)
return rule | python | def rule_to_regex(cls, rule):
"""
Convert AdBlock rule to a regular expression.
"""
if not rule:
return rule
# Check if the rule isn't already regexp
if rule.startswith('/') and rule.endswith('/'):
if len(rule) > 1:
rule = rule[1:-1]
else:
raise AdblockParsingError('Invalid rule')
return rule
# escape special regex characters
rule = re.sub(r"([.$+?{}()\[\]\\])", r"\\\1", rule)
# XXX: the resulting regex must use non-capturing groups (?:
# for performance reasons; also, there is a limit on number
# of capturing groups, no using them would prevent building
# a single regex out of several rules.
# Separator character ^ matches anything but a letter, a digit, or
# one of the following: _ - . %. The end of the address is also
# accepted as separator.
rule = rule.replace("^", "(?:[^\w\d_\-.%]|$)")
# * symbol
rule = rule.replace("*", ".*")
# | in the end means the end of the address
if rule[-1] == '|':
rule = rule[:-1] + '$'
# || in the beginning means beginning of the domain name
if rule[:2] == '||':
# XXX: it is better to use urlparse for such things,
# but urlparse doesn't give us a single regex.
# Regex is based on http://tools.ietf.org/html/rfc3986#appendix-B
if len(rule) > 2:
# | | complete part |
# | scheme | of the domain |
rule = r"^(?:[^:/?#]+:)?(?://(?:[^/?#]*\.)?)?" + rule[2:]
elif rule[0] == '|':
# | in the beginning means start of the address
rule = '^' + rule[1:]
# other | symbols should be escaped
# we have "|$" in our regexp - do not touch it
rule = re.sub("(\|)[^$]", r"\|", rule)
return rule | [
"def",
"rule_to_regex",
"(",
"cls",
",",
"rule",
")",
":",
"if",
"not",
"rule",
":",
"return",
"rule",
"# Check if the rule isn't already regexp",
"if",
"rule",
".",
"startswith",
"(",
"'/'",
")",
"and",
"rule",
".",
"endswith",
"(",
"'/'",
")",
":",
"if",... | Convert AdBlock rule to a regular expression. | [
"Convert",
"AdBlock",
"rule",
"to",
"a",
"regular",
"expression",
"."
] | 4089612d65018d38dbb88dd7f697bcb07814014d | https://github.com/scrapinghub/adblockparser/blob/4089612d65018d38dbb88dd7f697bcb07814014d/adblockparser/parser.py#L221-L274 | train | 200,160 |
amsehili/auditok | auditok/core.py | StreamTokenizer.tokenize | def tokenize(self, data_source, callback=None):
"""
Read data from `data_source`, one frame a time, and process the read frames in
order to detect sequences of frames that make up valid tokens.
:Parameters:
`data_source` : instance of the :class:`DataSource` class that implements a `read` method.
'read' should return a slice of signal, i.e. frame (of whatever \
type as long as it can be processed by validator) and None if \
there is no more signal.
`callback` : an optional 3-argument function.
If a `callback` function is given, it will be called each time a valid token
is found.
:Returns:
A list of tokens if `callback` is None. Each token is tuple with the following elements:
.. code python
(data, start, end)
where `data` is a list of read frames, `start`: index of the first frame in the
original data and `end` : index of the last frame.
"""
self._reinitialize()
if callback is not None:
self._deliver = callback
while True:
frame = data_source.read()
if frame is None:
break
self._current_frame += 1
self._process(frame)
self._post_process()
if callback is None:
_ret = self._tokens
self._tokens = None
return _ret | python | def tokenize(self, data_source, callback=None):
"""
Read data from `data_source`, one frame a time, and process the read frames in
order to detect sequences of frames that make up valid tokens.
:Parameters:
`data_source` : instance of the :class:`DataSource` class that implements a `read` method.
'read' should return a slice of signal, i.e. frame (of whatever \
type as long as it can be processed by validator) and None if \
there is no more signal.
`callback` : an optional 3-argument function.
If a `callback` function is given, it will be called each time a valid token
is found.
:Returns:
A list of tokens if `callback` is None. Each token is tuple with the following elements:
.. code python
(data, start, end)
where `data` is a list of read frames, `start`: index of the first frame in the
original data and `end` : index of the last frame.
"""
self._reinitialize()
if callback is not None:
self._deliver = callback
while True:
frame = data_source.read()
if frame is None:
break
self._current_frame += 1
self._process(frame)
self._post_process()
if callback is None:
_ret = self._tokens
self._tokens = None
return _ret | [
"def",
"tokenize",
"(",
"self",
",",
"data_source",
",",
"callback",
"=",
"None",
")",
":",
"self",
".",
"_reinitialize",
"(",
")",
"if",
"callback",
"is",
"not",
"None",
":",
"self",
".",
"_deliver",
"=",
"callback",
"while",
"True",
":",
"frame",
"="... | Read data from `data_source`, one frame a time, and process the read frames in
order to detect sequences of frames that make up valid tokens.
:Parameters:
`data_source` : instance of the :class:`DataSource` class that implements a `read` method.
'read' should return a slice of signal, i.e. frame (of whatever \
type as long as it can be processed by validator) and None if \
there is no more signal.
`callback` : an optional 3-argument function.
If a `callback` function is given, it will be called each time a valid token
is found.
:Returns:
A list of tokens if `callback` is None. Each token is tuple with the following elements:
.. code python
(data, start, end)
where `data` is a list of read frames, `start`: index of the first frame in the
original data and `end` : index of the last frame. | [
"Read",
"data",
"from",
"data_source",
"one",
"frame",
"a",
"time",
"and",
"process",
"the",
"read",
"frames",
"in",
"order",
"to",
"detect",
"sequences",
"of",
"frames",
"that",
"make",
"up",
"valid",
"tokens",
"."
] | df6eb1d80f8cd9034be47b24869ce59b74f5f4db | https://github.com/amsehili/auditok/blob/df6eb1d80f8cd9034be47b24869ce59b74f5f4db/auditok/core.py#L266-L311 | train | 200,161 |
amsehili/auditok | auditok/util.py | StringDataSource.read | def read(self):
"""
Read one character from buffer.
:Returns:
Current character or None if end of buffer is reached
"""
if self._current >= len(self._data):
return None
self._current += 1
return self._data[self._current - 1] | python | def read(self):
"""
Read one character from buffer.
:Returns:
Current character or None if end of buffer is reached
"""
if self._current >= len(self._data):
return None
self._current += 1
return self._data[self._current - 1] | [
"def",
"read",
"(",
"self",
")",
":",
"if",
"self",
".",
"_current",
">=",
"len",
"(",
"self",
".",
"_data",
")",
":",
"return",
"None",
"self",
".",
"_current",
"+=",
"1",
"return",
"self",
".",
"_data",
"[",
"self",
".",
"_current",
"-",
"1",
"... | Read one character from buffer.
:Returns:
Current character or None if end of buffer is reached | [
"Read",
"one",
"character",
"from",
"buffer",
"."
] | df6eb1d80f8cd9034be47b24869ce59b74f5f4db | https://github.com/amsehili/auditok/blob/df6eb1d80f8cd9034be47b24869ce59b74f5f4db/auditok/util.py#L92-L104 | train | 200,162 |
amsehili/auditok | auditok/util.py | StringDataSource.set_data | def set_data(self, data):
"""
Set a new data buffer.
:Parameters:
`data` : a basestring object
New data buffer.
"""
if not isinstance(data, basestring):
raise ValueError("data must an instance of basestring")
self._data = data
self._current = 0 | python | def set_data(self, data):
"""
Set a new data buffer.
:Parameters:
`data` : a basestring object
New data buffer.
"""
if not isinstance(data, basestring):
raise ValueError("data must an instance of basestring")
self._data = data
self._current = 0 | [
"def",
"set_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"\"data must an instance of basestring\"",
")",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_current"... | Set a new data buffer.
:Parameters:
`data` : a basestring object
New data buffer. | [
"Set",
"a",
"new",
"data",
"buffer",
"."
] | df6eb1d80f8cd9034be47b24869ce59b74f5f4db | https://github.com/amsehili/auditok/blob/df6eb1d80f8cd9034be47b24869ce59b74f5f4db/auditok/util.py#L106-L119 | train | 200,163 |
amsehili/auditok | auditok/io.py | BufferAudioSource.set_data | def set_data(self, data_buffer):
""" Set new data for this audio stream.
:Parameters:
`data_buffer` : str, basestring, Bytes
a string buffer with a length multiple of (sample_width * channels)
"""
if len(data_buffer) % (self.sample_width * self.channels) != 0:
raise ValueError("length of data_buffer must be a multiple of (sample_width * channels)")
self._buffer = data_buffer
self._index = 0
self._left = 0 if self._buffer is None else len(self._buffer) | python | def set_data(self, data_buffer):
""" Set new data for this audio stream.
:Parameters:
`data_buffer` : str, basestring, Bytes
a string buffer with a length multiple of (sample_width * channels)
"""
if len(data_buffer) % (self.sample_width * self.channels) != 0:
raise ValueError("length of data_buffer must be a multiple of (sample_width * channels)")
self._buffer = data_buffer
self._index = 0
self._left = 0 if self._buffer is None else len(self._buffer) | [
"def",
"set_data",
"(",
"self",
",",
"data_buffer",
")",
":",
"if",
"len",
"(",
"data_buffer",
")",
"%",
"(",
"self",
".",
"sample_width",
"*",
"self",
".",
"channels",
")",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"length of data_buffer must be a multi... | Set new data for this audio stream.
:Parameters:
`data_buffer` : str, basestring, Bytes
a string buffer with a length multiple of (sample_width * channels) | [
"Set",
"new",
"data",
"for",
"this",
"audio",
"stream",
"."
] | df6eb1d80f8cd9034be47b24869ce59b74f5f4db | https://github.com/amsehili/auditok/blob/df6eb1d80f8cd9034be47b24869ce59b74f5f4db/auditok/io.py#L247-L259 | train | 200,164 |
amsehili/auditok | auditok/io.py | BufferAudioSource.append_data | def append_data(self, data_buffer):
""" Append data to this audio stream
:Parameters:
`data_buffer` : str, basestring, Bytes
a buffer with a length multiple of (sample_width * channels)
"""
if len(data_buffer) % (self.sample_width * self.channels) != 0:
raise ValueError("length of data_buffer must be a multiple of (sample_width * channels)")
self._buffer += data_buffer
self._left += len(data_buffer) | python | def append_data(self, data_buffer):
""" Append data to this audio stream
:Parameters:
`data_buffer` : str, basestring, Bytes
a buffer with a length multiple of (sample_width * channels)
"""
if len(data_buffer) % (self.sample_width * self.channels) != 0:
raise ValueError("length of data_buffer must be a multiple of (sample_width * channels)")
self._buffer += data_buffer
self._left += len(data_buffer) | [
"def",
"append_data",
"(",
"self",
",",
"data_buffer",
")",
":",
"if",
"len",
"(",
"data_buffer",
")",
"%",
"(",
"self",
".",
"sample_width",
"*",
"self",
".",
"channels",
")",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"length of data_buffer must be a mu... | Append data to this audio stream
:Parameters:
`data_buffer` : str, basestring, Bytes
a buffer with a length multiple of (sample_width * channels) | [
"Append",
"data",
"to",
"this",
"audio",
"stream"
] | df6eb1d80f8cd9034be47b24869ce59b74f5f4db | https://github.com/amsehili/auditok/blob/df6eb1d80f8cd9034be47b24869ce59b74f5f4db/auditok/io.py#L261-L274 | train | 200,165 |
pinax/django-user-accounts | account/models.py | user_post_save | def user_post_save(sender, **kwargs):
"""
After User.save is called we check to see if it was a created user. If so,
we check if the User object wants account creation. If all passes we
create an Account object.
We only run on user creation to avoid having to check for existence on
each call to User.save.
"""
# Disable post_save during manage.py loaddata
if kwargs.get("raw", False):
return False
user, created = kwargs["instance"], kwargs["created"]
disabled = getattr(user, "_disable_account_creation", not settings.ACCOUNT_CREATE_ON_SAVE)
if created and not disabled:
Account.create(user=user) | python | def user_post_save(sender, **kwargs):
"""
After User.save is called we check to see if it was a created user. If so,
we check if the User object wants account creation. If all passes we
create an Account object.
We only run on user creation to avoid having to check for existence on
each call to User.save.
"""
# Disable post_save during manage.py loaddata
if kwargs.get("raw", False):
return False
user, created = kwargs["instance"], kwargs["created"]
disabled = getattr(user, "_disable_account_creation", not settings.ACCOUNT_CREATE_ON_SAVE)
if created and not disabled:
Account.create(user=user) | [
"def",
"user_post_save",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"# Disable post_save during manage.py loaddata",
"if",
"kwargs",
".",
"get",
"(",
"\"raw\"",
",",
"False",
")",
":",
"return",
"False",
"user",
",",
"created",
"=",
"kwargs",
"[",
"\"... | After User.save is called we check to see if it was a created user. If so,
we check if the User object wants account creation. If all passes we
create an Account object.
We only run on user creation to avoid having to check for existence on
each call to User.save. | [
"After",
"User",
".",
"save",
"is",
"called",
"we",
"check",
"to",
"see",
"if",
"it",
"was",
"a",
"created",
"user",
".",
"If",
"so",
"we",
"check",
"if",
"the",
"User",
"object",
"wants",
"account",
"creation",
".",
"If",
"all",
"passes",
"we",
"cre... | ad301bd57ae65c456ed6e45ae3b5cb06d4e2378b | https://github.com/pinax/django-user-accounts/blob/ad301bd57ae65c456ed6e45ae3b5cb06d4e2378b/account/models.py#L95-L112 | train | 200,166 |
pinax/django-user-accounts | account/utils.py | check_password_expired | def check_password_expired(user):
"""
Return True if password is expired and system is using
password expiration, False otherwise.
"""
if not settings.ACCOUNT_PASSWORD_USE_HISTORY:
return False
if hasattr(user, "password_expiry"):
# user-specific value
expiry = user.password_expiry.expiry
else:
# use global value
expiry = settings.ACCOUNT_PASSWORD_EXPIRY
if expiry == 0: # zero indicates no expiration
return False
try:
# get latest password info
latest = user.password_history.latest("timestamp")
except PasswordHistory.DoesNotExist:
return False
now = datetime.datetime.now(tz=pytz.UTC)
expiration = latest.timestamp + datetime.timedelta(seconds=expiry)
if expiration < now:
return True
else:
return False | python | def check_password_expired(user):
"""
Return True if password is expired and system is using
password expiration, False otherwise.
"""
if not settings.ACCOUNT_PASSWORD_USE_HISTORY:
return False
if hasattr(user, "password_expiry"):
# user-specific value
expiry = user.password_expiry.expiry
else:
# use global value
expiry = settings.ACCOUNT_PASSWORD_EXPIRY
if expiry == 0: # zero indicates no expiration
return False
try:
# get latest password info
latest = user.password_history.latest("timestamp")
except PasswordHistory.DoesNotExist:
return False
now = datetime.datetime.now(tz=pytz.UTC)
expiration = latest.timestamp + datetime.timedelta(seconds=expiry)
if expiration < now:
return True
else:
return False | [
"def",
"check_password_expired",
"(",
"user",
")",
":",
"if",
"not",
"settings",
".",
"ACCOUNT_PASSWORD_USE_HISTORY",
":",
"return",
"False",
"if",
"hasattr",
"(",
"user",
",",
"\"password_expiry\"",
")",
":",
"# user-specific value",
"expiry",
"=",
"user",
".",
... | Return True if password is expired and system is using
password expiration, False otherwise. | [
"Return",
"True",
"if",
"password",
"is",
"expired",
"and",
"system",
"is",
"using",
"password",
"expiration",
"False",
"otherwise",
"."
] | ad301bd57ae65c456ed6e45ae3b5cb06d4e2378b | https://github.com/pinax/django-user-accounts/blob/ad301bd57ae65c456ed6e45ae3b5cb06d4e2378b/account/utils.py#L115-L145 | train | 200,167 |
pinax/django-user-accounts | account/decorators.py | login_required | def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log in page if necessary.
"""
def decorator(view_func):
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if is_authenticated(request.user):
return view_func(request, *args, **kwargs)
return handle_redirect_to_login(
request,
redirect_field_name=redirect_field_name,
login_url=login_url
)
return _wrapped_view
if func:
return decorator(func)
return decorator | python | def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log in page if necessary.
"""
def decorator(view_func):
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if is_authenticated(request.user):
return view_func(request, *args, **kwargs)
return handle_redirect_to_login(
request,
redirect_field_name=redirect_field_name,
login_url=login_url
)
return _wrapped_view
if func:
return decorator(func)
return decorator | [
"def",
"login_required",
"(",
"func",
"=",
"None",
",",
"redirect_field_name",
"=",
"REDIRECT_FIELD_NAME",
",",
"login_url",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"view_func",
",",
"assign... | Decorator for views that checks that the user is logged in, redirecting
to the log in page if necessary. | [
"Decorator",
"for",
"views",
"that",
"checks",
"that",
"the",
"user",
"is",
"logged",
"in",
"redirecting",
"to",
"the",
"log",
"in",
"page",
"if",
"necessary",
"."
] | ad301bd57ae65c456ed6e45ae3b5cb06d4e2378b | https://github.com/pinax/django-user-accounts/blob/ad301bd57ae65c456ed6e45ae3b5cb06d4e2378b/account/decorators.py#L12-L30 | train | 200,168 |
pinax/django-user-accounts | account/templatetags/account_tags.py | URLNextNode.add_next | def add_next(self, url, context):
"""
With both `redirect_field_name` and `redirect_field_value` available in
the context, add on a querystring to handle "next" redirecting.
"""
if all([key in context for key in ["redirect_field_name", "redirect_field_value"]]):
if context["redirect_field_value"]:
url += "?" + urlencode({
context["redirect_field_name"]: context["redirect_field_value"],
})
return url | python | def add_next(self, url, context):
"""
With both `redirect_field_name` and `redirect_field_value` available in
the context, add on a querystring to handle "next" redirecting.
"""
if all([key in context for key in ["redirect_field_name", "redirect_field_value"]]):
if context["redirect_field_value"]:
url += "?" + urlencode({
context["redirect_field_name"]: context["redirect_field_value"],
})
return url | [
"def",
"add_next",
"(",
"self",
",",
"url",
",",
"context",
")",
":",
"if",
"all",
"(",
"[",
"key",
"in",
"context",
"for",
"key",
"in",
"[",
"\"redirect_field_name\"",
",",
"\"redirect_field_value\"",
"]",
"]",
")",
":",
"if",
"context",
"[",
"\"redirec... | With both `redirect_field_name` and `redirect_field_value` available in
the context, add on a querystring to handle "next" redirecting. | [
"With",
"both",
"redirect_field_name",
"and",
"redirect_field_value",
"available",
"in",
"the",
"context",
"add",
"on",
"a",
"querystring",
"to",
"handle",
"next",
"redirecting",
"."
] | ad301bd57ae65c456ed6e45ae3b5cb06d4e2378b | https://github.com/pinax/django-user-accounts/blob/ad301bd57ae65c456ed6e45ae3b5cb06d4e2378b/account/templatetags/account_tags.py#L56-L66 | train | 200,169 |
ahopkins/sanic-jwt | example/custom_authentication_cls_complex.py | MyAuthentication._verify | def _verify(
self,
request,
return_payload=False,
verify=True,
raise_missing=False,
request_args=None,
request_kwargs=None,
*args,
**kwargs
):
"""
If there is a "permakey", then we will verify the token by checking the
database. Otherwise, just do the normal verification.
Typically, any method that begins with an underscore in sanic-jwt should
not be touched. In this case, we are trying to break the rules a bit to handle
a unique use case: handle both expirable and non-expirable tokens.
"""
if "permakey" in request.headers:
# Extract the permakey from the headers
permakey = request.headers.get("permakey")
# In production, probably should have some exception handling Here
# in case the permakey is an empty string or some other bad value
payload = self._decode(permakey, verify=verify)
# Sometimes, the application will call _verify(...return_payload=True)
# So, let's make sure to handle this scenario.
if return_payload:
return payload
# Retrieve the user from the database
user_id = payload.get("user_id", None)
user = userid_table.get(user_id)
# If wer cannot find a user, then this method should return
# is_valid == False
# reason == some text for why
# status == some status code, probably a 401
if not user_id or not user:
is_valid = False
reason = "No user found"
status = 401
else:
# After finding a user, make sure the permakey matches,
# or else return a bad status or some other error.
# In production, both this scenario, and the above "No user found"
# scenario should return an identical message and status code.
# This is to prevent your application accidentally
# leaking information about the existence or non-existence of users.
is_valid = user.permakey == permakey
reason = None if is_valid else "Permakey mismatch"
status = 200 if is_valid else 401
return is_valid, status, reason
else:
return super()._verify(
request=request,
return_payload=return_payload,
verify=verify,
raise_missing=raise_missing,
request_args=request_args,
request_kwargs=request_kwargs,
*args,
**kwargs
) | python | def _verify(
self,
request,
return_payload=False,
verify=True,
raise_missing=False,
request_args=None,
request_kwargs=None,
*args,
**kwargs
):
"""
If there is a "permakey", then we will verify the token by checking the
database. Otherwise, just do the normal verification.
Typically, any method that begins with an underscore in sanic-jwt should
not be touched. In this case, we are trying to break the rules a bit to handle
a unique use case: handle both expirable and non-expirable tokens.
"""
if "permakey" in request.headers:
# Extract the permakey from the headers
permakey = request.headers.get("permakey")
# In production, probably should have some exception handling Here
# in case the permakey is an empty string or some other bad value
payload = self._decode(permakey, verify=verify)
# Sometimes, the application will call _verify(...return_payload=True)
# So, let's make sure to handle this scenario.
if return_payload:
return payload
# Retrieve the user from the database
user_id = payload.get("user_id", None)
user = userid_table.get(user_id)
# If wer cannot find a user, then this method should return
# is_valid == False
# reason == some text for why
# status == some status code, probably a 401
if not user_id or not user:
is_valid = False
reason = "No user found"
status = 401
else:
# After finding a user, make sure the permakey matches,
# or else return a bad status or some other error.
# In production, both this scenario, and the above "No user found"
# scenario should return an identical message and status code.
# This is to prevent your application accidentally
# leaking information about the existence or non-existence of users.
is_valid = user.permakey == permakey
reason = None if is_valid else "Permakey mismatch"
status = 200 if is_valid else 401
return is_valid, status, reason
else:
return super()._verify(
request=request,
return_payload=return_payload,
verify=verify,
raise_missing=raise_missing,
request_args=request_args,
request_kwargs=request_kwargs,
*args,
**kwargs
) | [
"def",
"_verify",
"(",
"self",
",",
"request",
",",
"return_payload",
"=",
"False",
",",
"verify",
"=",
"True",
",",
"raise_missing",
"=",
"False",
",",
"request_args",
"=",
"None",
",",
"request_kwargs",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"... | If there is a "permakey", then we will verify the token by checking the
database. Otherwise, just do the normal verification.
Typically, any method that begins with an underscore in sanic-jwt should
not be touched. In this case, we are trying to break the rules a bit to handle
a unique use case: handle both expirable and non-expirable tokens. | [
"If",
"there",
"is",
"a",
"permakey",
"then",
"we",
"will",
"verify",
"the",
"token",
"by",
"checking",
"the",
"database",
".",
"Otherwise",
"just",
"do",
"the",
"normal",
"verification",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/example/custom_authentication_cls_complex.py#L65-L132 | train | 200,170 |
ahopkins/sanic-jwt | sanic_jwt/configuration.py | Configuration.get | def get(self, item):
"""Helper method to avoid calling getattr
"""
if item in self: # noqa
item = getattr(self, item)
return item() | python | def get(self, item):
"""Helper method to avoid calling getattr
"""
if item in self: # noqa
item = getattr(self, item)
return item() | [
"def",
"get",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"in",
"self",
":",
"# noqa",
"item",
"=",
"getattr",
"(",
"self",
",",
"item",
")",
"return",
"item",
"(",
")"
] | Helper method to avoid calling getattr | [
"Helper",
"method",
"to",
"avoid",
"calling",
"getattr"
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/configuration.py#L233-L238 | train | 200,171 |
ahopkins/sanic-jwt | sanic_jwt/configuration.py | Configuration.extract_presets | def extract_presets(app_config):
"""
Pull the application's configurations for Sanic JWT
"""
return {
x.lower()[10:]: app_config.get(x)
for x in filter(lambda x: x.startswith("SANIC_JWT"), app_config)
} | python | def extract_presets(app_config):
"""
Pull the application's configurations for Sanic JWT
"""
return {
x.lower()[10:]: app_config.get(x)
for x in filter(lambda x: x.startswith("SANIC_JWT"), app_config)
} | [
"def",
"extract_presets",
"(",
"app_config",
")",
":",
"return",
"{",
"x",
".",
"lower",
"(",
")",
"[",
"10",
":",
"]",
":",
"app_config",
".",
"get",
"(",
"x",
")",
"for",
"x",
"in",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"startswith",
"("... | Pull the application's configurations for Sanic JWT | [
"Pull",
"the",
"application",
"s",
"configurations",
"for",
"Sanic",
"JWT"
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/configuration.py#L318-L325 | train | 200,172 |
ahopkins/sanic-jwt | sanic_jwt/initialization.py | initialize | def initialize(*args, **kwargs):
"""
Functional approach to initializing Sanic JWT. This was the original
method, but was replaced by the Initialize class. It is recommended to use
the class because it is more flexible. There is no current plan to remove
this method, but it may be depracated in the future.
"""
if len(args) > 1:
kwargs.update({"authenticate": args[1]})
return Initialize(args[0], **kwargs) | python | def initialize(*args, **kwargs):
"""
Functional approach to initializing Sanic JWT. This was the original
method, but was replaced by the Initialize class. It is recommended to use
the class because it is more flexible. There is no current plan to remove
this method, but it may be depracated in the future.
"""
if len(args) > 1:
kwargs.update({"authenticate": args[1]})
return Initialize(args[0], **kwargs) | [
"def",
"initialize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"authenticate\"",
":",
"args",
"[",
"1",
"]",
"}",
")",
"return",
"Initialize",
"(",
"arg... | Functional approach to initializing Sanic JWT. This was the original
method, but was replaced by the Initialize class. It is recommended to use
the class because it is more flexible. There is no current plan to remove
this method, but it may be depracated in the future. | [
"Functional",
"approach",
"to",
"initializing",
"Sanic",
"JWT",
".",
"This",
"was",
"the",
"original",
"method",
"but",
"was",
"replaced",
"by",
"the",
"Initialize",
"class",
".",
"It",
"is",
"recommended",
"to",
"use",
"the",
"class",
"because",
"it",
"is",... | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/initialization.py#L20-L29 | train | 200,173 |
ahopkins/sanic-jwt | sanic_jwt/initialization.py | Initialize.__check_deprecated | def __check_deprecated(self):
"""
Checks for deprecated configuration keys
"""
# Depracation notices
if "SANIC_JWT_HANDLER_PAYLOAD_SCOPES" in self.app.config:
raise exceptions.InvalidConfiguration(
"SANIC_JWT_HANDLER_PAYLOAD_SCOPES has been deprecated. "
"Instead, pass your handler method (not an import path) as "
"initialize(add_scopes_to_payload=my_scope_extender)"
)
if "SANIC_JWT_PAYLOAD_HANDLER" in self.app.config:
raise exceptions.InvalidConfiguration(
"SANIC_JWT_PAYLOAD_HANDLER has been deprecated. "
"Instead, you will need to subclass Authentication. "
)
if "SANIC_JWT_HANDLER_PAYLOAD_EXTEND" in self.app.config:
raise exceptions.InvalidConfiguration(
"SANIC_JWT_HANDLER_PAYLOAD_EXTEND has been deprecated. "
"Instead, you will need to subclass Authentication. "
"Check out the documentation for more information."
) | python | def __check_deprecated(self):
"""
Checks for deprecated configuration keys
"""
# Depracation notices
if "SANIC_JWT_HANDLER_PAYLOAD_SCOPES" in self.app.config:
raise exceptions.InvalidConfiguration(
"SANIC_JWT_HANDLER_PAYLOAD_SCOPES has been deprecated. "
"Instead, pass your handler method (not an import path) as "
"initialize(add_scopes_to_payload=my_scope_extender)"
)
if "SANIC_JWT_PAYLOAD_HANDLER" in self.app.config:
raise exceptions.InvalidConfiguration(
"SANIC_JWT_PAYLOAD_HANDLER has been deprecated. "
"Instead, you will need to subclass Authentication. "
)
if "SANIC_JWT_HANDLER_PAYLOAD_EXTEND" in self.app.config:
raise exceptions.InvalidConfiguration(
"SANIC_JWT_HANDLER_PAYLOAD_EXTEND has been deprecated. "
"Instead, you will need to subclass Authentication. "
"Check out the documentation for more information."
) | [
"def",
"__check_deprecated",
"(",
"self",
")",
":",
"# Depracation notices",
"if",
"\"SANIC_JWT_HANDLER_PAYLOAD_SCOPES\"",
"in",
"self",
".",
"app",
".",
"config",
":",
"raise",
"exceptions",
".",
"InvalidConfiguration",
"(",
"\"SANIC_JWT_HANDLER_PAYLOAD_SCOPES has been dep... | Checks for deprecated configuration keys | [
"Checks",
"for",
"deprecated",
"configuration",
"keys"
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/initialization.py#L121-L144 | train | 200,174 |
ahopkins/sanic-jwt | sanic_jwt/initialization.py | Initialize.__add_endpoints | def __add_endpoints(self):
"""
Initialize the Sanic JWT Blueprint and add to the instance initialized
"""
for mapping in endpoint_mappings:
if all(map(self.config.get, mapping.keys)):
self.__add_single_endpoint(
mapping.cls, mapping.endpoint, mapping.is_protected
)
self.bp.exception(exceptions.SanicJWTException)(
self.responses.exception_response
)
if not self.instance_is_blueprint:
url_prefix = self._get_url_prefix()
self.instance.blueprint(self.bp, url_prefix=url_prefix) | python | def __add_endpoints(self):
"""
Initialize the Sanic JWT Blueprint and add to the instance initialized
"""
for mapping in endpoint_mappings:
if all(map(self.config.get, mapping.keys)):
self.__add_single_endpoint(
mapping.cls, mapping.endpoint, mapping.is_protected
)
self.bp.exception(exceptions.SanicJWTException)(
self.responses.exception_response
)
if not self.instance_is_blueprint:
url_prefix = self._get_url_prefix()
self.instance.blueprint(self.bp, url_prefix=url_prefix) | [
"def",
"__add_endpoints",
"(",
"self",
")",
":",
"for",
"mapping",
"in",
"endpoint_mappings",
":",
"if",
"all",
"(",
"map",
"(",
"self",
".",
"config",
".",
"get",
",",
"mapping",
".",
"keys",
")",
")",
":",
"self",
".",
"__add_single_endpoint",
"(",
"... | Initialize the Sanic JWT Blueprint and add to the instance initialized | [
"Initialize",
"the",
"Sanic",
"JWT",
"Blueprint",
"and",
"add",
"to",
"the",
"instance",
"initialized"
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/initialization.py#L146-L162 | train | 200,175 |
ahopkins/sanic-jwt | sanic_jwt/initialization.py | Initialize.__add_class_views | def __add_class_views(self):
"""
Include any custom class views on the Sanic JWT Blueprint
"""
config = self.config
if "class_views" in self.kwargs:
class_views = self.kwargs.pop("class_views")
for route, view in class_views:
if issubclass(view, endpoints.BaseEndpoint) and isinstance(
route, str
):
self.bp.add_route(
view.as_view(
self.responses,
config=self.config,
instance=self.instance,
),
route,
strict_slashes=config.strict_slashes(),
)
else:
raise exceptions.InvalidClassViewsFormat() | python | def __add_class_views(self):
"""
Include any custom class views on the Sanic JWT Blueprint
"""
config = self.config
if "class_views" in self.kwargs:
class_views = self.kwargs.pop("class_views")
for route, view in class_views:
if issubclass(view, endpoints.BaseEndpoint) and isinstance(
route, str
):
self.bp.add_route(
view.as_view(
self.responses,
config=self.config,
instance=self.instance,
),
route,
strict_slashes=config.strict_slashes(),
)
else:
raise exceptions.InvalidClassViewsFormat() | [
"def",
"__add_class_views",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"config",
"if",
"\"class_views\"",
"in",
"self",
".",
"kwargs",
":",
"class_views",
"=",
"self",
".",
"kwargs",
".",
"pop",
"(",
"\"class_views\"",
")",
"for",
"route",
",",
"... | Include any custom class views on the Sanic JWT Blueprint | [
"Include",
"any",
"custom",
"class",
"views",
"on",
"the",
"Sanic",
"JWT",
"Blueprint"
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/initialization.py#L164-L186 | train | 200,176 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | BaseAuthentication._get_user_id | async def _get_user_id(self, user, *, asdict=False):
"""
Get a user_id from a user object. If `asdict` is True, will return
it as a dict with `config.user_id` as key. The `asdict` keyword
defaults to `False`.
"""
uid = self.config.user_id()
if isinstance(user, dict):
user_id = user.get(uid)
elif hasattr(user, "to_dict"):
_to_dict = await utils.call(user.to_dict)
user_id = _to_dict.get(uid)
else:
raise exceptions.InvalidRetrieveUserObject()
if asdict:
return {uid: user_id}
return user_id | python | async def _get_user_id(self, user, *, asdict=False):
"""
Get a user_id from a user object. If `asdict` is True, will return
it as a dict with `config.user_id` as key. The `asdict` keyword
defaults to `False`.
"""
uid = self.config.user_id()
if isinstance(user, dict):
user_id = user.get(uid)
elif hasattr(user, "to_dict"):
_to_dict = await utils.call(user.to_dict)
user_id = _to_dict.get(uid)
else:
raise exceptions.InvalidRetrieveUserObject()
if asdict:
return {uid: user_id}
return user_id | [
"async",
"def",
"_get_user_id",
"(",
"self",
",",
"user",
",",
"*",
",",
"asdict",
"=",
"False",
")",
":",
"uid",
"=",
"self",
".",
"config",
".",
"user_id",
"(",
")",
"if",
"isinstance",
"(",
"user",
",",
"dict",
")",
":",
"user_id",
"=",
"user",
... | Get a user_id from a user object. If `asdict` is True, will return
it as a dict with `config.user_id` as key. The `asdict` keyword
defaults to `False`. | [
"Get",
"a",
"user_id",
"from",
"a",
"user",
"object",
".",
"If",
"asdict",
"is",
"True",
"will",
"return",
"it",
"as",
"a",
"dict",
"with",
"config",
".",
"user_id",
"as",
"key",
".",
"The",
"asdict",
"keyword",
"defaults",
"to",
"False",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L29-L47 | train | 200,177 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication._check_authentication | def _check_authentication(self, request, request_args, request_kwargs):
"""
Checks a request object to determine if that request contains a valid,
and authenticated JWT.
It returns a tuple:
1. Boolean whether the request is authenticated with a valid JWT
2. HTTP status code
3. Reasons (if any) for a potential authentication failure
"""
try:
is_valid, status, reasons = self._verify(
request,
request_args=request_args,
request_kwargs=request_kwargs,
)
except Exception as e:
logger.debug(e.args)
if self.config.debug():
raise e
args = e.args if isinstance(e, SanicJWTException) else []
raise exceptions.Unauthorized(*args)
return is_valid, status, reasons | python | def _check_authentication(self, request, request_args, request_kwargs):
"""
Checks a request object to determine if that request contains a valid,
and authenticated JWT.
It returns a tuple:
1. Boolean whether the request is authenticated with a valid JWT
2. HTTP status code
3. Reasons (if any) for a potential authentication failure
"""
try:
is_valid, status, reasons = self._verify(
request,
request_args=request_args,
request_kwargs=request_kwargs,
)
except Exception as e:
logger.debug(e.args)
if self.config.debug():
raise e
args = e.args if isinstance(e, SanicJWTException) else []
raise exceptions.Unauthorized(*args)
return is_valid, status, reasons | [
"def",
"_check_authentication",
"(",
"self",
",",
"request",
",",
"request_args",
",",
"request_kwargs",
")",
":",
"try",
":",
"is_valid",
",",
"status",
",",
"reasons",
"=",
"self",
".",
"_verify",
"(",
"request",
",",
"request_args",
"=",
"request_args",
"... | Checks a request object to determine if that request contains a valid,
and authenticated JWT.
It returns a tuple:
1. Boolean whether the request is authenticated with a valid JWT
2. HTTP status code
3. Reasons (if any) for a potential authentication failure | [
"Checks",
"a",
"request",
"object",
"to",
"determine",
"if",
"that",
"request",
"contains",
"a",
"valid",
"and",
"authenticated",
"JWT",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L117-L142 | train | 200,178 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication._decode | def _decode(self, token, verify=True):
"""
Take a JWT and return a decoded payload. Optionally, will verify
the claims on the token.
"""
secret = self._get_secret()
algorithm = self._get_algorithm()
kwargs = {}
for claim in self.claims:
if claim != "exp":
setting = "claim_{}".format(claim.lower())
if setting in self.config: # noqa
value = self.config.get(setting)
kwargs.update({claim_label[claim]: value})
kwargs["leeway"] = int(self.config.leeway())
if "claim_aud" in self.config: # noqa
kwargs["audience"] = self.config.claim_aud()
if "claim_iss" in self.config: # noqa
kwargs["issuer"] = self.config.claim_iss()
decoded = jwt.decode(
token,
secret,
algorithms=[algorithm],
verify=verify,
options={"verify_exp": self.config.verify_exp()},
**kwargs
)
return decoded | python | def _decode(self, token, verify=True):
"""
Take a JWT and return a decoded payload. Optionally, will verify
the claims on the token.
"""
secret = self._get_secret()
algorithm = self._get_algorithm()
kwargs = {}
for claim in self.claims:
if claim != "exp":
setting = "claim_{}".format(claim.lower())
if setting in self.config: # noqa
value = self.config.get(setting)
kwargs.update({claim_label[claim]: value})
kwargs["leeway"] = int(self.config.leeway())
if "claim_aud" in self.config: # noqa
kwargs["audience"] = self.config.claim_aud()
if "claim_iss" in self.config: # noqa
kwargs["issuer"] = self.config.claim_iss()
decoded = jwt.decode(
token,
secret,
algorithms=[algorithm],
verify=verify,
options={"verify_exp": self.config.verify_exp()},
**kwargs
)
return decoded | [
"def",
"_decode",
"(",
"self",
",",
"token",
",",
"verify",
"=",
"True",
")",
":",
"secret",
"=",
"self",
".",
"_get_secret",
"(",
")",
"algorithm",
"=",
"self",
".",
"_get_algorithm",
"(",
")",
"kwargs",
"=",
"{",
"}",
"for",
"claim",
"in",
"self",
... | Take a JWT and return a decoded payload. Optionally, will verify
the claims on the token. | [
"Take",
"a",
"JWT",
"and",
"return",
"a",
"decoded",
"payload",
".",
"Optionally",
"will",
"verify",
"the",
"claims",
"on",
"the",
"token",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L144-L174 | train | 200,179 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication._get_payload | async def _get_payload(self, user):
"""
Given a user object, create a payload and extend it as configured.
"""
payload = await utils.call(self.build_payload, user)
if (
not isinstance(payload, dict)
or self.config.user_id() not in payload
):
raise exceptions.InvalidPayload
payload = await utils.call(self.add_claims, payload, user)
extend_payload_args = inspect.getfullargspec(self.extend_payload)
args = [payload]
if "user" in extend_payload_args.args:
args.append(user)
payload = await utils.call(self.extend_payload, *args)
if self.config.scopes_enabled():
scopes = await utils.call(self.add_scopes_to_payload, user)
if not isinstance(scopes, (tuple, list)):
scopes = [scopes]
payload[self.config.scopes_name()] = scopes
claims = self.claims + [x.get_key() for x in self._custom_claims]
missing = [x for x in claims if x not in payload]
if missing:
logger.debug("")
raise exceptions.MissingRegisteredClaim(missing=missing)
return payload | python | async def _get_payload(self, user):
"""
Given a user object, create a payload and extend it as configured.
"""
payload = await utils.call(self.build_payload, user)
if (
not isinstance(payload, dict)
or self.config.user_id() not in payload
):
raise exceptions.InvalidPayload
payload = await utils.call(self.add_claims, payload, user)
extend_payload_args = inspect.getfullargspec(self.extend_payload)
args = [payload]
if "user" in extend_payload_args.args:
args.append(user)
payload = await utils.call(self.extend_payload, *args)
if self.config.scopes_enabled():
scopes = await utils.call(self.add_scopes_to_payload, user)
if not isinstance(scopes, (tuple, list)):
scopes = [scopes]
payload[self.config.scopes_name()] = scopes
claims = self.claims + [x.get_key() for x in self._custom_claims]
missing = [x for x in claims if x not in payload]
if missing:
logger.debug("")
raise exceptions.MissingRegisteredClaim(missing=missing)
return payload | [
"async",
"def",
"_get_payload",
"(",
"self",
",",
"user",
")",
":",
"payload",
"=",
"await",
"utils",
".",
"call",
"(",
"self",
".",
"build_payload",
",",
"user",
")",
"if",
"(",
"not",
"isinstance",
"(",
"payload",
",",
"dict",
")",
"or",
"self",
".... | Given a user object, create a payload and extend it as configured. | [
"Given",
"a",
"user",
"object",
"create",
"a",
"payload",
"and",
"extend",
"it",
"as",
"configured",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L179-L211 | train | 200,180 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication._get_token_from_cookies | def _get_token_from_cookies(self, request, refresh_token):
"""
Extract the token if present inside the request cookies.
"""
if refresh_token:
cookie_token_name_key = "cookie_refresh_token_name"
else:
cookie_token_name_key = "cookie_access_token_name"
cookie_token_name = getattr(self.config, cookie_token_name_key)
return request.cookies.get(cookie_token_name(), None) | python | def _get_token_from_cookies(self, request, refresh_token):
"""
Extract the token if present inside the request cookies.
"""
if refresh_token:
cookie_token_name_key = "cookie_refresh_token_name"
else:
cookie_token_name_key = "cookie_access_token_name"
cookie_token_name = getattr(self.config, cookie_token_name_key)
return request.cookies.get(cookie_token_name(), None) | [
"def",
"_get_token_from_cookies",
"(",
"self",
",",
"request",
",",
"refresh_token",
")",
":",
"if",
"refresh_token",
":",
"cookie_token_name_key",
"=",
"\"cookie_refresh_token_name\"",
"else",
":",
"cookie_token_name_key",
"=",
"\"cookie_access_token_name\"",
"cookie_token... | Extract the token if present inside the request cookies. | [
"Extract",
"the",
"token",
"if",
"present",
"inside",
"the",
"request",
"cookies",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L231-L240 | train | 200,181 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication._get_token_from_headers | def _get_token_from_headers(self, request, refresh_token):
"""
Extract the token if present inside the headers of a request.
"""
header = request.headers.get(self.config.authorization_header(), None)
if header is None:
return None
else:
header_prefix_key = "authorization_header_prefix"
header_prefix = getattr(self.config, header_prefix_key)
if header_prefix():
try:
prefix, token = header.split(" ")
if prefix != header_prefix():
raise Exception
except Exception:
raise exceptions.InvalidAuthorizationHeader()
else:
token = header
if refresh_token:
token = request.json.get(self.config.refresh_token_name())
return token | python | def _get_token_from_headers(self, request, refresh_token):
"""
Extract the token if present inside the headers of a request.
"""
header = request.headers.get(self.config.authorization_header(), None)
if header is None:
return None
else:
header_prefix_key = "authorization_header_prefix"
header_prefix = getattr(self.config, header_prefix_key)
if header_prefix():
try:
prefix, token = header.split(" ")
if prefix != header_prefix():
raise Exception
except Exception:
raise exceptions.InvalidAuthorizationHeader()
else:
token = header
if refresh_token:
token = request.json.get(self.config.refresh_token_name())
return token | [
"def",
"_get_token_from_headers",
"(",
"self",
",",
"request",
",",
"refresh_token",
")",
":",
"header",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"self",
".",
"config",
".",
"authorization_header",
"(",
")",
",",
"None",
")",
"if",
"header",
"is",
... | Extract the token if present inside the headers of a request. | [
"Extract",
"the",
"token",
"if",
"present",
"inside",
"the",
"headers",
"of",
"a",
"request",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L242-L269 | train | 200,182 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication._get_token_from_query_string | def _get_token_from_query_string(self, request, refresh_token):
"""
Extract the token if present from the request args.
"""
if refresh_token:
query_string_token_name_key = "query_string_refresh_token_name"
else:
query_string_token_name_key = "query_string_access_token_name"
query_string_token_name = getattr(
self.config, query_string_token_name_key
)
return request.args.get(query_string_token_name(), None) | python | def _get_token_from_query_string(self, request, refresh_token):
"""
Extract the token if present from the request args.
"""
if refresh_token:
query_string_token_name_key = "query_string_refresh_token_name"
else:
query_string_token_name_key = "query_string_access_token_name"
query_string_token_name = getattr(
self.config, query_string_token_name_key
)
return request.args.get(query_string_token_name(), None) | [
"def",
"_get_token_from_query_string",
"(",
"self",
",",
"request",
",",
"refresh_token",
")",
":",
"if",
"refresh_token",
":",
"query_string_token_name_key",
"=",
"\"query_string_refresh_token_name\"",
"else",
":",
"query_string_token_name_key",
"=",
"\"query_string_access_t... | Extract the token if present from the request args. | [
"Extract",
"the",
"token",
"if",
"present",
"from",
"the",
"request",
"args",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L271-L282 | train | 200,183 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication._get_token | def _get_token(self, request, refresh_token=False):
"""
Extract a token from a request object.
"""
if self.config.cookie_set():
token = self._get_token_from_cookies(request, refresh_token)
if token:
return token
else:
if self.config.cookie_strict():
raise exceptions.MissingAuthorizationCookie()
if self.config.query_string_set():
token = self._get_token_from_query_string(request, refresh_token)
if token:
return token
else:
if self.config.query_string_strict():
raise exceptions.MissingAuthorizationQueryArg()
token = self._get_token_from_headers(request, refresh_token)
if token:
return token
raise exceptions.MissingAuthorizationHeader() | python | def _get_token(self, request, refresh_token=False):
"""
Extract a token from a request object.
"""
if self.config.cookie_set():
token = self._get_token_from_cookies(request, refresh_token)
if token:
return token
else:
if self.config.cookie_strict():
raise exceptions.MissingAuthorizationCookie()
if self.config.query_string_set():
token = self._get_token_from_query_string(request, refresh_token)
if token:
return token
else:
if self.config.query_string_strict():
raise exceptions.MissingAuthorizationQueryArg()
token = self._get_token_from_headers(request, refresh_token)
if token:
return token
raise exceptions.MissingAuthorizationHeader() | [
"def",
"_get_token",
"(",
"self",
",",
"request",
",",
"refresh_token",
"=",
"False",
")",
":",
"if",
"self",
".",
"config",
".",
"cookie_set",
"(",
")",
":",
"token",
"=",
"self",
".",
"_get_token_from_cookies",
"(",
"request",
",",
"refresh_token",
")",
... | Extract a token from a request object. | [
"Extract",
"a",
"token",
"from",
"a",
"request",
"object",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L284-L311 | train | 200,184 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication._verify | def _verify(
self,
request,
return_payload=False,
verify=True,
raise_missing=False,
request_args=None,
request_kwargs=None,
*args,
**kwargs
):
"""
Verify that a request object is authenticated.
"""
try:
token = self._get_token(request)
is_valid = True
reason = None
except (
exceptions.MissingAuthorizationCookie,
exceptions.MissingAuthorizationQueryArg,
exceptions.MissingAuthorizationHeader,
) as e:
token = None
is_valid = False
reason = list(e.args)
status = e.status_code if self.config.debug() else 401
if raise_missing:
if not self.config.debug():
e.status_code = 401
raise e
if token:
try:
payload = self._decode(token, verify=verify)
if verify:
if self._extra_verifications:
self._verify_extras(payload)
if self._custom_claims:
self._verify_custom_claims(payload)
except (
jwt.exceptions.ExpiredSignatureError,
jwt.exceptions.InvalidIssuerError,
jwt.exceptions.ImmatureSignatureError,
jwt.exceptions.InvalidIssuedAtError,
jwt.exceptions.InvalidAudienceError,
InvalidVerificationError,
InvalidCustomClaimError,
) as e:
# Make sure that the reasons all end with '.' for consistency
reason = [
x if x.endswith(".") else "{}.".format(x)
for x in list(e.args)
]
payload = None
status = 401
is_valid = False
except jwt.exceptions.DecodeError as e:
self._reasons = e.args
# Make sure that the reasons all end with '.' for consistency
reason = (
[
x if x.endswith(".") else "{}.".format(x)
for x in list(e.args)
]
if self.config.debug()
else "Auth required."
)
logger.debug(e.args)
is_valid = False
payload = None
status = 400 if self.config.debug() else 401
else:
payload = None
if return_payload:
return payload
status = 200 if is_valid else status
return is_valid, status, reason | python | def _verify(
self,
request,
return_payload=False,
verify=True,
raise_missing=False,
request_args=None,
request_kwargs=None,
*args,
**kwargs
):
"""
Verify that a request object is authenticated.
"""
try:
token = self._get_token(request)
is_valid = True
reason = None
except (
exceptions.MissingAuthorizationCookie,
exceptions.MissingAuthorizationQueryArg,
exceptions.MissingAuthorizationHeader,
) as e:
token = None
is_valid = False
reason = list(e.args)
status = e.status_code if self.config.debug() else 401
if raise_missing:
if not self.config.debug():
e.status_code = 401
raise e
if token:
try:
payload = self._decode(token, verify=verify)
if verify:
if self._extra_verifications:
self._verify_extras(payload)
if self._custom_claims:
self._verify_custom_claims(payload)
except (
jwt.exceptions.ExpiredSignatureError,
jwt.exceptions.InvalidIssuerError,
jwt.exceptions.ImmatureSignatureError,
jwt.exceptions.InvalidIssuedAtError,
jwt.exceptions.InvalidAudienceError,
InvalidVerificationError,
InvalidCustomClaimError,
) as e:
# Make sure that the reasons all end with '.' for consistency
reason = [
x if x.endswith(".") else "{}.".format(x)
for x in list(e.args)
]
payload = None
status = 401
is_valid = False
except jwt.exceptions.DecodeError as e:
self._reasons = e.args
# Make sure that the reasons all end with '.' for consistency
reason = (
[
x if x.endswith(".") else "{}.".format(x)
for x in list(e.args)
]
if self.config.debug()
else "Auth required."
)
logger.debug(e.args)
is_valid = False
payload = None
status = 400 if self.config.debug() else 401
else:
payload = None
if return_payload:
return payload
status = 200 if is_valid else status
return is_valid, status, reason | [
"def",
"_verify",
"(",
"self",
",",
"request",
",",
"return_payload",
"=",
"False",
",",
"verify",
"=",
"True",
",",
"raise_missing",
"=",
"False",
",",
"request_args",
"=",
"None",
",",
"request_kwargs",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"... | Verify that a request object is authenticated. | [
"Verify",
"that",
"a",
"request",
"object",
"is",
"authenticated",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L313-L395 | train | 200,185 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication.extract_payload | def extract_payload(self, request, verify=True, *args, **kwargs):
"""
Extract a payload from a request object.
"""
payload = self._verify(
request, return_payload=True, verify=verify, *args, **kwargs
)
return payload | python | def extract_payload(self, request, verify=True, *args, **kwargs):
"""
Extract a payload from a request object.
"""
payload = self._verify(
request, return_payload=True, verify=verify, *args, **kwargs
)
return payload | [
"def",
"extract_payload",
"(",
"self",
",",
"request",
",",
"verify",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"self",
".",
"_verify",
"(",
"request",
",",
"return_payload",
"=",
"True",
",",
"verify",
"=",
"v... | Extract a payload from a request object. | [
"Extract",
"a",
"payload",
"from",
"a",
"request",
"object",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L413-L420 | train | 200,186 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication.extract_scopes | def extract_scopes(self, request):
"""
Extract scopes from a request object.
"""
payload = self.extract_payload(request)
if not payload:
return None
scopes_attribute = self.config.scopes_name()
return payload.get(scopes_attribute, None) | python | def extract_scopes(self, request):
"""
Extract scopes from a request object.
"""
payload = self.extract_payload(request)
if not payload:
return None
scopes_attribute = self.config.scopes_name()
return payload.get(scopes_attribute, None) | [
"def",
"extract_scopes",
"(",
"self",
",",
"request",
")",
":",
"payload",
"=",
"self",
".",
"extract_payload",
"(",
"request",
")",
"if",
"not",
"payload",
":",
"return",
"None",
"scopes_attribute",
"=",
"self",
".",
"config",
".",
"scopes_name",
"(",
")"... | Extract scopes from a request object. | [
"Extract",
"scopes",
"from",
"a",
"request",
"object",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L422-L431 | train | 200,187 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication.extract_user_id | def extract_user_id(self, request):
"""
Extract a user id from a request object.
"""
payload = self.extract_payload(request)
user_id_attribute = self.config.user_id()
return payload.get(user_id_attribute, None) | python | def extract_user_id(self, request):
"""
Extract a user id from a request object.
"""
payload = self.extract_payload(request)
user_id_attribute = self.config.user_id()
return payload.get(user_id_attribute, None) | [
"def",
"extract_user_id",
"(",
"self",
",",
"request",
")",
":",
"payload",
"=",
"self",
".",
"extract_payload",
"(",
"request",
")",
"user_id_attribute",
"=",
"self",
".",
"config",
".",
"user_id",
"(",
")",
"return",
"payload",
".",
"get",
"(",
"user_id_... | Extract a user id from a request object. | [
"Extract",
"a",
"user",
"id",
"from",
"a",
"request",
"object",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L433-L439 | train | 200,188 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication.generate_access_token | async def generate_access_token(self, user):
"""
Generate an access token for a given user.
"""
payload = await self._get_payload(user)
secret = self._get_secret(True)
algorithm = self._get_algorithm()
return jwt.encode(payload, secret, algorithm=algorithm).decode("utf-8") | python | async def generate_access_token(self, user):
"""
Generate an access token for a given user.
"""
payload = await self._get_payload(user)
secret = self._get_secret(True)
algorithm = self._get_algorithm()
return jwt.encode(payload, secret, algorithm=algorithm).decode("utf-8") | [
"async",
"def",
"generate_access_token",
"(",
"self",
",",
"user",
")",
":",
"payload",
"=",
"await",
"self",
".",
"_get_payload",
"(",
"user",
")",
"secret",
"=",
"self",
".",
"_get_secret",
"(",
"True",
")",
"algorithm",
"=",
"self",
".",
"_get_algorithm... | Generate an access token for a given user. | [
"Generate",
"an",
"access",
"token",
"for",
"a",
"given",
"user",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L441-L449 | train | 200,189 |
ahopkins/sanic-jwt | sanic_jwt/authentication.py | Authentication.generate_refresh_token | async def generate_refresh_token(self, request, user):
"""
Generate a refresh token for a given user.
"""
refresh_token = await utils.call(self.config.generate_refresh_token())
user_id = await self._get_user_id(user)
await utils.call(
self.store_refresh_token,
user_id=user_id,
refresh_token=refresh_token,
request=request,
)
return refresh_token | python | async def generate_refresh_token(self, request, user):
"""
Generate a refresh token for a given user.
"""
refresh_token = await utils.call(self.config.generate_refresh_token())
user_id = await self._get_user_id(user)
await utils.call(
self.store_refresh_token,
user_id=user_id,
refresh_token=refresh_token,
request=request,
)
return refresh_token | [
"async",
"def",
"generate_refresh_token",
"(",
"self",
",",
"request",
",",
"user",
")",
":",
"refresh_token",
"=",
"await",
"utils",
".",
"call",
"(",
"self",
".",
"config",
".",
"generate_refresh_token",
"(",
")",
")",
"user_id",
"=",
"await",
"self",
".... | Generate a refresh token for a given user. | [
"Generate",
"a",
"refresh",
"token",
"for",
"a",
"given",
"user",
"."
] | fca7750499c8cedde823d778512f613777fb5282 | https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L451-L463 | train | 200,190 |
rushter/heamy | heamy/utils/main.py | tsplit | def tsplit(df, shape):
"""Split array into two parts."""
if isinstance(df, (pd.DataFrame, pd.Series)):
return df.iloc[0:shape], df.iloc[shape:]
else:
return df[0:shape], df[shape:] | python | def tsplit(df, shape):
"""Split array into two parts."""
if isinstance(df, (pd.DataFrame, pd.Series)):
return df.iloc[0:shape], df.iloc[shape:]
else:
return df[0:shape], df[shape:] | [
"def",
"tsplit",
"(",
"df",
",",
"shape",
")",
":",
"if",
"isinstance",
"(",
"df",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"return",
"df",
".",
"iloc",
"[",
"0",
":",
"shape",
"]",
",",
"df",
".",
"iloc",
"[... | Split array into two parts. | [
"Split",
"array",
"into",
"two",
"parts",
"."
] | c330854cee3c547417eb353a4a4a23331b40b4bc | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/utils/main.py#L29-L34 | train | 200,191 |
rushter/heamy | heamy/utils/main.py | concat | def concat(x, y, axis=0):
"""Concatenate a sequence of pandas or numpy objects into one entity."""
if all([isinstance(df, (pd.DataFrame, pd.Series)) for df in [x, y]]):
return pd.concat([x, y], axis=axis)
else:
if axis == 0:
return np.concatenate([x, y])
else:
return np.column_stack([x, y]) | python | def concat(x, y, axis=0):
"""Concatenate a sequence of pandas or numpy objects into one entity."""
if all([isinstance(df, (pd.DataFrame, pd.Series)) for df in [x, y]]):
return pd.concat([x, y], axis=axis)
else:
if axis == 0:
return np.concatenate([x, y])
else:
return np.column_stack([x, y]) | [
"def",
"concat",
"(",
"x",
",",
"y",
",",
"axis",
"=",
"0",
")",
":",
"if",
"all",
"(",
"[",
"isinstance",
"(",
"df",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
"for",
"df",
"in",
"[",
"x",
",",
"y",
"]",
"]",
"... | Concatenate a sequence of pandas or numpy objects into one entity. | [
"Concatenate",
"a",
"sequence",
"of",
"pandas",
"or",
"numpy",
"objects",
"into",
"one",
"entity",
"."
] | c330854cee3c547417eb353a4a4a23331b40b4bc | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/utils/main.py#L37-L45 | train | 200,192 |
rushter/heamy | heamy/utils/main.py | reshape_1d | def reshape_1d(df):
"""If parameter is 1D row vector then convert it into 2D matrix."""
shape = df.shape
if len(shape) == 1:
return df.reshape(shape[0], 1)
else:
return df | python | def reshape_1d(df):
"""If parameter is 1D row vector then convert it into 2D matrix."""
shape = df.shape
if len(shape) == 1:
return df.reshape(shape[0], 1)
else:
return df | [
"def",
"reshape_1d",
"(",
"df",
")",
":",
"shape",
"=",
"df",
".",
"shape",
"if",
"len",
"(",
"shape",
")",
"==",
"1",
":",
"return",
"df",
".",
"reshape",
"(",
"shape",
"[",
"0",
"]",
",",
"1",
")",
"else",
":",
"return",
"df"
] | If parameter is 1D row vector then convert it into 2D matrix. | [
"If",
"parameter",
"is",
"1D",
"row",
"vector",
"then",
"convert",
"it",
"into",
"2D",
"matrix",
"."
] | c330854cee3c547417eb353a4a4a23331b40b4bc | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/utils/main.py#L48-L54 | train | 200,193 |
rushter/heamy | heamy/utils/main.py | idx | def idx(df, index):
"""Universal indexing for numpy and pandas objects."""
if isinstance(df, (pd.DataFrame, pd.Series)):
return df.iloc[index]
else:
return df[index, :] | python | def idx(df, index):
"""Universal indexing for numpy and pandas objects."""
if isinstance(df, (pd.DataFrame, pd.Series)):
return df.iloc[index]
else:
return df[index, :] | [
"def",
"idx",
"(",
"df",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"df",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"return",
"df",
".",
"iloc",
"[",
"index",
"]",
"else",
":",
"return",
"df",
"[",
"index"... | Universal indexing for numpy and pandas objects. | [
"Universal",
"indexing",
"for",
"numpy",
"and",
"pandas",
"objects",
"."
] | c330854cee3c547417eb353a4a4a23331b40b4bc | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/utils/main.py#L57-L62 | train | 200,194 |
rushter/heamy | heamy/utils/main.py | xgb_progressbar | def xgb_progressbar(rounds=1000):
"""Progressbar for xgboost using tqdm library.
Examples
--------
>>> model = xgb.train(params, X_train, 1000, callbacks=[xgb_progress(1000), ])
"""
pbar = tqdm(total=rounds)
def callback(_, ):
pbar.update(1)
return callback | python | def xgb_progressbar(rounds=1000):
"""Progressbar for xgboost using tqdm library.
Examples
--------
>>> model = xgb.train(params, X_train, 1000, callbacks=[xgb_progress(1000), ])
"""
pbar = tqdm(total=rounds)
def callback(_, ):
pbar.update(1)
return callback | [
"def",
"xgb_progressbar",
"(",
"rounds",
"=",
"1000",
")",
":",
"pbar",
"=",
"tqdm",
"(",
"total",
"=",
"rounds",
")",
"def",
"callback",
"(",
"_",
",",
")",
":",
"pbar",
".",
"update",
"(",
"1",
")",
"return",
"callback"
] | Progressbar for xgboost using tqdm library.
Examples
--------
>>> model = xgb.train(params, X_train, 1000, callbacks=[xgb_progress(1000), ]) | [
"Progressbar",
"for",
"xgboost",
"using",
"tqdm",
"library",
"."
] | c330854cee3c547417eb353a4a4a23331b40b4bc | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/utils/main.py#L101-L114 | train | 200,195 |
rushter/heamy | heamy/pipeline.py | ModelsPipeline.add | def add(self, model):
"""Adds a single model.
Parameters
----------
model : `Estimator`
"""
if isinstance(model, (Regressor, Classifier)):
self.models.append(model)
else:
raise ValueError('Unrecognized estimator.') | python | def add(self, model):
"""Adds a single model.
Parameters
----------
model : `Estimator`
"""
if isinstance(model, (Regressor, Classifier)):
self.models.append(model)
else:
raise ValueError('Unrecognized estimator.') | [
"def",
"add",
"(",
"self",
",",
"model",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"(",
"Regressor",
",",
"Classifier",
")",
")",
":",
"self",
".",
"models",
".",
"append",
"(",
"model",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unrecogn... | Adds a single model.
Parameters
----------
model : `Estimator` | [
"Adds",
"a",
"single",
"model",
"."
] | c330854cee3c547417eb353a4a4a23331b40b4bc | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/pipeline.py#L25-L35 | train | 200,196 |
rushter/heamy | heamy/pipeline.py | ModelsPipeline.stack | def stack(self, k=5, stratify=False, shuffle=True, seed=100, full_test=True, add_diff=False):
"""Stacks sequence of models.
Parameters
----------
k : int, default 5
Number of folds.
stratify : bool, default False
shuffle : bool, default True
seed : int, default 100
full_test : bool, default True
If True then evaluate test dataset on the full data otherwise take the mean of every fold.
add_diff : bool, default False
Returns
-------
`DataFrame`
Examples
--------
>>> pipeline = ModelsPipeline(model_rf,model_lr)
>>> stack_ds = pipeline.stack(k=10, seed=111)
"""
result_train = []
result_test = []
y = None
for model in self.models:
result = model.stack(k=k, stratify=stratify, shuffle=shuffle, seed=seed, full_test=full_test)
train_df = pd.DataFrame(result.X_train, columns=generate_columns(result.X_train, model.name))
test_df = pd.DataFrame(result.X_test, columns=generate_columns(result.X_test, model.name))
result_train.append(train_df)
result_test.append(test_df)
if y is None:
y = result.y_train
result_train = pd.concat(result_train, axis=1)
result_test = pd.concat(result_test, axis=1)
if add_diff:
result_train = feature_combiner(result_train)
result_test = feature_combiner(result_test)
ds = Dataset(X_train=result_train, y_train=y, X_test=result_test)
return ds | python | def stack(self, k=5, stratify=False, shuffle=True, seed=100, full_test=True, add_diff=False):
"""Stacks sequence of models.
Parameters
----------
k : int, default 5
Number of folds.
stratify : bool, default False
shuffle : bool, default True
seed : int, default 100
full_test : bool, default True
If True then evaluate test dataset on the full data otherwise take the mean of every fold.
add_diff : bool, default False
Returns
-------
`DataFrame`
Examples
--------
>>> pipeline = ModelsPipeline(model_rf,model_lr)
>>> stack_ds = pipeline.stack(k=10, seed=111)
"""
result_train = []
result_test = []
y = None
for model in self.models:
result = model.stack(k=k, stratify=stratify, shuffle=shuffle, seed=seed, full_test=full_test)
train_df = pd.DataFrame(result.X_train, columns=generate_columns(result.X_train, model.name))
test_df = pd.DataFrame(result.X_test, columns=generate_columns(result.X_test, model.name))
result_train.append(train_df)
result_test.append(test_df)
if y is None:
y = result.y_train
result_train = pd.concat(result_train, axis=1)
result_test = pd.concat(result_test, axis=1)
if add_diff:
result_train = feature_combiner(result_train)
result_test = feature_combiner(result_test)
ds = Dataset(X_train=result_train, y_train=y, X_test=result_test)
return ds | [
"def",
"stack",
"(",
"self",
",",
"k",
"=",
"5",
",",
"stratify",
"=",
"False",
",",
"shuffle",
"=",
"True",
",",
"seed",
"=",
"100",
",",
"full_test",
"=",
"True",
",",
"add_diff",
"=",
"False",
")",
":",
"result_train",
"=",
"[",
"]",
"result_tes... | Stacks sequence of models.
Parameters
----------
k : int, default 5
Number of folds.
stratify : bool, default False
shuffle : bool, default True
seed : int, default 100
full_test : bool, default True
If True then evaluate test dataset on the full data otherwise take the mean of every fold.
add_diff : bool, default False
Returns
-------
`DataFrame`
Examples
--------
>>> pipeline = ModelsPipeline(model_rf,model_lr)
>>> stack_ds = pipeline.stack(k=10, seed=111) | [
"Stacks",
"sequence",
"of",
"models",
"."
] | c330854cee3c547417eb353a4a4a23331b40b4bc | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/pipeline.py#L104-L150 | train | 200,197 |
rushter/heamy | heamy/pipeline.py | ModelsPipeline.blend | def blend(self, proportion=0.2, stratify=False, seed=100, indices=None, add_diff=False):
"""Blends sequence of models.
Parameters
----------
proportion : float, default 0.2
stratify : bool, default False
seed : int, default False
indices : list(np.ndarray,np.ndarray), default None
Two numpy arrays that contain indices for train/test slicing.
add_diff : bool, default False
Returns
-------
`DataFrame`
Examples
--------
>>> pipeline = ModelsPipeline(model_rf,model_lr)
>>> pipeline.blend(seed=15)
>>> # Custom indices
>>> train_index = np.array(range(250))
>>> test_index = np.array(range(250,333))
>>> res = model_rf.blend(indicies=(train_index,test_index))
"""
result_train = []
result_test = []
y = None
for model in self.models:
result = model.blend(proportion=proportion, stratify=stratify, seed=seed, indices=indices)
train_df = pd.DataFrame(result.X_train, columns=generate_columns(result.X_train, model.name))
test_df = pd.DataFrame(result.X_test, columns=generate_columns(result.X_test, model.name))
result_train.append(train_df)
result_test.append(test_df)
if y is None:
y = result.y_train
result_train = pd.concat(result_train, axis=1, ignore_index=True)
result_test = pd.concat(result_test, axis=1, ignore_index=True)
if add_diff:
result_train = feature_combiner(result_train)
result_test = feature_combiner(result_test)
return Dataset(X_train=result_train, y_train=y, X_test=result_test) | python | def blend(self, proportion=0.2, stratify=False, seed=100, indices=None, add_diff=False):
"""Blends sequence of models.
Parameters
----------
proportion : float, default 0.2
stratify : bool, default False
seed : int, default False
indices : list(np.ndarray,np.ndarray), default None
Two numpy arrays that contain indices for train/test slicing.
add_diff : bool, default False
Returns
-------
`DataFrame`
Examples
--------
>>> pipeline = ModelsPipeline(model_rf,model_lr)
>>> pipeline.blend(seed=15)
>>> # Custom indices
>>> train_index = np.array(range(250))
>>> test_index = np.array(range(250,333))
>>> res = model_rf.blend(indicies=(train_index,test_index))
"""
result_train = []
result_test = []
y = None
for model in self.models:
result = model.blend(proportion=proportion, stratify=stratify, seed=seed, indices=indices)
train_df = pd.DataFrame(result.X_train, columns=generate_columns(result.X_train, model.name))
test_df = pd.DataFrame(result.X_test, columns=generate_columns(result.X_test, model.name))
result_train.append(train_df)
result_test.append(test_df)
if y is None:
y = result.y_train
result_train = pd.concat(result_train, axis=1, ignore_index=True)
result_test = pd.concat(result_test, axis=1, ignore_index=True)
if add_diff:
result_train = feature_combiner(result_train)
result_test = feature_combiner(result_test)
return Dataset(X_train=result_train, y_train=y, X_test=result_test) | [
"def",
"blend",
"(",
"self",
",",
"proportion",
"=",
"0.2",
",",
"stratify",
"=",
"False",
",",
"seed",
"=",
"100",
",",
"indices",
"=",
"None",
",",
"add_diff",
"=",
"False",
")",
":",
"result_train",
"=",
"[",
"]",
"result_test",
"=",
"[",
"]",
"... | Blends sequence of models.
Parameters
----------
proportion : float, default 0.2
stratify : bool, default False
seed : int, default False
indices : list(np.ndarray,np.ndarray), default None
Two numpy arrays that contain indices for train/test slicing.
add_diff : bool, default False
Returns
-------
`DataFrame`
Examples
--------
>>> pipeline = ModelsPipeline(model_rf,model_lr)
>>> pipeline.blend(seed=15)
>>> # Custom indices
>>> train_index = np.array(range(250))
>>> test_index = np.array(range(250,333))
>>> res = model_rf.blend(indicies=(train_index,test_index)) | [
"Blends",
"sequence",
"of",
"models",
"."
] | c330854cee3c547417eb353a4a4a23331b40b4bc | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/pipeline.py#L152-L198 | train | 200,198 |
rushter/heamy | heamy/pipeline.py | ModelsPipeline.find_weights | def find_weights(self, scorer, test_size=0.2, method='SLSQP'):
"""Finds optimal weights for weighted average of models.
Parameters
----------
scorer : function
Scikit-learn like metric.
test_size : float, default 0.2
method : str
Type of solver. Should be one of:
- 'Nelder-Mead'
- 'Powell'
- 'CG'
- 'BFGS'
- 'Newton-CG'
- 'L-BFGS-B'
- 'TNC'
- 'COBYLA'
- 'SLSQP'
- 'dogleg'
- 'trust-ncg'
Returns
-------
list
"""
p = Optimizer(self.models, test_size=test_size, scorer=scorer)
return p.minimize(method) | python | def find_weights(self, scorer, test_size=0.2, method='SLSQP'):
"""Finds optimal weights for weighted average of models.
Parameters
----------
scorer : function
Scikit-learn like metric.
test_size : float, default 0.2
method : str
Type of solver. Should be one of:
- 'Nelder-Mead'
- 'Powell'
- 'CG'
- 'BFGS'
- 'Newton-CG'
- 'L-BFGS-B'
- 'TNC'
- 'COBYLA'
- 'SLSQP'
- 'dogleg'
- 'trust-ncg'
Returns
-------
list
"""
p = Optimizer(self.models, test_size=test_size, scorer=scorer)
return p.minimize(method) | [
"def",
"find_weights",
"(",
"self",
",",
"scorer",
",",
"test_size",
"=",
"0.2",
",",
"method",
"=",
"'SLSQP'",
")",
":",
"p",
"=",
"Optimizer",
"(",
"self",
".",
"models",
",",
"test_size",
"=",
"test_size",
",",
"scorer",
"=",
"scorer",
")",
"return"... | Finds optimal weights for weighted average of models.
Parameters
----------
scorer : function
Scikit-learn like metric.
test_size : float, default 0.2
method : str
Type of solver. Should be one of:
- 'Nelder-Mead'
- 'Powell'
- 'CG'
- 'BFGS'
- 'Newton-CG'
- 'L-BFGS-B'
- 'TNC'
- 'COBYLA'
- 'SLSQP'
- 'dogleg'
- 'trust-ncg'
Returns
-------
list | [
"Finds",
"optimal",
"weights",
"for",
"weighted",
"average",
"of",
"models",
"."
] | c330854cee3c547417eb353a4a4a23331b40b4bc | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/pipeline.py#L200-L228 | train | 200,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.