repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
tinybike/coinbridge | coinbridge/__init__.py | Bridge.getaccountaddress | def getaccountaddress(self, user_id=""):
"""Get the coin address associated with a user id.
If the specified user id does not yet have an address for this
coin, then generate one.
Args:
user_id (str): this user's unique identifier
Returns:
str: Base58Check address for this account
"""
address = self.rpc.call("getaccountaddress", user_id)
self.logger.debug("Your", self.coin, "address is", address)
return address | python | def getaccountaddress(self, user_id=""):
"""Get the coin address associated with a user id.
If the specified user id does not yet have an address for this
coin, then generate one.
Args:
user_id (str): this user's unique identifier
Returns:
str: Base58Check address for this account
"""
address = self.rpc.call("getaccountaddress", user_id)
self.logger.debug("Your", self.coin, "address is", address)
return address | [
"def",
"getaccountaddress",
"(",
"self",
",",
"user_id",
"=",
"\"\"",
")",
":",
"address",
"=",
"self",
".",
"rpc",
".",
"call",
"(",
"\"getaccountaddress\"",
",",
"user_id",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Your\"",
",",
"self",
".",
... | Get the coin address associated with a user id.
If the specified user id does not yet have an address for this
coin, then generate one.
Args:
user_id (str): this user's unique identifier
Returns:
str: Base58Check address for this account | [
"Get",
"the",
"coin",
"address",
"associated",
"with",
"a",
"user",
"id",
"."
] | train | https://github.com/tinybike/coinbridge/blob/c9bde6f4196fecc09e8119f51dff8a26cfc1aee6/coinbridge/__init__.py#L333-L348 |
tinybike/coinbridge | coinbridge/__init__.py | Bridge.getbalance | def getbalance(self, user_id="", as_decimal=True):
"""Calculate the total balance in all addresses belonging to this user.
Args:
user_id (str): this user's unique identifier
as_decimal (bool): balance is returned as a Decimal if True (default)
or a string if False
Returns:
str or Decimal: this account's total coin balance
"""
balance = unicode(self.rpc.call("getbalance", user_id))
self.logger.debug("\"" + user_id + "\"", self.coin, "balance:", balance)
if as_decimal:
return Decimal(balance)
else:
return balance | python | def getbalance(self, user_id="", as_decimal=True):
"""Calculate the total balance in all addresses belonging to this user.
Args:
user_id (str): this user's unique identifier
as_decimal (bool): balance is returned as a Decimal if True (default)
or a string if False
Returns:
str or Decimal: this account's total coin balance
"""
balance = unicode(self.rpc.call("getbalance", user_id))
self.logger.debug("\"" + user_id + "\"", self.coin, "balance:", balance)
if as_decimal:
return Decimal(balance)
else:
return balance | [
"def",
"getbalance",
"(",
"self",
",",
"user_id",
"=",
"\"\"",
",",
"as_decimal",
"=",
"True",
")",
":",
"balance",
"=",
"unicode",
"(",
"self",
".",
"rpc",
".",
"call",
"(",
"\"getbalance\"",
",",
"user_id",
")",
")",
"self",
".",
"logger",
".",
"de... | Calculate the total balance in all addresses belonging to this user.
Args:
user_id (str): this user's unique identifier
as_decimal (bool): balance is returned as a Decimal if True (default)
or a string if False
Returns:
str or Decimal: this account's total coin balance | [
"Calculate",
"the",
"total",
"balance",
"in",
"all",
"addresses",
"belonging",
"to",
"this",
"user",
"."
] | train | https://github.com/tinybike/coinbridge/blob/c9bde6f4196fecc09e8119f51dff8a26cfc1aee6/coinbridge/__init__.py#L351-L368 |
tinybike/coinbridge | coinbridge/__init__.py | Bridge.listtransactions | def listtransactions(self, user_id="", count=10, start_at=0):
"""List all transactions associated with this account.
Args:
user_id (str): this user's unique identifier
count (int): number of transactions to return (default=10)
start_at (int): start the list at this transaction (default=0)
Returns:
list [dict]: transactions associated with this user's account
"""
txlist = self.rpc.call("listtransactions", user_id, count, start_at)
self.logger.debug("Got transaction list for " + str(user_id))
return txlist | python | def listtransactions(self, user_id="", count=10, start_at=0):
"""List all transactions associated with this account.
Args:
user_id (str): this user's unique identifier
count (int): number of transactions to return (default=10)
start_at (int): start the list at this transaction (default=0)
Returns:
list [dict]: transactions associated with this user's account
"""
txlist = self.rpc.call("listtransactions", user_id, count, start_at)
self.logger.debug("Got transaction list for " + str(user_id))
return txlist | [
"def",
"listtransactions",
"(",
"self",
",",
"user_id",
"=",
"\"\"",
",",
"count",
"=",
"10",
",",
"start_at",
"=",
"0",
")",
":",
"txlist",
"=",
"self",
".",
"rpc",
".",
"call",
"(",
"\"listtransactions\"",
",",
"user_id",
",",
"count",
",",
"start_at... | List all transactions associated with this account.
Args:
user_id (str): this user's unique identifier
count (int): number of transactions to return (default=10)
start_at (int): start the list at this transaction (default=0)
Returns:
list [dict]: transactions associated with this user's account | [
"List",
"all",
"transactions",
"associated",
"with",
"this",
"account",
"."
] | train | https://github.com/tinybike/coinbridge/blob/c9bde6f4196fecc09e8119f51dff8a26cfc1aee6/coinbridge/__init__.py#L384-L398 |
tinybike/coinbridge | coinbridge/__init__.py | Bridge.move | def move(self, fromaccount, toaccount, amount, minconf=1):
"""Send coins between accounts in the same wallet.
If the receiving account does not exist, it is automatically
created (but not automatically assigned an address).
Args:
fromaccount (str): origin account
toaccount (str): destination account
amount (str or Decimal): amount to send (8 decimal points)
minconf (int): ensure the account has a valid balance using this
many confirmations (default=1)
Returns:
bool: True if the coins are moved successfully, False otherwise
"""
amount = Decimal(amount).quantize(self.quantum, rounding=ROUND_HALF_EVEN)
return self.rpc.call("move",
fromaccount, toaccount, float(str(amount)), minconf
) | python | def move(self, fromaccount, toaccount, amount, minconf=1):
"""Send coins between accounts in the same wallet.
If the receiving account does not exist, it is automatically
created (but not automatically assigned an address).
Args:
fromaccount (str): origin account
toaccount (str): destination account
amount (str or Decimal): amount to send (8 decimal points)
minconf (int): ensure the account has a valid balance using this
many confirmations (default=1)
Returns:
bool: True if the coins are moved successfully, False otherwise
"""
amount = Decimal(amount).quantize(self.quantum, rounding=ROUND_HALF_EVEN)
return self.rpc.call("move",
fromaccount, toaccount, float(str(amount)), minconf
) | [
"def",
"move",
"(",
"self",
",",
"fromaccount",
",",
"toaccount",
",",
"amount",
",",
"minconf",
"=",
"1",
")",
":",
"amount",
"=",
"Decimal",
"(",
"amount",
")",
".",
"quantize",
"(",
"self",
".",
"quantum",
",",
"rounding",
"=",
"ROUND_HALF_EVEN",
")... | Send coins between accounts in the same wallet.
If the receiving account does not exist, it is automatically
created (but not automatically assigned an address).
Args:
fromaccount (str): origin account
toaccount (str): destination account
amount (str or Decimal): amount to send (8 decimal points)
minconf (int): ensure the account has a valid balance using this
many confirmations (default=1)
Returns:
bool: True if the coins are moved successfully, False otherwise | [
"Send",
"coins",
"between",
"accounts",
"in",
"the",
"same",
"wallet",
"."
] | train | https://github.com/tinybike/coinbridge/blob/c9bde6f4196fecc09e8119f51dff8a26cfc1aee6/coinbridge/__init__.py#L401-L421 |
tinybike/coinbridge | coinbridge/__init__.py | Bridge.sendfrom | def sendfrom(self, user_id, dest_address, amount, minconf=1):
"""
Send coins from user's account.
Args:
user_id (str): this user's unique identifier
dest_address (str): address which is to receive coins
amount (str or Decimal): amount to send (eight decimal points)
minconf (int): ensure the account has a valid balance using this
many confirmations (default=1)
Returns:
str: transaction ID
"""
amount = Decimal(amount).quantize(self.quantum, rounding=ROUND_HALF_EVEN)
txhash = self.rpc.call("sendfrom",
user_id, dest_address, float(str(amount)), minconf
)
self.logger.debug("Send %s %s from %s to %s" % (str(amount), self.coin,
str(user_id), dest_address))
self.logger.debug("Transaction hash: %s" % txhash)
return txhash | python | def sendfrom(self, user_id, dest_address, amount, minconf=1):
"""
Send coins from user's account.
Args:
user_id (str): this user's unique identifier
dest_address (str): address which is to receive coins
amount (str or Decimal): amount to send (eight decimal points)
minconf (int): ensure the account has a valid balance using this
many confirmations (default=1)
Returns:
str: transaction ID
"""
amount = Decimal(amount).quantize(self.quantum, rounding=ROUND_HALF_EVEN)
txhash = self.rpc.call("sendfrom",
user_id, dest_address, float(str(amount)), minconf
)
self.logger.debug("Send %s %s from %s to %s" % (str(amount), self.coin,
str(user_id), dest_address))
self.logger.debug("Transaction hash: %s" % txhash)
return txhash | [
"def",
"sendfrom",
"(",
"self",
",",
"user_id",
",",
"dest_address",
",",
"amount",
",",
"minconf",
"=",
"1",
")",
":",
"amount",
"=",
"Decimal",
"(",
"amount",
")",
".",
"quantize",
"(",
"self",
".",
"quantum",
",",
"rounding",
"=",
"ROUND_HALF_EVEN",
... | Send coins from user's account.
Args:
user_id (str): this user's unique identifier
dest_address (str): address which is to receive coins
amount (str or Decimal): amount to send (eight decimal points)
minconf (int): ensure the account has a valid balance using this
many confirmations (default=1)
Returns:
str: transaction ID | [
"Send",
"coins",
"from",
"user",
"s",
"account",
"."
] | train | https://github.com/tinybike/coinbridge/blob/c9bde6f4196fecc09e8119f51dff8a26cfc1aee6/coinbridge/__init__.py#L424-L446 |
tinybike/coinbridge | coinbridge/__init__.py | Bridge.signmessage | def signmessage(self, address, message):
"""Sign a message with the private key of an address.
Cryptographically signs a message using ECDSA. Since this requires
an address's private key, the wallet must be unlocked first.
Args:
address (str): address used to sign the message
message (str): plaintext message to which apply the signature
Returns:
str: ECDSA signature over the message
"""
signature = self.rpc.call("signmessage", address, message)
self.logger.debug("Signature: %s" % signature)
return signature | python | def signmessage(self, address, message):
"""Sign a message with the private key of an address.
Cryptographically signs a message using ECDSA. Since this requires
an address's private key, the wallet must be unlocked first.
Args:
address (str): address used to sign the message
message (str): plaintext message to which apply the signature
Returns:
str: ECDSA signature over the message
"""
signature = self.rpc.call("signmessage", address, message)
self.logger.debug("Signature: %s" % signature)
return signature | [
"def",
"signmessage",
"(",
"self",
",",
"address",
",",
"message",
")",
":",
"signature",
"=",
"self",
".",
"rpc",
".",
"call",
"(",
"\"signmessage\"",
",",
"address",
",",
"message",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Signature: %s\"",
"%... | Sign a message with the private key of an address.
Cryptographically signs a message using ECDSA. Since this requires
an address's private key, the wallet must be unlocked first.
Args:
address (str): address used to sign the message
message (str): plaintext message to which apply the signature
Returns:
str: ECDSA signature over the message | [
"Sign",
"a",
"message",
"with",
"the",
"private",
"key",
"of",
"an",
"address",
"."
] | train | https://github.com/tinybike/coinbridge/blob/c9bde6f4196fecc09e8119f51dff8a26cfc1aee6/coinbridge/__init__.py#L486-L502 |
tinybike/coinbridge | coinbridge/__init__.py | Bridge.verifymessage | def verifymessage(self, address, signature, message):
"""
Verifies that a message has been signed by an address.
Args:
address (str): address claiming to have signed the message
signature (str): ECDSA signature
message (str): plaintext message which was signed
Returns:
bool: True if the address signed the message, False otherwise
"""
verified = self.rpc.call("verifymessage", address, signature, message)
self.logger.debug("Signature verified: %s" % str(verified))
return verified | python | def verifymessage(self, address, signature, message):
"""
Verifies that a message has been signed by an address.
Args:
address (str): address claiming to have signed the message
signature (str): ECDSA signature
message (str): plaintext message which was signed
Returns:
bool: True if the address signed the message, False otherwise
"""
verified = self.rpc.call("verifymessage", address, signature, message)
self.logger.debug("Signature verified: %s" % str(verified))
return verified | [
"def",
"verifymessage",
"(",
"self",
",",
"address",
",",
"signature",
",",
"message",
")",
":",
"verified",
"=",
"self",
".",
"rpc",
".",
"call",
"(",
"\"verifymessage\"",
",",
"address",
",",
"signature",
",",
"message",
")",
"self",
".",
"logger",
"."... | Verifies that a message has been signed by an address.
Args:
address (str): address claiming to have signed the message
signature (str): ECDSA signature
message (str): plaintext message which was signed
Returns:
bool: True if the address signed the message, False otherwise | [
"Verifies",
"that",
"a",
"message",
"has",
"been",
"signed",
"by",
"an",
"address",
"."
] | train | https://github.com/tinybike/coinbridge/blob/c9bde6f4196fecc09e8119f51dff8a26cfc1aee6/coinbridge/__init__.py#L505-L520 |
tinybike/coinbridge | coinbridge/__init__.py | Bridge.call | def call(self, command, *args):
"""
Passes an arbitrary command to the coin daemon.
Args:
command (str): command to be sent to the coin daemon
"""
return self.rpc.call(str(command), *args) | python | def call(self, command, *args):
"""
Passes an arbitrary command to the coin daemon.
Args:
command (str): command to be sent to the coin daemon
"""
return self.rpc.call(str(command), *args) | [
"def",
"call",
"(",
"self",
",",
"command",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"rpc",
".",
"call",
"(",
"str",
"(",
"command",
")",
",",
"*",
"args",
")"
] | Passes an arbitrary command to the coin daemon.
Args:
command (str): command to be sent to the coin daemon | [
"Passes",
"an",
"arbitrary",
"command",
"to",
"the",
"coin",
"daemon",
"."
] | train | https://github.com/tinybike/coinbridge/blob/c9bde6f4196fecc09e8119f51dff8a26cfc1aee6/coinbridge/__init__.py#L523-L531 |
theonion/django-bulbs | bulbs/contributions/signals.py | update_feature_type_rates | def update_feature_type_rates(sender, instance, created, *args, **kwargs):
"""
Creates a default FeatureTypeRate for each role after the creation of a FeatureTypeRate.
"""
if created:
for role in ContributorRole.objects.all():
FeatureTypeRate.objects.create(role=role, feature_type=instance, rate=0) | python | def update_feature_type_rates(sender, instance, created, *args, **kwargs):
"""
Creates a default FeatureTypeRate for each role after the creation of a FeatureTypeRate.
"""
if created:
for role in ContributorRole.objects.all():
FeatureTypeRate.objects.create(role=role, feature_type=instance, rate=0) | [
"def",
"update_feature_type_rates",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
":",
"for",
"role",
"in",
"ContributorRole",
".",
"objects",
".",
"all",
"(",
")",
":",
"FeatureType... | Creates a default FeatureTypeRate for each role after the creation of a FeatureTypeRate. | [
"Creates",
"a",
"default",
"FeatureTypeRate",
"for",
"each",
"role",
"after",
"the",
"creation",
"of",
"a",
"FeatureTypeRate",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/contributions/signals.py#L12-L18 |
theonion/django-bulbs | bulbs/contributions/signals.py | update_contributions | def update_contributions(sender, instance, action, model, pk_set, **kwargs):
"""Creates a contribution for each author added to an article.
"""
if action != 'pre_add':
return
else:
for author in model.objects.filter(pk__in=pk_set):
update_content_contributions(instance, author) | python | def update_contributions(sender, instance, action, model, pk_set, **kwargs):
"""Creates a contribution for each author added to an article.
"""
if action != 'pre_add':
return
else:
for author in model.objects.filter(pk__in=pk_set):
update_content_contributions(instance, author) | [
"def",
"update_contributions",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"model",
",",
"pk_set",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"!=",
"'pre_add'",
":",
"return",
"else",
":",
"for",
"author",
"in",
"model",
".",
"objects",
... | Creates a contribution for each author added to an article. | [
"Creates",
"a",
"contribution",
"for",
"each",
"author",
"added",
"to",
"an",
"article",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/contributions/signals.py#L27-L34 |
PGower/PyCanvas | pycanvas/apis/calendar_events.py | CalendarEventsAPI.list_calendar_events | def list_calendar_events(self, all_events=None, context_codes=None, end_date=None, excludes=None, start_date=None, type=None, undated=None):
"""
List calendar events.
Retrieve the list of calendar events or assignments for the current user
"""
path = {}
data = {}
params = {}
# OPTIONAL - type
"""Defaults to "event""""
if type is not None:
self._validate_enum(type, ["event", "assignment"])
params["type"] = type
# OPTIONAL - start_date
"""Only return events since the start_date (inclusive).
Defaults to today. The value should be formatted as: yyyy-mm-dd or ISO 8601 YYYY-MM-DDTHH:MM:SSZ."""
if start_date is not None:
params["start_date"] = start_date
# OPTIONAL - end_date
"""Only return events before the end_date (inclusive).
Defaults to start_date. The value should be formatted as: yyyy-mm-dd or ISO 8601 YYYY-MM-DDTHH:MM:SSZ.
If end_date is the same as start_date, then only events on that day are
returned."""
if end_date is not None:
params["end_date"] = end_date
# OPTIONAL - undated
"""Defaults to false (dated events only).
If true, only return undated events and ignore start_date and end_date."""
if undated is not None:
params["undated"] = undated
# OPTIONAL - all_events
"""Defaults to false (uses start_date, end_date, and undated criteria).
If true, all events are returned, ignoring start_date, end_date, and undated criteria."""
if all_events is not None:
params["all_events"] = all_events
# OPTIONAL - context_codes
"""List of context codes of courses/groups/users whose events you want to see.
If not specified, defaults to the current user (i.e personal calendar,
no course/group events). Limited to 10 context codes, additional ones are
ignored. The format of this field is the context type, followed by an
underscore, followed by the context id. For example: course_42"""
if context_codes is not None:
params["context_codes"] = context_codes
# OPTIONAL - excludes
"""Array of attributes to exclude. Possible values are "description", "child_events" and "assignment""""
if excludes is not None:
params["excludes"] = excludes
self.logger.debug("GET /api/v1/calendar_events with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/calendar_events".format(**path), data=data, params=params, all_pages=True) | python | def list_calendar_events(self, all_events=None, context_codes=None, end_date=None, excludes=None, start_date=None, type=None, undated=None):
"""
List calendar events.
Retrieve the list of calendar events or assignments for the current user
"""
path = {}
data = {}
params = {}
# OPTIONAL - type
"""Defaults to "event""""
if type is not None:
self._validate_enum(type, ["event", "assignment"])
params["type"] = type
# OPTIONAL - start_date
"""Only return events since the start_date (inclusive).
Defaults to today. The value should be formatted as: yyyy-mm-dd or ISO 8601 YYYY-MM-DDTHH:MM:SSZ."""
if start_date is not None:
params["start_date"] = start_date
# OPTIONAL - end_date
"""Only return events before the end_date (inclusive).
Defaults to start_date. The value should be formatted as: yyyy-mm-dd or ISO 8601 YYYY-MM-DDTHH:MM:SSZ.
If end_date is the same as start_date, then only events on that day are
returned."""
if end_date is not None:
params["end_date"] = end_date
# OPTIONAL - undated
"""Defaults to false (dated events only).
If true, only return undated events and ignore start_date and end_date."""
if undated is not None:
params["undated"] = undated
# OPTIONAL - all_events
"""Defaults to false (uses start_date, end_date, and undated criteria).
If true, all events are returned, ignoring start_date, end_date, and undated criteria."""
if all_events is not None:
params["all_events"] = all_events
# OPTIONAL - context_codes
"""List of context codes of courses/groups/users whose events you want to see.
If not specified, defaults to the current user (i.e personal calendar,
no course/group events). Limited to 10 context codes, additional ones are
ignored. The format of this field is the context type, followed by an
underscore, followed by the context id. For example: course_42"""
if context_codes is not None:
params["context_codes"] = context_codes
# OPTIONAL - excludes
"""Array of attributes to exclude. Possible values are "description", "child_events" and "assignment""""
if excludes is not None:
params["excludes"] = excludes
self.logger.debug("GET /api/v1/calendar_events with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/calendar_events".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_calendar_events",
"(",
"self",
",",
"all_events",
"=",
"None",
",",
"context_codes",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"excludes",
"=",
"None",
",",
"start_date",
"=",
"None",
",",
"type",
"=",
"None",
",",
"undated",
"=",
"Non... | List calendar events.
Retrieve the list of calendar events or assignments for the current user | [
"List",
"calendar",
"events",
".",
"Retrieve",
"the",
"list",
"of",
"calendar",
"events",
"or",
"assignments",
"for",
"the",
"current",
"user"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/calendar_events.py#L19-L76 |
PGower/PyCanvas | pycanvas/apis/calendar_events.py | CalendarEventsAPI.create_calendar_event | def create_calendar_event(self, calendar_event_context_code, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_description=None, calendar_event_duplicate_append_iterator=None, calendar_event_duplicate_count=None, calendar_event_duplicate_frequency=None, calendar_event_duplicate_interval=None, calendar_event_end_at=None, calendar_event_location_address=None, calendar_event_location_name=None, calendar_event_start_at=None, calendar_event_time_zone_edited=None, calendar_event_title=None):
"""
Create a calendar event.
Create and return a new calendar event
"""
path = {}
data = {}
params = {}
# REQUIRED - calendar_event[context_code]
"""Context code of the course/group/user whose calendar this event should be
added to."""
data["calendar_event[context_code]"] = calendar_event_context_code
# OPTIONAL - calendar_event[title]
"""Short title for the calendar event."""
if calendar_event_title is not None:
data["calendar_event[title]"] = calendar_event_title
# OPTIONAL - calendar_event[description]
"""Longer HTML description of the event."""
if calendar_event_description is not None:
data["calendar_event[description]"] = calendar_event_description
# OPTIONAL - calendar_event[start_at]
"""Start date/time of the event."""
if calendar_event_start_at is not None:
data["calendar_event[start_at]"] = calendar_event_start_at
# OPTIONAL - calendar_event[end_at]
"""End date/time of the event."""
if calendar_event_end_at is not None:
data["calendar_event[end_at]"] = calendar_event_end_at
# OPTIONAL - calendar_event[location_name]
"""Location name of the event."""
if calendar_event_location_name is not None:
data["calendar_event[location_name]"] = calendar_event_location_name
# OPTIONAL - calendar_event[location_address]
"""Location address"""
if calendar_event_location_address is not None:
data["calendar_event[location_address]"] = calendar_event_location_address
# OPTIONAL - calendar_event[time_zone_edited]
"""Time zone of the user editing the event. Allowed time zones are
{http://www.iana.org/time-zones IANA time zones} or friendlier
{http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}."""
if calendar_event_time_zone_edited is not None:
data["calendar_event[time_zone_edited]"] = calendar_event_time_zone_edited
# OPTIONAL - calendar_event[child_event_data][X][start_at]
"""Section-level start time(s) if this is a course event. X can be any
identifier, provided that it is consistent across the start_at, end_at
and context_code"""
if calendar_event_child_event_data_X_start_at is not None:
data["calendar_event[child_event_data][X][start_at]"] = calendar_event_child_event_data_X_start_at
# OPTIONAL - calendar_event[child_event_data][X][end_at]
"""Section-level end time(s) if this is a course event."""
if calendar_event_child_event_data_X_end_at is not None:
data["calendar_event[child_event_data][X][end_at]"] = calendar_event_child_event_data_X_end_at
# OPTIONAL - calendar_event[child_event_data][X][context_code]
"""Context code(s) corresponding to the section-level start and end time(s)."""
if calendar_event_child_event_data_X_context_code is not None:
data["calendar_event[child_event_data][X][context_code]"] = calendar_event_child_event_data_X_context_code
# OPTIONAL - calendar_event[duplicate][count]
"""Number of times to copy/duplicate the event."""
if calendar_event_duplicate_count is not None:
data["calendar_event[duplicate][count]"] = calendar_event_duplicate_count
# OPTIONAL - calendar_event[duplicate][interval]
"""Defaults to 1 if duplicate `count` is set. The interval between the duplicated events."""
if calendar_event_duplicate_interval is not None:
data["calendar_event[duplicate][interval]"] = calendar_event_duplicate_interval
# OPTIONAL - calendar_event[duplicate][frequency]
"""Defaults to "weekly". The frequency at which to duplicate the event"""
if calendar_event_duplicate_frequency is not None:
self._validate_enum(calendar_event_duplicate_frequency, ["daily", "weekly", "monthly"])
data["calendar_event[duplicate][frequency]"] = calendar_event_duplicate_frequency
# OPTIONAL - calendar_event[duplicate][append_iterator]
"""Defaults to false. If set to `true`, an increasing counter number will be appended to the event title
when the event is duplicated. (e.g. Event 1, Event 2, Event 3, etc)"""
if calendar_event_duplicate_append_iterator is not None:
data["calendar_event[duplicate][append_iterator]"] = calendar_event_duplicate_append_iterator
self.logger.debug("POST /api/v1/calendar_events with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/calendar_events".format(**path), data=data, params=params, no_data=True) | python | def create_calendar_event(self, calendar_event_context_code, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_description=None, calendar_event_duplicate_append_iterator=None, calendar_event_duplicate_count=None, calendar_event_duplicate_frequency=None, calendar_event_duplicate_interval=None, calendar_event_end_at=None, calendar_event_location_address=None, calendar_event_location_name=None, calendar_event_start_at=None, calendar_event_time_zone_edited=None, calendar_event_title=None):
"""
Create a calendar event.
Create and return a new calendar event
"""
path = {}
data = {}
params = {}
# REQUIRED - calendar_event[context_code]
"""Context code of the course/group/user whose calendar this event should be
added to."""
data["calendar_event[context_code]"] = calendar_event_context_code
# OPTIONAL - calendar_event[title]
"""Short title for the calendar event."""
if calendar_event_title is not None:
data["calendar_event[title]"] = calendar_event_title
# OPTIONAL - calendar_event[description]
"""Longer HTML description of the event."""
if calendar_event_description is not None:
data["calendar_event[description]"] = calendar_event_description
# OPTIONAL - calendar_event[start_at]
"""Start date/time of the event."""
if calendar_event_start_at is not None:
data["calendar_event[start_at]"] = calendar_event_start_at
# OPTIONAL - calendar_event[end_at]
"""End date/time of the event."""
if calendar_event_end_at is not None:
data["calendar_event[end_at]"] = calendar_event_end_at
# OPTIONAL - calendar_event[location_name]
"""Location name of the event."""
if calendar_event_location_name is not None:
data["calendar_event[location_name]"] = calendar_event_location_name
# OPTIONAL - calendar_event[location_address]
"""Location address"""
if calendar_event_location_address is not None:
data["calendar_event[location_address]"] = calendar_event_location_address
# OPTIONAL - calendar_event[time_zone_edited]
"""Time zone of the user editing the event. Allowed time zones are
{http://www.iana.org/time-zones IANA time zones} or friendlier
{http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}."""
if calendar_event_time_zone_edited is not None:
data["calendar_event[time_zone_edited]"] = calendar_event_time_zone_edited
# OPTIONAL - calendar_event[child_event_data][X][start_at]
"""Section-level start time(s) if this is a course event. X can be any
identifier, provided that it is consistent across the start_at, end_at
and context_code"""
if calendar_event_child_event_data_X_start_at is not None:
data["calendar_event[child_event_data][X][start_at]"] = calendar_event_child_event_data_X_start_at
# OPTIONAL - calendar_event[child_event_data][X][end_at]
"""Section-level end time(s) if this is a course event."""
if calendar_event_child_event_data_X_end_at is not None:
data["calendar_event[child_event_data][X][end_at]"] = calendar_event_child_event_data_X_end_at
# OPTIONAL - calendar_event[child_event_data][X][context_code]
"""Context code(s) corresponding to the section-level start and end time(s)."""
if calendar_event_child_event_data_X_context_code is not None:
data["calendar_event[child_event_data][X][context_code]"] = calendar_event_child_event_data_X_context_code
# OPTIONAL - calendar_event[duplicate][count]
"""Number of times to copy/duplicate the event."""
if calendar_event_duplicate_count is not None:
data["calendar_event[duplicate][count]"] = calendar_event_duplicate_count
# OPTIONAL - calendar_event[duplicate][interval]
"""Defaults to 1 if duplicate `count` is set. The interval between the duplicated events."""
if calendar_event_duplicate_interval is not None:
data["calendar_event[duplicate][interval]"] = calendar_event_duplicate_interval
# OPTIONAL - calendar_event[duplicate][frequency]
"""Defaults to "weekly". The frequency at which to duplicate the event"""
if calendar_event_duplicate_frequency is not None:
self._validate_enum(calendar_event_duplicate_frequency, ["daily", "weekly", "monthly"])
data["calendar_event[duplicate][frequency]"] = calendar_event_duplicate_frequency
# OPTIONAL - calendar_event[duplicate][append_iterator]
"""Defaults to false. If set to `true`, an increasing counter number will be appended to the event title
when the event is duplicated. (e.g. Event 1, Event 2, Event 3, etc)"""
if calendar_event_duplicate_append_iterator is not None:
data["calendar_event[duplicate][append_iterator]"] = calendar_event_duplicate_append_iterator
self.logger.debug("POST /api/v1/calendar_events with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/calendar_events".format(**path), data=data, params=params, no_data=True) | [
"def",
"create_calendar_event",
"(",
"self",
",",
"calendar_event_context_code",
",",
"calendar_event_child_event_data_X_context_code",
"=",
"None",
",",
"calendar_event_child_event_data_X_end_at",
"=",
"None",
",",
"calendar_event_child_event_data_X_start_at",
"=",
"None",
",",
... | Create a calendar event.
Create and return a new calendar event | [
"Create",
"a",
"calendar",
"event",
".",
"Create",
"and",
"return",
"a",
"new",
"calendar",
"event"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/calendar_events.py#L143-L235 |
PGower/PyCanvas | pycanvas/apis/calendar_events.py | CalendarEventsAPI.reserve_time_slot | def reserve_time_slot(self, id, cancel_existing=None, comments=None, participant_id=None):
"""
Reserve a time slot.
Reserves a particular time slot and return the new reservation
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - participant_id
"""User or group id for whom you are making the reservation (depends on the
participant type). Defaults to the current user (or user's candidate group)."""
if participant_id is not None:
data["participant_id"] = participant_id
# OPTIONAL - comments
"""Comments to associate with this reservation"""
if comments is not None:
data["comments"] = comments
# OPTIONAL - cancel_existing
"""Defaults to false. If true, cancel any previous reservation(s) for this
participant and appointment group."""
if cancel_existing is not None:
data["cancel_existing"] = cancel_existing
self.logger.debug("POST /api/v1/calendar_events/{id}/reservations with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/calendar_events/{id}/reservations".format(**path), data=data, params=params, no_data=True) | python | def reserve_time_slot(self, id, cancel_existing=None, comments=None, participant_id=None):
"""
Reserve a time slot.
Reserves a particular time slot and return the new reservation
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - participant_id
"""User or group id for whom you are making the reservation (depends on the
participant type). Defaults to the current user (or user's candidate group)."""
if participant_id is not None:
data["participant_id"] = participant_id
# OPTIONAL - comments
"""Comments to associate with this reservation"""
if comments is not None:
data["comments"] = comments
# OPTIONAL - cancel_existing
"""Defaults to false. If true, cancel any previous reservation(s) for this
participant and appointment group."""
if cancel_existing is not None:
data["cancel_existing"] = cancel_existing
self.logger.debug("POST /api/v1/calendar_events/{id}/reservations with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/calendar_events/{id}/reservations".format(**path), data=data, params=params, no_data=True) | [
"def",
"reserve_time_slot",
"(",
"self",
",",
"id",
",",
"cancel_existing",
"=",
"None",
",",
"comments",
"=",
"None",
",",
"participant_id",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PA... | Reserve a time slot.
Reserves a particular time slot and return the new reservation | [
"Reserve",
"a",
"time",
"slot",
".",
"Reserves",
"a",
"particular",
"time",
"slot",
"and",
"return",
"the",
"new",
"reservation"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/calendar_events.py#L254-L286 |
PGower/PyCanvas | pycanvas/apis/calendar_events.py | CalendarEventsAPI.update_calendar_event | def update_calendar_event(self, id, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_context_code=None, calendar_event_description=None, calendar_event_end_at=None, calendar_event_location_address=None, calendar_event_location_name=None, calendar_event_start_at=None, calendar_event_time_zone_edited=None, calendar_event_title=None):
"""
Update a calendar event.
Update and return a calendar event
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - calendar_event[context_code]
"""Context code of the course/group/user to move this event to.
Scheduler appointments and events with section-specific times cannot be moved between calendars."""
if calendar_event_context_code is not None:
data["calendar_event[context_code]"] = calendar_event_context_code
# OPTIONAL - calendar_event[title]
"""Short title for the calendar event."""
if calendar_event_title is not None:
data["calendar_event[title]"] = calendar_event_title
# OPTIONAL - calendar_event[description]
"""Longer HTML description of the event."""
if calendar_event_description is not None:
data["calendar_event[description]"] = calendar_event_description
# OPTIONAL - calendar_event[start_at]
"""Start date/time of the event."""
if calendar_event_start_at is not None:
data["calendar_event[start_at]"] = calendar_event_start_at
# OPTIONAL - calendar_event[end_at]
"""End date/time of the event."""
if calendar_event_end_at is not None:
data["calendar_event[end_at]"] = calendar_event_end_at
# OPTIONAL - calendar_event[location_name]
"""Location name of the event."""
if calendar_event_location_name is not None:
data["calendar_event[location_name]"] = calendar_event_location_name
# OPTIONAL - calendar_event[location_address]
"""Location address"""
if calendar_event_location_address is not None:
data["calendar_event[location_address]"] = calendar_event_location_address
# OPTIONAL - calendar_event[time_zone_edited]
"""Time zone of the user editing the event. Allowed time zones are
{http://www.iana.org/time-zones IANA time zones} or friendlier
{http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}."""
if calendar_event_time_zone_edited is not None:
data["calendar_event[time_zone_edited]"] = calendar_event_time_zone_edited
# OPTIONAL - calendar_event[child_event_data][X][start_at]
"""Section-level start time(s) if this is a course event. X can be any
identifier, provided that it is consistent across the start_at, end_at
and context_code"""
if calendar_event_child_event_data_X_start_at is not None:
data["calendar_event[child_event_data][X][start_at]"] = calendar_event_child_event_data_X_start_at
# OPTIONAL - calendar_event[child_event_data][X][end_at]
"""Section-level end time(s) if this is a course event."""
if calendar_event_child_event_data_X_end_at is not None:
data["calendar_event[child_event_data][X][end_at]"] = calendar_event_child_event_data_X_end_at
# OPTIONAL - calendar_event[child_event_data][X][context_code]
"""Context code(s) corresponding to the section-level start and end time(s)."""
if calendar_event_child_event_data_X_context_code is not None:
data["calendar_event[child_event_data][X][context_code]"] = calendar_event_child_event_data_X_context_code
self.logger.debug("PUT /api/v1/calendar_events/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/calendar_events/{id}".format(**path), data=data, params=params, no_data=True) | python | def update_calendar_event(self, id, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_context_code=None, calendar_event_description=None, calendar_event_end_at=None, calendar_event_location_address=None, calendar_event_location_name=None, calendar_event_start_at=None, calendar_event_time_zone_edited=None, calendar_event_title=None):
"""
Update a calendar event.
Update and return a calendar event
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - calendar_event[context_code]
"""Context code of the course/group/user to move this event to.
Scheduler appointments and events with section-specific times cannot be moved between calendars."""
if calendar_event_context_code is not None:
data["calendar_event[context_code]"] = calendar_event_context_code
# OPTIONAL - calendar_event[title]
"""Short title for the calendar event."""
if calendar_event_title is not None:
data["calendar_event[title]"] = calendar_event_title
# OPTIONAL - calendar_event[description]
"""Longer HTML description of the event."""
if calendar_event_description is not None:
data["calendar_event[description]"] = calendar_event_description
# OPTIONAL - calendar_event[start_at]
"""Start date/time of the event."""
if calendar_event_start_at is not None:
data["calendar_event[start_at]"] = calendar_event_start_at
# OPTIONAL - calendar_event[end_at]
"""End date/time of the event."""
if calendar_event_end_at is not None:
data["calendar_event[end_at]"] = calendar_event_end_at
# OPTIONAL - calendar_event[location_name]
"""Location name of the event."""
if calendar_event_location_name is not None:
data["calendar_event[location_name]"] = calendar_event_location_name
# OPTIONAL - calendar_event[location_address]
"""Location address"""
if calendar_event_location_address is not None:
data["calendar_event[location_address]"] = calendar_event_location_address
# OPTIONAL - calendar_event[time_zone_edited]
"""Time zone of the user editing the event. Allowed time zones are
{http://www.iana.org/time-zones IANA time zones} or friendlier
{http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}."""
if calendar_event_time_zone_edited is not None:
data["calendar_event[time_zone_edited]"] = calendar_event_time_zone_edited
# OPTIONAL - calendar_event[child_event_data][X][start_at]
"""Section-level start time(s) if this is a course event. X can be any
identifier, provided that it is consistent across the start_at, end_at
and context_code"""
if calendar_event_child_event_data_X_start_at is not None:
data["calendar_event[child_event_data][X][start_at]"] = calendar_event_child_event_data_X_start_at
# OPTIONAL - calendar_event[child_event_data][X][end_at]
"""Section-level end time(s) if this is a course event."""
if calendar_event_child_event_data_X_end_at is not None:
data["calendar_event[child_event_data][X][end_at]"] = calendar_event_child_event_data_X_end_at
# OPTIONAL - calendar_event[child_event_data][X][context_code]
"""Context code(s) corresponding to the section-level start and end time(s)."""
if calendar_event_child_event_data_X_context_code is not None:
data["calendar_event[child_event_data][X][context_code]"] = calendar_event_child_event_data_X_context_code
self.logger.debug("PUT /api/v1/calendar_events/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/calendar_events/{id}".format(**path), data=data, params=params, no_data=True) | [
"def",
"update_calendar_event",
"(",
"self",
",",
"id",
",",
"calendar_event_child_event_data_X_context_code",
"=",
"None",
",",
"calendar_event_child_event_data_X_end_at",
"=",
"None",
",",
"calendar_event_child_event_data_X_start_at",
"=",
"None",
",",
"calendar_event_context... | Update a calendar event.
Update and return a calendar event | [
"Update",
"a",
"calendar",
"event",
".",
"Update",
"and",
"return",
"a",
"calendar",
"event"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/calendar_events.py#L321-L396 |
PGower/PyCanvas | pycanvas/apis/calendar_events.py | CalendarEventsAPI.delete_calendar_event | def delete_calendar_event(self, id, cancel_reason=None):
"""
Delete a calendar event.
Delete an event from the calendar and return the deleted event
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - cancel_reason
"""Reason for deleting/canceling the event."""
if cancel_reason is not None:
params["cancel_reason"] = cancel_reason
self.logger.debug("DELETE /api/v1/calendar_events/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/calendar_events/{id}".format(**path), data=data, params=params, no_data=True) | python | def delete_calendar_event(self, id, cancel_reason=None):
"""
Delete a calendar event.
Delete an event from the calendar and return the deleted event
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - cancel_reason
"""Reason for deleting/canceling the event."""
if cancel_reason is not None:
params["cancel_reason"] = cancel_reason
self.logger.debug("DELETE /api/v1/calendar_events/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/calendar_events/{id}".format(**path), data=data, params=params, no_data=True) | [
"def",
"delete_calendar_event",
"(",
"self",
",",
"id",
",",
"cancel_reason",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"id\"",
"]",
"=",
"id... | Delete a calendar event.
Delete an event from the calendar and return the deleted event | [
"Delete",
"a",
"calendar",
"event",
".",
"Delete",
"an",
"event",
"from",
"the",
"calendar",
"and",
"return",
"the",
"deleted",
"event"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/calendar_events.py#L398-L418 |
PGower/PyCanvas | pycanvas/apis/calendar_events.py | CalendarEventsAPI.set_course_timetable | def set_course_timetable(self, course_id, timetables_course_section_id=None, timetables_course_section_id_end_time=None, timetables_course_section_id_location_name=None, timetables_course_section_id_start_time=None, timetables_course_section_id_weekdays=None):
"""
Set a course timetable.
Creates and updates "timetable" events for a course.
Can automaticaly generate a series of calendar events based on simple schedules
(e.g. "Monday and Wednesday at 2:00pm" )
Existing timetable events for the course and course sections
will be updated if they still are part of the timetable.
Otherwise, they will be deleted.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - timetables[course_section_id]
"""An array of timetable objects for the course section specified by course_section_id.
If course_section_id is set to "all", events will be created for the entire course."""
if timetables_course_section_id is not None:
data["timetables[course_section_id]"] = timetables_course_section_id
# OPTIONAL - timetables[course_section_id][weekdays]
"""A comma-separated list of abbreviated weekdays
(Mon-Monday, Tue-Tuesday, Wed-Wednesday, Thu-Thursday, Fri-Friday, Sat-Saturday, Sun-Sunday)"""
if timetables_course_section_id_weekdays is not None:
data["timetables[course_section_id][weekdays]"] = timetables_course_section_id_weekdays
# OPTIONAL - timetables[course_section_id][start_time]
"""Time to start each event at (e.g. "9:00 am")"""
if timetables_course_section_id_start_time is not None:
data["timetables[course_section_id][start_time]"] = timetables_course_section_id_start_time
# OPTIONAL - timetables[course_section_id][end_time]
"""Time to end each event at (e.g. "9:00 am")"""
if timetables_course_section_id_end_time is not None:
data["timetables[course_section_id][end_time]"] = timetables_course_section_id_end_time
# OPTIONAL - timetables[course_section_id][location_name]
"""A location name to set for each event"""
if timetables_course_section_id_location_name is not None:
data["timetables[course_section_id][location_name]"] = timetables_course_section_id_location_name
self.logger.debug("POST /api/v1/courses/{course_id}/calendar_events/timetable with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/calendar_events/timetable".format(**path), data=data, params=params, no_data=True) | python | def set_course_timetable(self, course_id, timetables_course_section_id=None, timetables_course_section_id_end_time=None, timetables_course_section_id_location_name=None, timetables_course_section_id_start_time=None, timetables_course_section_id_weekdays=None):
"""
Set a course timetable.
Creates and updates "timetable" events for a course.
Can automaticaly generate a series of calendar events based on simple schedules
(e.g. "Monday and Wednesday at 2:00pm" )
Existing timetable events for the course and course sections
will be updated if they still are part of the timetable.
Otherwise, they will be deleted.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - timetables[course_section_id]
"""An array of timetable objects for the course section specified by course_section_id.
If course_section_id is set to "all", events will be created for the entire course."""
if timetables_course_section_id is not None:
data["timetables[course_section_id]"] = timetables_course_section_id
# OPTIONAL - timetables[course_section_id][weekdays]
"""A comma-separated list of abbreviated weekdays
(Mon-Monday, Tue-Tuesday, Wed-Wednesday, Thu-Thursday, Fri-Friday, Sat-Saturday, Sun-Sunday)"""
if timetables_course_section_id_weekdays is not None:
data["timetables[course_section_id][weekdays]"] = timetables_course_section_id_weekdays
# OPTIONAL - timetables[course_section_id][start_time]
"""Time to start each event at (e.g. "9:00 am")"""
if timetables_course_section_id_start_time is not None:
data["timetables[course_section_id][start_time]"] = timetables_course_section_id_start_time
# OPTIONAL - timetables[course_section_id][end_time]
"""Time to end each event at (e.g. "9:00 am")"""
if timetables_course_section_id_end_time is not None:
data["timetables[course_section_id][end_time]"] = timetables_course_section_id_end_time
# OPTIONAL - timetables[course_section_id][location_name]
"""A location name to set for each event"""
if timetables_course_section_id_location_name is not None:
data["timetables[course_section_id][location_name]"] = timetables_course_section_id_location_name
self.logger.debug("POST /api/v1/courses/{course_id}/calendar_events/timetable with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/calendar_events/timetable".format(**path), data=data, params=params, no_data=True) | [
"def",
"set_course_timetable",
"(",
"self",
",",
"course_id",
",",
"timetables_course_section_id",
"=",
"None",
",",
"timetables_course_section_id_end_time",
"=",
"None",
",",
"timetables_course_section_id_location_name",
"=",
"None",
",",
"timetables_course_section_id_start_ti... | Set a course timetable.
Creates and updates "timetable" events for a course.
Can automaticaly generate a series of calendar events based on simple schedules
(e.g. "Monday and Wednesday at 2:00pm" )
Existing timetable events for the course and course sections
will be updated if they still are part of the timetable.
Otherwise, they will be deleted. | [
"Set",
"a",
"course",
"timetable",
".",
"Creates",
"and",
"updates",
"timetable",
"events",
"for",
"a",
"course",
".",
"Can",
"automaticaly",
"generate",
"a",
"series",
"of",
"calendar",
"events",
"based",
"on",
"simple",
"schedules",
"(",
"e",
".",
"g",
"... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/calendar_events.py#L420-L468 |
PGower/PyCanvas | pycanvas/apis/calendar_events.py | CalendarEventsAPI.create_or_update_events_directly_for_course_timetable | def create_or_update_events_directly_for_course_timetable(self, course_id, course_section_id=None, events=None, events_code=None, events_end_at=None, events_location_name=None, events_start_at=None):
"""
Create or update events directly for a course timetable.
Creates and updates "timetable" events for a course or course section.
Similar to {api:CalendarEventsApiController#set_course_timetable setting a course timetable},
but instead of generating a list of events based on a timetable schedule,
this endpoint expects a complete list of events.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - course_section_id
"""Events will be created for the course section specified by course_section_id.
If not present, events will be created for the entire course."""
if course_section_id is not None:
data["course_section_id"] = course_section_id
# OPTIONAL - events
"""An array of event objects to use."""
if events is not None:
data["events"] = events
# OPTIONAL - events[start_at]
"""Start time for the event"""
if events_start_at is not None:
data["events[start_at]"] = events_start_at
# OPTIONAL - events[end_at]
"""End time for the event"""
if events_end_at is not None:
data["events[end_at]"] = events_end_at
# OPTIONAL - events[location_name]
"""Location name for the event"""
if events_location_name is not None:
data["events[location_name]"] = events_location_name
# OPTIONAL - events[code]
"""A unique identifier that can be used to update the event at a later time
If one is not specified, an identifier will be generated based on the start and end times"""
if events_code is not None:
data["events[code]"] = events_code
self.logger.debug("POST /api/v1/courses/{course_id}/calendar_events/timetable_events with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/calendar_events/timetable_events".format(**path), data=data, params=params, no_data=True) | python | def create_or_update_events_directly_for_course_timetable(self, course_id, course_section_id=None, events=None, events_code=None, events_end_at=None, events_location_name=None, events_start_at=None):
"""
Create or update events directly for a course timetable.
Creates and updates "timetable" events for a course or course section.
Similar to {api:CalendarEventsApiController#set_course_timetable setting a course timetable},
but instead of generating a list of events based on a timetable schedule,
this endpoint expects a complete list of events.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - course_section_id
"""Events will be created for the course section specified by course_section_id.
If not present, events will be created for the entire course."""
if course_section_id is not None:
data["course_section_id"] = course_section_id
# OPTIONAL - events
"""An array of event objects to use."""
if events is not None:
data["events"] = events
# OPTIONAL - events[start_at]
"""Start time for the event"""
if events_start_at is not None:
data["events[start_at]"] = events_start_at
# OPTIONAL - events[end_at]
"""End time for the event"""
if events_end_at is not None:
data["events[end_at]"] = events_end_at
# OPTIONAL - events[location_name]
"""Location name for the event"""
if events_location_name is not None:
data["events[location_name]"] = events_location_name
# OPTIONAL - events[code]
"""A unique identifier that can be used to update the event at a later time
If one is not specified, an identifier will be generated based on the start and end times"""
if events_code is not None:
data["events[code]"] = events_code
self.logger.debug("POST /api/v1/courses/{course_id}/calendar_events/timetable_events with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/calendar_events/timetable_events".format(**path), data=data, params=params, no_data=True) | [
"def",
"create_or_update_events_directly_for_course_timetable",
"(",
"self",
",",
"course_id",
",",
"course_section_id",
"=",
"None",
",",
"events",
"=",
"None",
",",
"events_code",
"=",
"None",
",",
"events_end_at",
"=",
"None",
",",
"events_location_name",
"=",
"N... | Create or update events directly for a course timetable.
Creates and updates "timetable" events for a course or course section.
Similar to {api:CalendarEventsApiController#set_course_timetable setting a course timetable},
but instead of generating a list of events based on a timetable schedule,
this endpoint expects a complete list of events. | [
"Create",
"or",
"update",
"events",
"directly",
"for",
"a",
"course",
"timetable",
".",
"Creates",
"and",
"updates",
"timetable",
"events",
"for",
"a",
"course",
"or",
"course",
"section",
".",
"Similar",
"to",
"{",
"api",
":",
"CalendarEventsApiController#set_c... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/calendar_events.py#L488-L538 |
Adarnof/adarnauth-esi | esi/decorators.py | tokens_required | def tokens_required(scopes='', new=False):
"""
Decorator for views to request an ESI Token.
Accepts required scopes as a space-delimited string
or list of strings of scope names.
Can require a new token to be retrieved by SSO.
Returns a QueryDict of Tokens.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
# if we're coming back from SSO for a new token, return it
token = _check_callback(request)
if token and new:
tokens = Token.objects.filter(pk=token.pk)
logger.debug("Returning new token.")
return view_func(request, tokens, *args, **kwargs)
if not new:
# ensure user logged in to check existing tokens
if not request.user.is_authenticated:
logger.debug(
"Session {0} is not logged in. Redirecting to login.".format(request.session.session_key[:5]))
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.get_full_path())
# collect tokens in db, check if still valid, return if any
tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
if tokens.exists():
logger.debug("Retrieved {0} tokens for {1} session {2}".format(tokens.count(), request.user,
request.session.session_key[:5]))
return view_func(request, tokens, *args, **kwargs)
# trigger creation of new token via sso
logger.debug("No tokens identified for {0} session {1}. Redirecting to SSO.".format(request.user, request.session.session_key[:5]))
from esi.views import sso_redirect
return sso_redirect(request, scopes=scopes)
return _wrapped_view
return decorator | python | def tokens_required(scopes='', new=False):
"""
Decorator for views to request an ESI Token.
Accepts required scopes as a space-delimited string
or list of strings of scope names.
Can require a new token to be retrieved by SSO.
Returns a QueryDict of Tokens.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
# if we're coming back from SSO for a new token, return it
token = _check_callback(request)
if token and new:
tokens = Token.objects.filter(pk=token.pk)
logger.debug("Returning new token.")
return view_func(request, tokens, *args, **kwargs)
if not new:
# ensure user logged in to check existing tokens
if not request.user.is_authenticated:
logger.debug(
"Session {0} is not logged in. Redirecting to login.".format(request.session.session_key[:5]))
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.get_full_path())
# collect tokens in db, check if still valid, return if any
tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
if tokens.exists():
logger.debug("Retrieved {0} tokens for {1} session {2}".format(tokens.count(), request.user,
request.session.session_key[:5]))
return view_func(request, tokens, *args, **kwargs)
# trigger creation of new token via sso
logger.debug("No tokens identified for {0} session {1}. Redirecting to SSO.".format(request.user, request.session.session_key[:5]))
from esi.views import sso_redirect
return sso_redirect(request, scopes=scopes)
return _wrapped_view
return decorator | [
"def",
"tokens_required",
"(",
"scopes",
"=",
"''",
",",
"new",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_func",
")",
")",
"def",
"_wrapped_... | Decorator for views to request an ESI Token.
Accepts required scopes as a space-delimited string
or list of strings of scope names.
Can require a new token to be retrieved by SSO.
Returns a QueryDict of Tokens. | [
"Decorator",
"for",
"views",
"to",
"request",
"an",
"ESI",
"Token",
".",
"Accepts",
"required",
"scopes",
"as",
"a",
"space",
"-",
"delimited",
"string",
"or",
"list",
"of",
"strings",
"of",
"scope",
"names",
".",
"Can",
"require",
"a",
"new",
"token",
"... | train | https://github.com/Adarnof/adarnauth-esi/blob/f6618a31efbfeedeb96316ab9b82ecadda776ac1/esi/decorators.py#L29-L71 |
Adarnof/adarnauth-esi | esi/decorators.py | token_required | def token_required(scopes='', new=False):
"""
Decorator for views which supplies a single, user-selected token for the view to process.
Same parameters as tokens_required.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
# if we're coming back from SSO for a new token, return it
token = _check_callback(request)
if token and new:
logger.debug("Got new token from {0} session {1}. Returning to view.".format(request.user, request.session.session_key[:5]))
return view_func(request, token, *args, **kwargs)
# if we're selecting a token, return it
if request.method == 'POST':
if request.POST.get("_add", False):
logger.debug("{0} has selected to add new token. Redirecting to SSO.".format(request.user))
# user has selected to add a new token
from esi.views import sso_redirect
return sso_redirect(request, scopes=scopes)
token_pk = request.POST.get('_token', None)
if token_pk:
logger.debug("{0} has selected token {1}".format(request.user, token_pk))
try:
token = Token.objects.get(pk=token_pk)
# ensure token belongs to this user and has required scopes
if ((token.user and token.user == request.user) or not token.user) and Token.objects.filter(
pk=token_pk).require_scopes(scopes).require_valid().exists():
logger.debug("Selected token fulfills requirements of view. Returning.")
return view_func(request, token, *args, **kwargs)
except Token.DoesNotExist:
logger.debug("Token {0} not found.".format(token_pk))
pass
if not new:
# present the user with token choices
tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
if tokens.exists():
logger.debug("Returning list of available tokens for {0}.".format(request.user))
from esi.views import select_token
return select_token(request, scopes=scopes, new=new)
else:
logger.debug("No tokens found for {0} session {1} with scopes {2}".format(request.user, request.session.session_key[:5], scopes))
# prompt the user to add a new token
logger.debug("Redirecting {0} session {1} to SSO.".format(request.user, request.session.session_key[:5]))
from esi.views import sso_redirect
return sso_redirect(request, scopes=scopes)
return _wrapped_view
return decorator | python | def token_required(scopes='', new=False):
"""
Decorator for views which supplies a single, user-selected token for the view to process.
Same parameters as tokens_required.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
# if we're coming back from SSO for a new token, return it
token = _check_callback(request)
if token and new:
logger.debug("Got new token from {0} session {1}. Returning to view.".format(request.user, request.session.session_key[:5]))
return view_func(request, token, *args, **kwargs)
# if we're selecting a token, return it
if request.method == 'POST':
if request.POST.get("_add", False):
logger.debug("{0} has selected to add new token. Redirecting to SSO.".format(request.user))
# user has selected to add a new token
from esi.views import sso_redirect
return sso_redirect(request, scopes=scopes)
token_pk = request.POST.get('_token', None)
if token_pk:
logger.debug("{0} has selected token {1}".format(request.user, token_pk))
try:
token = Token.objects.get(pk=token_pk)
# ensure token belongs to this user and has required scopes
if ((token.user and token.user == request.user) or not token.user) and Token.objects.filter(
pk=token_pk).require_scopes(scopes).require_valid().exists():
logger.debug("Selected token fulfills requirements of view. Returning.")
return view_func(request, token, *args, **kwargs)
except Token.DoesNotExist:
logger.debug("Token {0} not found.".format(token_pk))
pass
if not new:
# present the user with token choices
tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
if tokens.exists():
logger.debug("Returning list of available tokens for {0}.".format(request.user))
from esi.views import select_token
return select_token(request, scopes=scopes, new=new)
else:
logger.debug("No tokens found for {0} session {1} with scopes {2}".format(request.user, request.session.session_key[:5], scopes))
# prompt the user to add a new token
logger.debug("Redirecting {0} session {1} to SSO.".format(request.user, request.session.session_key[:5]))
from esi.views import sso_redirect
return sso_redirect(request, scopes=scopes)
return _wrapped_view
return decorator | [
"def",
"token_required",
"(",
"scopes",
"=",
"''",
",",
"new",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_func",
")",
")",
"def",
"_wrapped_v... | Decorator for views which supplies a single, user-selected token for the view to process.
Same parameters as tokens_required. | [
"Decorator",
"for",
"views",
"which",
"supplies",
"a",
"single",
"user",
"-",
"selected",
"token",
"for",
"the",
"view",
"to",
"process",
".",
"Same",
"parameters",
"as",
"tokens_required",
"."
] | train | https://github.com/Adarnof/adarnauth-esi/blob/f6618a31efbfeedeb96316ab9b82ecadda776ac1/esi/decorators.py#L74-L129 |
abusix/querycontacts | querycontacts/__init__.py | ContactFinder.find | def find(self, ip):
'''
Find the abuse contact for a IP address
:param ip: IPv4 or IPv6 address to check
:type ip: string
:returns: emails associated with IP
:rtype: list
:returns: none if no contact could be found
:rtype: None
:raises: :py:class:`ValueError`: if ip is not properly formatted
'''
ip = ipaddr.IPAddress(ip)
rev = reversename(ip.exploded)
revip, _ = rev.split(3)
lookup = revip.concatenate(self.provider).to_text()
contacts = self._get_txt_record(lookup)
if contacts:
return contacts.split(',') | python | def find(self, ip):
'''
Find the abuse contact for a IP address
:param ip: IPv4 or IPv6 address to check
:type ip: string
:returns: emails associated with IP
:rtype: list
:returns: none if no contact could be found
:rtype: None
:raises: :py:class:`ValueError`: if ip is not properly formatted
'''
ip = ipaddr.IPAddress(ip)
rev = reversename(ip.exploded)
revip, _ = rev.split(3)
lookup = revip.concatenate(self.provider).to_text()
contacts = self._get_txt_record(lookup)
if contacts:
return contacts.split(',') | [
"def",
"find",
"(",
"self",
",",
"ip",
")",
":",
"ip",
"=",
"ipaddr",
".",
"IPAddress",
"(",
"ip",
")",
"rev",
"=",
"reversename",
"(",
"ip",
".",
"exploded",
")",
"revip",
",",
"_",
"=",
"rev",
".",
"split",
"(",
"3",
")",
"lookup",
"=",
"revi... | Find the abuse contact for a IP address
:param ip: IPv4 or IPv6 address to check
:type ip: string
:returns: emails associated with IP
:rtype: list
:returns: none if no contact could be found
:rtype: None
:raises: :py:class:`ValueError`: if ip is not properly formatted | [
"Find",
"the",
"abuse",
"contact",
"for",
"a",
"IP",
"address"
] | train | https://github.com/abusix/querycontacts/blob/6c04b260547b23013cccb49b416e3871a6e146da/querycontacts/__init__.py#L43-L64 |
shmir/PyIxNetwork | ixnetwork/api/ixn_tcl.py | IxnTclWrapper.add | def add(self, parent, obj_type, **attributes):
""" IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: IXN object reference.
"""
return self.ixnCommand('add', parent.obj_ref(), obj_type, get_args_pairs(attributes)) | python | def add(self, parent, obj_type, **attributes):
""" IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: IXN object reference.
"""
return self.ixnCommand('add', parent.obj_ref(), obj_type, get_args_pairs(attributes)) | [
"def",
"add",
"(",
"self",
",",
"parent",
",",
"obj_type",
",",
"*",
"*",
"attributes",
")",
":",
"return",
"self",
".",
"ixnCommand",
"(",
"'add'",
",",
"parent",
".",
"obj_ref",
"(",
")",
",",
"obj_type",
",",
"get_args_pairs",
"(",
"attributes",
")"... | IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: IXN object reference. | [
"IXN",
"API",
"add",
"command"
] | train | https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/api/ixn_tcl.py#L108-L116 |
inveniosoftware/invenio-pages | invenio_pages/admin.py | template_exists | def template_exists(form, field):
"""Form validation: check that selected template exists."""
try:
current_app.jinja_env.get_template(field.data)
except TemplateNotFound:
raise ValidationError(_("Template selected does not exist")) | python | def template_exists(form, field):
"""Form validation: check that selected template exists."""
try:
current_app.jinja_env.get_template(field.data)
except TemplateNotFound:
raise ValidationError(_("Template selected does not exist")) | [
"def",
"template_exists",
"(",
"form",
",",
"field",
")",
":",
"try",
":",
"current_app",
".",
"jinja_env",
".",
"get_template",
"(",
"field",
".",
"data",
")",
"except",
"TemplateNotFound",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"\"Template selected ... | Form validation: check that selected template exists. | [
"Form",
"validation",
":",
"check",
"that",
"selected",
"template",
"exists",
"."
] | train | https://github.com/inveniosoftware/invenio-pages/blob/8d544d72fb4c22b7134c521f435add0abed42544/invenio_pages/admin.py#L64-L69 |
inveniosoftware/invenio-pages | invenio_pages/admin.py | same_page_choosen | def same_page_choosen(form, field):
"""Check that we are not trying to assign list page itself as a child."""
if form._obj is not None:
if field.data.id == form._obj.list_id:
raise ValidationError(
_('You cannot assign list page itself as a child.')) | python | def same_page_choosen(form, field):
"""Check that we are not trying to assign list page itself as a child."""
if form._obj is not None:
if field.data.id == form._obj.list_id:
raise ValidationError(
_('You cannot assign list page itself as a child.')) | [
"def",
"same_page_choosen",
"(",
"form",
",",
"field",
")",
":",
"if",
"form",
".",
"_obj",
"is",
"not",
"None",
":",
"if",
"field",
".",
"data",
".",
"id",
"==",
"form",
".",
"_obj",
".",
"list_id",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
... | Check that we are not trying to assign list page itself as a child. | [
"Check",
"that",
"we",
"are",
"not",
"trying",
"to",
"assign",
"list",
"page",
"itself",
"as",
"a",
"child",
"."
] | train | https://github.com/inveniosoftware/invenio-pages/blob/8d544d72fb4c22b7134c521f435add0abed42544/invenio_pages/admin.py#L72-L77 |
mrstephenneal/mysql-toolkit | mysql/toolkit/utils.py | cols_str | def cols_str(columns):
"""Concatenate list of columns into a string."""
cols = ""
for c in columns:
cols = cols + wrap(c) + ', '
return cols[:-2] | python | def cols_str(columns):
"""Concatenate list of columns into a string."""
cols = ""
for c in columns:
cols = cols + wrap(c) + ', '
return cols[:-2] | [
"def",
"cols_str",
"(",
"columns",
")",
":",
"cols",
"=",
"\"\"",
"for",
"c",
"in",
"columns",
":",
"cols",
"=",
"cols",
"+",
"wrap",
"(",
"c",
")",
"+",
"', '",
"return",
"cols",
"[",
":",
"-",
"2",
"]"
] | Concatenate list of columns into a string. | [
"Concatenate",
"list",
"of",
"columns",
"into",
"a",
"string",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/utils.py#L6-L11 |
mrstephenneal/mysql-toolkit | mysql/toolkit/utils.py | join_cols | def join_cols(cols):
"""Join list of columns into a string for a SQL query"""
return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols | python | def join_cols(cols):
"""Join list of columns into a string for a SQL query"""
return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols | [
"def",
"join_cols",
"(",
"cols",
")",
":",
"return",
"\", \"",
".",
"join",
"(",
"[",
"i",
"for",
"i",
"in",
"cols",
"]",
")",
"if",
"isinstance",
"(",
"cols",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
"else",
"cols"
] | Join list of columns into a string for a SQL query | [
"Join",
"list",
"of",
"columns",
"into",
"a",
"string",
"for",
"a",
"SQL",
"query"
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/utils.py#L35-L37 |
praekelt/django-order | order/utils.py | create_order_classes | def create_order_classes(model_label, order_field_names):
"""
Create order model and admin class.
Add order model to order.models module and register admin class.
Connect ordered_objects manager to related model.
"""
# Seperate model_label into parts.
labels = resolve_labels(model_label)
# Get model class for model_label string.
model = get_model(labels['app'], labels['model'])
# Dynamic Classes
class OrderItemBase(models.Model):
"""
Dynamic order class base.
"""
item = models.ForeignKey(model_label)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
app_label = 'order'
class Admin(admin.ModelAdmin):
"""
Dynamic order admin class.
"""
list_display = ('item_link',) + tuple(order_field_names)
list_editable = order_field_names
def get_model_perms(self, request):
"""
Return empty perms dict thus hiding the model from admin index.
"""
return {}
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
list_url = reverse('admin:%s_%s_changelist' % (labels['app'], \
labels['model'].lower()))
add_url = reverse('admin:%s_%s_add' % (labels['app'], \
labels['model'].lower()))
result = super(Admin, self).changelist_view(
request,
extra_context={
'add_url': add_url,
'list_url': list_url,
'related_opts': model._meta,
}
)
# XXX: Sanitize order on list save.
# if (request.method == "POST" and self.list_editable and \
# '_save' in request.POST):
# sanitize_order(self.model)
return result
def item_link(self, obj):
url = reverse('admin:%s_%s_change' % (labels['app'], \
labels['model'].lower()), args=(obj.item.id,))
return '<a href="%s">%s</a>' % (url, str(obj.item))
item_link.allow_tags = True
item_link.short_description = 'Item'
# Set up a dictionary to simulate declarations within a class.
attrs = {
'__module__': 'order.models',
}
# Create provided order fields and add to attrs.
fields = {}
for field in order_field_names:
fields[field] = models.IntegerField()
attrs.update(fields)
# Create the class which automatically triggers Django model processing.
order_item_class_name = resolve_order_item_class_name(labels)
order_model = type(order_item_class_name, (OrderItemBase, ), attrs)
# Register admin model.
admin.site.register(order_model, Admin)
# Add user_order_by method to base QuerySet.
from order import managers
setattr(QuerySet, 'user_order_by', managers.user_order_by)
# Return created model class.
return order_model | python | def create_order_classes(model_label, order_field_names):
"""
Create order model and admin class.
Add order model to order.models module and register admin class.
Connect ordered_objects manager to related model.
"""
# Seperate model_label into parts.
labels = resolve_labels(model_label)
# Get model class for model_label string.
model = get_model(labels['app'], labels['model'])
# Dynamic Classes
class OrderItemBase(models.Model):
"""
Dynamic order class base.
"""
item = models.ForeignKey(model_label)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
app_label = 'order'
class Admin(admin.ModelAdmin):
"""
Dynamic order admin class.
"""
list_display = ('item_link',) + tuple(order_field_names)
list_editable = order_field_names
def get_model_perms(self, request):
"""
Return empty perms dict thus hiding the model from admin index.
"""
return {}
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
list_url = reverse('admin:%s_%s_changelist' % (labels['app'], \
labels['model'].lower()))
add_url = reverse('admin:%s_%s_add' % (labels['app'], \
labels['model'].lower()))
result = super(Admin, self).changelist_view(
request,
extra_context={
'add_url': add_url,
'list_url': list_url,
'related_opts': model._meta,
}
)
# XXX: Sanitize order on list save.
# if (request.method == "POST" and self.list_editable and \
# '_save' in request.POST):
# sanitize_order(self.model)
return result
def item_link(self, obj):
url = reverse('admin:%s_%s_change' % (labels['app'], \
labels['model'].lower()), args=(obj.item.id,))
return '<a href="%s">%s</a>' % (url, str(obj.item))
item_link.allow_tags = True
item_link.short_description = 'Item'
# Set up a dictionary to simulate declarations within a class.
attrs = {
'__module__': 'order.models',
}
# Create provided order fields and add to attrs.
fields = {}
for field in order_field_names:
fields[field] = models.IntegerField()
attrs.update(fields)
# Create the class which automatically triggers Django model processing.
order_item_class_name = resolve_order_item_class_name(labels)
order_model = type(order_item_class_name, (OrderItemBase, ), attrs)
# Register admin model.
admin.site.register(order_model, Admin)
# Add user_order_by method to base QuerySet.
from order import managers
setattr(QuerySet, 'user_order_by', managers.user_order_by)
# Return created model class.
return order_model | [
"def",
"create_order_classes",
"(",
"model_label",
",",
"order_field_names",
")",
":",
"# Seperate model_label into parts.",
"labels",
"=",
"resolve_labels",
"(",
"model_label",
")",
"# Get model class for model_label string.",
"model",
"=",
"get_model",
"(",
"labels",
"[",... | Create order model and admin class.
Add order model to order.models module and register admin class.
Connect ordered_objects manager to related model. | [
"Create",
"order",
"model",
"and",
"admin",
"class",
".",
"Add",
"order",
"model",
"to",
"order",
".",
"models",
"module",
"and",
"register",
"admin",
"class",
".",
"Connect",
"ordered_objects",
"manager",
"to",
"related",
"model",
"."
] | train | https://github.com/praekelt/django-order/blob/dcffeb5b28d460872f7d47675c4bfc8a32c807a3/order/utils.py#L20-L108 |
praekelt/django-order | order/utils.py | create_order_objects | def create_order_objects(model, order_fields):
"""
Create order items for objects already present in the database.
"""
for rel in model._meta.get_all_related_objects():
rel_model = rel.model
if rel_model.__module__ == 'order.models':
objs = model.objects.all()
values = {}
for order_field in order_fields:
order_objs = rel_model.objects.all().order_by('-%s' \
% order_field)
try:
values[order_field] = getattr(order_objs[0], \
order_field) + 1
except IndexError:
values[order_field] = 1
for obj in objs:
try:
rel_model.objects.get(item=obj)
except rel_model.DoesNotExist:
rel_model.objects.create(item=obj, **values)
for key in values:
values[key] += 1 | python | def create_order_objects(model, order_fields):
"""
Create order items for objects already present in the database.
"""
for rel in model._meta.get_all_related_objects():
rel_model = rel.model
if rel_model.__module__ == 'order.models':
objs = model.objects.all()
values = {}
for order_field in order_fields:
order_objs = rel_model.objects.all().order_by('-%s' \
% order_field)
try:
values[order_field] = getattr(order_objs[0], \
order_field) + 1
except IndexError:
values[order_field] = 1
for obj in objs:
try:
rel_model.objects.get(item=obj)
except rel_model.DoesNotExist:
rel_model.objects.create(item=obj, **values)
for key in values:
values[key] += 1 | [
"def",
"create_order_objects",
"(",
"model",
",",
"order_fields",
")",
":",
"for",
"rel",
"in",
"model",
".",
"_meta",
".",
"get_all_related_objects",
"(",
")",
":",
"rel_model",
"=",
"rel",
".",
"model",
"if",
"rel_model",
".",
"__module__",
"==",
"'order.m... | Create order items for objects already present in the database. | [
"Create",
"order",
"items",
"for",
"objects",
"already",
"present",
"in",
"the",
"database",
"."
] | train | https://github.com/praekelt/django-order/blob/dcffeb5b28d460872f7d47675c4bfc8a32c807a3/order/utils.py#L111-L135 |
praekelt/django-order | order/utils.py | is_orderable | def is_orderable(cls):
"""
Checks if the provided class is specified as an orderable in
settings.ORDERABLE_MODELS. If it is return its settings.
"""
if not getattr(settings, 'ORDERABLE_MODELS', None):
return False
labels = resolve_labels(cls)
if labels['app_model'] in settings.ORDERABLE_MODELS:
return settings.ORDERABLE_MODELS[labels['app_model']]
return False | python | def is_orderable(cls):
"""
Checks if the provided class is specified as an orderable in
settings.ORDERABLE_MODELS. If it is return its settings.
"""
if not getattr(settings, 'ORDERABLE_MODELS', None):
return False
labels = resolve_labels(cls)
if labels['app_model'] in settings.ORDERABLE_MODELS:
return settings.ORDERABLE_MODELS[labels['app_model']]
return False | [
"def",
"is_orderable",
"(",
"cls",
")",
":",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'ORDERABLE_MODELS'",
",",
"None",
")",
":",
"return",
"False",
"labels",
"=",
"resolve_labels",
"(",
"cls",
")",
"if",
"labels",
"[",
"'app_model'",
"]",
"in",
"s... | Checks if the provided class is specified as an orderable in
settings.ORDERABLE_MODELS. If it is return its settings. | [
"Checks",
"if",
"the",
"provided",
"class",
"is",
"specified",
"as",
"an",
"orderable",
"in",
"settings",
".",
"ORDERABLE_MODELS",
".",
"If",
"it",
"is",
"return",
"its",
"settings",
"."
] | train | https://github.com/praekelt/django-order/blob/dcffeb5b28d460872f7d47675c4bfc8a32c807a3/order/utils.py#L138-L149 |
praekelt/django-order | order/utils.py | resolve_labels | def resolve_labels(model_label):
"""
Seperate model_label into parts.
Returns dictionary with app, model and app_model strings.
"""
labels = {}
# Resolve app label.
labels['app'] = model_label.split('.')[0]
# Resolve model label
labels['model'] = model_label.split('.')[-1]
# Resolve module_app_model label.
labels['app_model'] = '%s.%s' % (labels['app'], labels['model'])
return labels | python | def resolve_labels(model_label):
"""
Seperate model_label into parts.
Returns dictionary with app, model and app_model strings.
"""
labels = {}
# Resolve app label.
labels['app'] = model_label.split('.')[0]
# Resolve model label
labels['model'] = model_label.split('.')[-1]
# Resolve module_app_model label.
labels['app_model'] = '%s.%s' % (labels['app'], labels['model'])
return labels | [
"def",
"resolve_labels",
"(",
"model_label",
")",
":",
"labels",
"=",
"{",
"}",
"# Resolve app label.",
"labels",
"[",
"'app'",
"]",
"=",
"model_label",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"# Resolve model label",
"labels",
"[",
"'model'",
"]",
"... | Seperate model_label into parts.
Returns dictionary with app, model and app_model strings. | [
"Seperate",
"model_label",
"into",
"parts",
".",
"Returns",
"dictionary",
"with",
"app",
"model",
"and",
"app_model",
"strings",
"."
] | train | https://github.com/praekelt/django-order/blob/dcffeb5b28d460872f7d47675c4bfc8a32c807a3/order/utils.py#L152-L168 |
praekelt/django-order | order/utils.py | sanitize_order | def sanitize_order(model):
"""
Sanitize order values so eliminate conflicts and gaps.
XXX: Early start, very ugly, needs work.
"""
to_order_dict = {}
order_field_names = []
for field in model._meta.fields:
if isinstance(field, models.IntegerField):
order_field_names.append(field.name)
for field_name in order_field_names:
to_order_dict[field_name] = list(model.objects.all().order_by(\
field_name, '-timestamp'))
updates = {}
for field_name, object_list in to_order_dict.items():
for i, obj in enumerate(object_list):
position = i + 1
if getattr(obj, field_name) != position:
if obj in updates:
updates[obj][field_name] = position
else:
updates[obj] = {field_name: position}
for obj, fields in updates.items():
for field, value in fields.items():
setattr(obj, field, value)
obj.save() | python | def sanitize_order(model):
"""
Sanitize order values so eliminate conflicts and gaps.
XXX: Early start, very ugly, needs work.
"""
to_order_dict = {}
order_field_names = []
for field in model._meta.fields:
if isinstance(field, models.IntegerField):
order_field_names.append(field.name)
for field_name in order_field_names:
to_order_dict[field_name] = list(model.objects.all().order_by(\
field_name, '-timestamp'))
updates = {}
for field_name, object_list in to_order_dict.items():
for i, obj in enumerate(object_list):
position = i + 1
if getattr(obj, field_name) != position:
if obj in updates:
updates[obj][field_name] = position
else:
updates[obj] = {field_name: position}
for obj, fields in updates.items():
for field, value in fields.items():
setattr(obj, field, value)
obj.save() | [
"def",
"sanitize_order",
"(",
"model",
")",
":",
"to_order_dict",
"=",
"{",
"}",
"order_field_names",
"=",
"[",
"]",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"fields",
":",
"if",
"isinstance",
"(",
"field",
",",
"models",
".",
"IntegerField",
")... | Sanitize order values so eliminate conflicts and gaps.
XXX: Early start, very ugly, needs work. | [
"Sanitize",
"order",
"values",
"so",
"eliminate",
"conflicts",
"and",
"gaps",
".",
"XXX",
":",
"Early",
"start",
"very",
"ugly",
"needs",
"work",
"."
] | train | https://github.com/praekelt/django-order/blob/dcffeb5b28d460872f7d47675c4bfc8a32c807a3/order/utils.py#L185-L214 |
theonion/django-bulbs | bulbs/api/views.py | ContentViewSet.get_serializer_class | def get_serializer_class(self):
"""gets the class type of the serializer
:return: `rest_framework.Serializer`
"""
klass = None
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg in self.kwargs:
# Looks like this is a detail...
klass = self.get_object().__class__
elif "doctype" in self.request.REQUEST:
base = self.model.get_base_class()
doctypes = indexable_registry.families[base]
try:
klass = doctypes[self.request.REQUEST["doctype"]]
except KeyError:
raise Http404
if hasattr(klass, "get_serializer_class"):
return klass.get_serializer_class()
# TODO: fix deprecation warning here -- `get_serializer_class` is going away soon!
return super(ContentViewSet, self).get_serializer_class() | python | def get_serializer_class(self):
"""gets the class type of the serializer
:return: `rest_framework.Serializer`
"""
klass = None
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg in self.kwargs:
# Looks like this is a detail...
klass = self.get_object().__class__
elif "doctype" in self.request.REQUEST:
base = self.model.get_base_class()
doctypes = indexable_registry.families[base]
try:
klass = doctypes[self.request.REQUEST["doctype"]]
except KeyError:
raise Http404
if hasattr(klass, "get_serializer_class"):
return klass.get_serializer_class()
# TODO: fix deprecation warning here -- `get_serializer_class` is going away soon!
return super(ContentViewSet, self).get_serializer_class() | [
"def",
"get_serializer_class",
"(",
"self",
")",
":",
"klass",
"=",
"None",
"lookup_url_kwarg",
"=",
"self",
".",
"lookup_url_kwarg",
"or",
"self",
".",
"lookup_field",
"if",
"lookup_url_kwarg",
"in",
"self",
".",
"kwargs",
":",
"# Looks like this is a detail...",
... | gets the class type of the serializer
:return: `rest_framework.Serializer` | [
"gets",
"the",
"class",
"type",
"of",
"the",
"serializer"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L75-L98 |
theonion/django-bulbs | bulbs/api/views.py | ContentViewSet.post_save | def post_save(self, obj, created=False):
"""indexes the object to ElasticSearch after any save function (POST/PUT)
:param obj: instance of the saved object
:param created: boolean expressing if object is newly created (`False` if updated)
:return: `rest_framework.viewset.ModelViewSet.post_save`
"""
from bulbs.content.tasks import index
index.delay(obj.polymorphic_ctype_id, obj.pk)
message = "Created" if created else "Saved"
LogEntry.objects.log(self.request.user, obj, message)
return super(ContentViewSet, self).post_save(obj, created=created) | python | def post_save(self, obj, created=False):
"""indexes the object to ElasticSearch after any save function (POST/PUT)
:param obj: instance of the saved object
:param created: boolean expressing if object is newly created (`False` if updated)
:return: `rest_framework.viewset.ModelViewSet.post_save`
"""
from bulbs.content.tasks import index
index.delay(obj.polymorphic_ctype_id, obj.pk)
message = "Created" if created else "Saved"
LogEntry.objects.log(self.request.user, obj, message)
return super(ContentViewSet, self).post_save(obj, created=created) | [
"def",
"post_save",
"(",
"self",
",",
"obj",
",",
"created",
"=",
"False",
")",
":",
"from",
"bulbs",
".",
"content",
".",
"tasks",
"import",
"index",
"index",
".",
"delay",
"(",
"obj",
".",
"polymorphic_ctype_id",
",",
"obj",
".",
"pk",
")",
"message"... | indexes the object to ElasticSearch after any save function (POST/PUT)
:param obj: instance of the saved object
:param created: boolean expressing if object is newly created (`False` if updated)
:return: `rest_framework.viewset.ModelViewSet.post_save` | [
"indexes",
"the",
"object",
"to",
"ElasticSearch",
"after",
"any",
"save",
"function",
"(",
"POST",
"/",
"PUT",
")"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L100-L113 |
theonion/django-bulbs | bulbs/api/views.py | ContentViewSet.list | def list(self, request, *args, **kwargs):
"""Modified list view to driving listing from ES"""
search_kwargs = {"published": False}
for field_name in ("before", "after", "status", "published"):
if field_name in get_query_params(self.request):
search_kwargs[field_name] = get_query_params(self.request).get(field_name)
for field_name in ("tags", "types", "feature_types"):
if field_name in get_query_params(self.request):
search_kwargs[field_name] = get_query_params(self.request).getlist(field_name)
if "search" in get_query_params(self.request):
search_kwargs["query"] = get_query_params(self.request).get("search")
queryset = self.model.search_objects.search(**search_kwargs)
if "authors" in get_query_params(self.request):
authors = get_query_params(self.request).getlist("authors")
queryset = queryset.filter(Authors(authors))
if "exclude" in get_query_params(self.request):
exclude = get_query_params(self.request).get("exclude")
queryset = queryset.filter(
es_filter.Not(es_filter.Type(**{'value': exclude}))
)
# always filter out Super Features from listing page
queryset = queryset.filter(
es_filter.Not(filter=es_filter.Type(
value=get_superfeature_model().search_objects.mapping.doc_type))
)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data) | python | def list(self, request, *args, **kwargs):
"""Modified list view to driving listing from ES"""
search_kwargs = {"published": False}
for field_name in ("before", "after", "status", "published"):
if field_name in get_query_params(self.request):
search_kwargs[field_name] = get_query_params(self.request).get(field_name)
for field_name in ("tags", "types", "feature_types"):
if field_name in get_query_params(self.request):
search_kwargs[field_name] = get_query_params(self.request).getlist(field_name)
if "search" in get_query_params(self.request):
search_kwargs["query"] = get_query_params(self.request).get("search")
queryset = self.model.search_objects.search(**search_kwargs)
if "authors" in get_query_params(self.request):
authors = get_query_params(self.request).getlist("authors")
queryset = queryset.filter(Authors(authors))
if "exclude" in get_query_params(self.request):
exclude = get_query_params(self.request).get("exclude")
queryset = queryset.filter(
es_filter.Not(es_filter.Type(**{'value': exclude}))
)
# always filter out Super Features from listing page
queryset = queryset.filter(
es_filter.Not(filter=es_filter.Type(
value=get_superfeature_model().search_objects.mapping.doc_type))
)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data) | [
"def",
"list",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"search_kwargs",
"=",
"{",
"\"published\"",
":",
"False",
"}",
"for",
"field_name",
"in",
"(",
"\"before\"",
",",
"\"after\"",
",",
"\"status\"",
",",
"\"p... | Modified list view to driving listing from ES | [
"Modified",
"list",
"view",
"to",
"driving",
"listing",
"from",
"ES"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L115-L156 |
theonion/django-bulbs | bulbs/api/views.py | ContentViewSet.publish | def publish(self, request, **kwargs):
"""sets the `published` value of the `Content`
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
if "published" in get_request_data(request):
if not get_request_data(request)["published"]:
content.published = None
else:
publish_dt = parse_datetime(get_request_data(request)["published"])
if publish_dt:
publish_dt = publish_dt.astimezone(timezone.utc)
else:
publish_dt = None
content.published = publish_dt
else:
content.published = timezone.now()
content.save()
LogEntry.objects.log(request.user, content, content.get_status())
return Response({"status": content.get_status(), "published": content.published}) | python | def publish(self, request, **kwargs):
"""sets the `published` value of the `Content`
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
if "published" in get_request_data(request):
if not get_request_data(request)["published"]:
content.published = None
else:
publish_dt = parse_datetime(get_request_data(request)["published"])
if publish_dt:
publish_dt = publish_dt.astimezone(timezone.utc)
else:
publish_dt = None
content.published = publish_dt
else:
content.published = timezone.now()
content.save()
LogEntry.objects.log(request.user, content, content.get_status())
return Response({"status": content.get_status(), "published": content.published}) | [
"def",
"publish",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"self",
".",
"get_object",
"(",
")",
"if",
"\"published\"",
"in",
"get_request_data",
"(",
"request",
")",
":",
"if",
"not",
"get_request_data",
"(",
"reque... | sets the `published` value of the `Content`
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response` | [
"sets",
"the",
"published",
"value",
"of",
"the",
"Content"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L159-L183 |
theonion/django-bulbs | bulbs/api/views.py | ContentViewSet.trash | def trash(self, request, **kwargs):
"""Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index
Content is not actually deleted, merely hidden by deleted from ES index.import
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
content.indexed = False
content.save()
LogEntry.objects.log(request.user, content, "Trashed")
return Response({"status": "Trashed"}) | python | def trash(self, request, **kwargs):
"""Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index
Content is not actually deleted, merely hidden by deleted from ES index.import
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
content.indexed = False
content.save()
LogEntry.objects.log(request.user, content, "Trashed")
return Response({"status": "Trashed"}) | [
"def",
"trash",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"self",
".",
"get_object",
"(",
")",
"content",
".",
"indexed",
"=",
"False",
"content",
".",
"save",
"(",
")",
"LogEntry",
".",
"objects",
".",
"log",
... | Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index
Content is not actually deleted, merely hidden by deleted from ES index.import
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response` | [
"Psuedo",
"-",
"deletes",
"a",
"Content",
"instance",
"and",
"removes",
"it",
"from",
"the",
"ElasticSearch",
"index"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L186-L201 |
theonion/django-bulbs | bulbs/api/views.py | ContentViewSet.status | def status(self, request, **kwargs):
"""This endpoint returns a status text, currently one of:
- "Draft" (If no publish date is set, and no item exists in the editor queue)
- "Waiting for Editor" (If no publish date is set, and an item exists in the editor queue)
- "Published" (The published date is in the past)
- "Scheduled" (The published date is set in the future)
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
return Response({"status": content.get_status()}) | python | def status(self, request, **kwargs):
"""This endpoint returns a status text, currently one of:
- "Draft" (If no publish date is set, and no item exists in the editor queue)
- "Waiting for Editor" (If no publish date is set, and an item exists in the editor queue)
- "Published" (The published date is in the past)
- "Scheduled" (The published date is set in the future)
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
return Response({"status": content.get_status()}) | [
"def",
"status",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"self",
".",
"get_object",
"(",
")",
"return",
"Response",
"(",
"{",
"\"status\"",
":",
"content",
".",
"get_status",
"(",
")",
"}",
")"
] | This endpoint returns a status text, currently one of:
- "Draft" (If no publish date is set, and no item exists in the editor queue)
- "Waiting for Editor" (If no publish date is set, and an item exists in the editor queue)
- "Published" (The published date is in the past)
- "Scheduled" (The published date is set in the future)
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response` | [
"This",
"endpoint",
"returns",
"a",
"status",
"text",
"currently",
"one",
"of",
":",
"-",
"Draft",
"(",
"If",
"no",
"publish",
"date",
"is",
"set",
"and",
"no",
"item",
"exists",
"in",
"the",
"editor",
"queue",
")",
"-",
"Waiting",
"for",
"Editor",
"("... | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L204-L216 |
theonion/django-bulbs | bulbs/api/views.py | ContentViewSet.contributions | def contributions(self, request, **kwargs):
"""gets or adds contributions
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
# Check if the contribution app is installed
if Contribution not in get_models():
return Response([])
if request.method == "POST":
serializer = ContributionSerializer(data=get_request_data(request), many=True)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return Response(serializer.data)
else:
content_pk = kwargs.get('pk', None)
if content_pk is None:
return Response([], status=status.HTTP_404_NOT_FOUND)
queryset = Contribution.search_objects.search().filter(
es_filter.Term(**{'content.id': content_pk})
)
serializer = ContributionSerializer(queryset[:queryset.count()].sort('id'), many=True)
return Response(serializer.data) | python | def contributions(self, request, **kwargs):
"""gets or adds contributions
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
# Check if the contribution app is installed
if Contribution not in get_models():
return Response([])
if request.method == "POST":
serializer = ContributionSerializer(data=get_request_data(request), many=True)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return Response(serializer.data)
else:
content_pk = kwargs.get('pk', None)
if content_pk is None:
return Response([], status=status.HTTP_404_NOT_FOUND)
queryset = Contribution.search_objects.search().filter(
es_filter.Term(**{'content.id': content_pk})
)
serializer = ContributionSerializer(queryset[:queryset.count()].sort('id'), many=True)
return Response(serializer.data) | [
"def",
"contributions",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check if the contribution app is installed",
"if",
"Contribution",
"not",
"in",
"get_models",
"(",
")",
":",
"return",
"Response",
"(",
"[",
"]",
")",
"if",
"request",
... | gets or adds contributions
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response` | [
"gets",
"or",
"adds",
"contributions"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L219-L244 |
theonion/django-bulbs | bulbs/api/views.py | ContentViewSet.create_token | def create_token(self, request, **kwargs):
"""Create a new obfuscated url info to use for accessing unpublished content.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
data = {
"content": self.get_object().id,
"create_date": get_request_data(request)["create_date"],
"expire_date": get_request_data(request)["expire_date"]
}
serializer = ObfuscatedUrlInfoSerializer(data=data)
if not serializer.is_valid():
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST,
content_type="application/json",
)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK, content_type="application/json") | python | def create_token(self, request, **kwargs):
"""Create a new obfuscated url info to use for accessing unpublished content.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
data = {
"content": self.get_object().id,
"create_date": get_request_data(request)["create_date"],
"expire_date": get_request_data(request)["expire_date"]
}
serializer = ObfuscatedUrlInfoSerializer(data=data)
if not serializer.is_valid():
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST,
content_type="application/json",
)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK, content_type="application/json") | [
"def",
"create_token",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"\"content\"",
":",
"self",
".",
"get_object",
"(",
")",
".",
"id",
",",
"\"create_date\"",
":",
"get_request_data",
"(",
"request",
")",
"[",
"\"c... | Create a new obfuscated url info to use for accessing unpublished content.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response` | [
"Create",
"a",
"new",
"obfuscated",
"url",
"info",
"to",
"use",
"for",
"accessing",
"unpublished",
"content",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L247-L269 |
theonion/django-bulbs | bulbs/api/views.py | ContentViewSet.list_tokens | def list_tokens(self, request, **kwargs):
"""List all tokens for this content instance.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
# no date checking is done here to make it more obvious if there's an issue with the
# number of records. Date filtering will be done on the frontend.
infos = [ObfuscatedUrlInfoSerializer(info).data
for info in ObfuscatedUrlInfo.objects.filter(content=self.get_object())]
return Response(infos, status=status.HTTP_200_OK, content_type="application/json") | python | def list_tokens(self, request, **kwargs):
"""List all tokens for this content instance.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
# no date checking is done here to make it more obvious if there's an issue with the
# number of records. Date filtering will be done on the frontend.
infos = [ObfuscatedUrlInfoSerializer(info).data
for info in ObfuscatedUrlInfo.objects.filter(content=self.get_object())]
return Response(infos, status=status.HTTP_200_OK, content_type="application/json") | [
"def",
"list_tokens",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# no date checking is done here to make it more obvious if there's an issue with the",
"# number of records. Date filtering will be done on the frontend.",
"infos",
"=",
"[",
"ObfuscatedUrlInfoSe... | List all tokens for this content instance.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response` | [
"List",
"all",
"tokens",
"for",
"this",
"content",
"instance",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L272-L284 |
theonion/django-bulbs | bulbs/api/views.py | LogEntryViewSet.get_queryset | def get_queryset(self):
"""creates the base queryset object for the serializer
:return: an instance of `django.db.models.QuerySet`
"""
qs = LogEntry.objects.all()
content_id = get_query_params(self.request).get("content", None)
if content_id:
qs = qs.filter(object_id=content_id)
return qs | python | def get_queryset(self):
"""creates the base queryset object for the serializer
:return: an instance of `django.db.models.QuerySet`
"""
qs = LogEntry.objects.all()
content_id = get_query_params(self.request).get("content", None)
if content_id:
qs = qs.filter(object_id=content_id)
return qs | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"LogEntry",
".",
"objects",
".",
"all",
"(",
")",
"content_id",
"=",
"get_query_params",
"(",
"self",
".",
"request",
")",
".",
"get",
"(",
"\"content\"",
",",
"None",
")",
"if",
"content_id",
":... | creates the base queryset object for the serializer
:return: an instance of `django.db.models.QuerySet` | [
"creates",
"the",
"base",
"queryset",
"object",
"for",
"the",
"serializer"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L331-L340 |
theonion/django-bulbs | bulbs/api/views.py | LogEntryViewSet.create | def create(self, request, *args, **kwargs):
"""
Grabbing the user from request.user, and the rest of the method
is the same as ModelViewSet.create().
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
:raise: 400
"""
data = get_request_data(request).copy()
data["user"] = request.user.id
serializer = self.get_serializer(data=data, files=request.FILES)
if serializer.is_valid():
self.pre_save(serializer.object)
self.object = serializer.save(force_insert=True)
self.post_save(self.object, created=True)
headers = self.get_success_headers(serializer.data)
return Response(
serializer.data,
status=status.HTTP_201_CREATED,
headers=headers
)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | python | def create(self, request, *args, **kwargs):
"""
Grabbing the user from request.user, and the rest of the method
is the same as ModelViewSet.create().
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
:raise: 400
"""
data = get_request_data(request).copy()
data["user"] = request.user.id
serializer = self.get_serializer(data=data, files=request.FILES)
if serializer.is_valid():
self.pre_save(serializer.object)
self.object = serializer.save(force_insert=True)
self.post_save(self.object, created=True)
headers = self.get_success_headers(serializer.data)
return Response(
serializer.data,
status=status.HTTP_201_CREATED,
headers=headers
)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | [
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"get_request_data",
"(",
"request",
")",
".",
"copy",
"(",
")",
"data",
"[",
"\"user\"",
"]",
"=",
"request",
".",
"user",
".",
"id",
... | Grabbing the user from request.user, and the rest of the method
is the same as ModelViewSet.create().
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
:raise: 400 | [
"Grabbing",
"the",
"user",
"from",
"request",
".",
"user",
"and",
"the",
"rest",
"of",
"the",
"method",
"is",
"the",
"same",
"as",
"ModelViewSet",
".",
"create",
"()",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L342-L368 |
theonion/django-bulbs | bulbs/api/views.py | AuthorViewSet.get_queryset | def get_queryset(self):
"""created the base queryset object for the serializer limited to users within the authors
groups and having `is_staff`
:return: `django.db.models.QuerySet`
"""
author_filter = getattr(settings, "BULBS_AUTHOR_FILTER", {"is_staff": True})
queryset = self.model.objects.filter(**author_filter).distinct()
return queryset | python | def get_queryset(self):
"""created the base queryset object for the serializer limited to users within the authors
groups and having `is_staff`
:return: `django.db.models.QuerySet`
"""
author_filter = getattr(settings, "BULBS_AUTHOR_FILTER", {"is_staff": True})
queryset = self.model.objects.filter(**author_filter).distinct()
return queryset | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"author_filter",
"=",
"getattr",
"(",
"settings",
",",
"\"BULBS_AUTHOR_FILTER\"",
",",
"{",
"\"is_staff\"",
":",
"True",
"}",
")",
"queryset",
"=",
"self",
".",
"model",
".",
"objects",
".",
"filter",
"(",
"*",... | created the base queryset object for the serializer limited to users within the authors
groups and having `is_staff`
:return: `django.db.models.QuerySet` | [
"created",
"the",
"base",
"queryset",
"object",
"for",
"the",
"serializer",
"limited",
"to",
"users",
"within",
"the",
"authors",
"groups",
"and",
"having",
"is_staff"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L381-L389 |
theonion/django-bulbs | bulbs/api/views.py | MeViewSet.retrieve | def retrieve(self, request, *args, **kwargs):
"""gets basic information about the user
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
data = UserSerializer().to_representation(request.user)
# add superuser flag only if user is a superuser, putting it here so users can only
# tell if they are themselves superusers
if request.user.is_superuser:
data['is_superuser'] = True
# attempt to add a firebase token if we have a firebase secret
secret = getattr(settings, 'FIREBASE_SECRET', None)
if secret:
# use firebase auth to provide auth variables to firebase security api
firebase_auth_payload = {
'id': request.user.pk,
'username': request.user.username,
'email': request.user.email,
'is_staff': request.user.is_staff
}
data['firebase_token'] = create_token(secret, firebase_auth_payload)
return Response(data) | python | def retrieve(self, request, *args, **kwargs):
"""gets basic information about the user
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
data = UserSerializer().to_representation(request.user)
# add superuser flag only if user is a superuser, putting it here so users can only
# tell if they are themselves superusers
if request.user.is_superuser:
data['is_superuser'] = True
# attempt to add a firebase token if we have a firebase secret
secret = getattr(settings, 'FIREBASE_SECRET', None)
if secret:
# use firebase auth to provide auth variables to firebase security api
firebase_auth_payload = {
'id': request.user.pk,
'username': request.user.username,
'email': request.user.email,
'is_staff': request.user.is_staff
}
data['firebase_token'] = create_token(secret, firebase_auth_payload)
return Response(data) | [
"def",
"retrieve",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"UserSerializer",
"(",
")",
".",
"to_representation",
"(",
"request",
".",
"user",
")",
"# add superuser flag only if user is a superuser, putting i... | gets basic information about the user
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response` | [
"gets",
"basic",
"information",
"about",
"the",
"user"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L416-L443 |
theonion/django-bulbs | bulbs/api/views.py | ContentTypeViewSet.list | def list(self, request):
"""Search the doctypes for this model."""
query = get_query_params(request).get("search", "")
results = []
base = self.model.get_base_class()
doctypes = indexable_registry.families[base]
for doctype, klass in doctypes.items():
name = klass._meta.verbose_name.title()
if query.lower() in name.lower():
results.append(dict(
name=name,
doctype=doctype
))
results.sort(key=lambda x: x["name"])
return Response(dict(results=results)) | python | def list(self, request):
"""Search the doctypes for this model."""
query = get_query_params(request).get("search", "")
results = []
base = self.model.get_base_class()
doctypes = indexable_registry.families[base]
for doctype, klass in doctypes.items():
name = klass._meta.verbose_name.title()
if query.lower() in name.lower():
results.append(dict(
name=name,
doctype=doctype
))
results.sort(key=lambda x: x["name"])
return Response(dict(results=results)) | [
"def",
"list",
"(",
"self",
",",
"request",
")",
":",
"query",
"=",
"get_query_params",
"(",
"request",
")",
".",
"get",
"(",
"\"search\"",
",",
"\"\"",
")",
"results",
"=",
"[",
"]",
"base",
"=",
"self",
".",
"model",
".",
"get_base_class",
"(",
")"... | Search the doctypes for this model. | [
"Search",
"the",
"doctypes",
"for",
"this",
"model",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L450-L464 |
theonion/django-bulbs | bulbs/api/views.py | CustomSearchContentViewSet.list | def list(self, request, *args, **kwargs):
"""Filter Content with a custom search.
{
"query": SEARCH_QUERY
"preview": true
}
"preview" is optional and, when true, will include
items that would normally be removed due to "excluded_ids".
"""
queryset = self.get_filtered_queryset(get_request_data(request))
# Switch between paginated or standard style responses
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data) | python | def list(self, request, *args, **kwargs):
"""Filter Content with a custom search.
{
"query": SEARCH_QUERY
"preview": true
}
"preview" is optional and, when true, will include
items that would normally be removed due to "excluded_ids".
"""
queryset = self.get_filtered_queryset(get_request_data(request))
# Switch between paginated or standard style responses
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data) | [
"def",
"list",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"self",
".",
"get_filtered_queryset",
"(",
"get_request_data",
"(",
"request",
")",
")",
"# Switch between paginated or standard style responses",
"... | Filter Content with a custom search.
{
"query": SEARCH_QUERY
"preview": true
}
"preview" is optional and, when true, will include
items that would normally be removed due to "excluded_ids". | [
"Filter",
"Content",
"with",
"a",
"custom",
"search",
".",
"{",
"query",
":",
"SEARCH_QUERY",
"preview",
":",
"true",
"}",
"preview",
"is",
"optional",
"and",
"when",
"true",
"will",
"include",
"items",
"that",
"would",
"normally",
"be",
"removed",
"due",
... | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L555-L573 |
theonion/django-bulbs | bulbs/api/views.py | CustomSearchContentViewSet.create | def create(self, request, *args, **kwargs):
"""HACK: couldn't get POST to the list endpoint without
messing up POST for the other list_routes so I'm doing this.
Maybe something to do with the router?
"""
return self.list(request, *args, **kwargs) | python | def create(self, request, *args, **kwargs):
"""HACK: couldn't get POST to the list endpoint without
messing up POST for the other list_routes so I'm doing this.
Maybe something to do with the router?
"""
return self.list(request, *args, **kwargs) | [
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"list",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | HACK: couldn't get POST to the list endpoint without
messing up POST for the other list_routes so I'm doing this.
Maybe something to do with the router? | [
"HACK",
":",
"couldn",
"t",
"get",
"POST",
"to",
"the",
"list",
"endpoint",
"without",
"messing",
"up",
"POST",
"for",
"the",
"other",
"list_routes",
"so",
"I",
"m",
"doing",
"this",
".",
"Maybe",
"something",
"to",
"do",
"with",
"the",
"router?"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L575-L580 |
PGower/PyCanvas | pycanvas/apis/course_audit_log.py | CourseAuditLogAPI.query_by_course | def query_by_course(self, course_id, end_time=None, start_time=None):
"""
Query by course.
List course change events for a given course.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - start_time
"""The beginning of the time range from which you want events."""
if start_time is not None:
params["start_time"] = start_time
# OPTIONAL - end_time
"""The end of the time range from which you want events."""
if end_time is not None:
params["end_time"] = end_time
self.logger.debug("GET /api/v1/audit/course/courses/{course_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/audit/course/courses/{course_id}".format(**path), data=data, params=params, all_pages=True) | python | def query_by_course(self, course_id, end_time=None, start_time=None):
"""
Query by course.
List course change events for a given course.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - start_time
"""The beginning of the time range from which you want events."""
if start_time is not None:
params["start_time"] = start_time
# OPTIONAL - end_time
"""The end of the time range from which you want events."""
if end_time is not None:
params["end_time"] = end_time
self.logger.debug("GET /api/v1/audit/course/courses/{course_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/audit/course/courses/{course_id}".format(**path), data=data, params=params, all_pages=True) | [
"def",
"query_by_course",
"(",
"self",
",",
"course_id",
",",
"end_time",
"=",
"None",
",",
"start_time",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"pa... | Query by course.
List course change events for a given course. | [
"Query",
"by",
"course",
".",
"List",
"course",
"change",
"events",
"for",
"a",
"given",
"course",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/course_audit_log.py#L19-L44 |
lordmauve/lepton | examples/tunnel.py | vary_radius | def vary_radius(dt):
"""Vary the disc radius over time"""
global time
time += dt
disc.inner_radius = disc.outer_radius = 2.5 + math.sin(time / 2.0) * 1.5 | python | def vary_radius(dt):
"""Vary the disc radius over time"""
global time
time += dt
disc.inner_radius = disc.outer_radius = 2.5 + math.sin(time / 2.0) * 1.5 | [
"def",
"vary_radius",
"(",
"dt",
")",
":",
"global",
"time",
"time",
"+=",
"dt",
"disc",
".",
"inner_radius",
"=",
"disc",
".",
"outer_radius",
"=",
"2.5",
"+",
"math",
".",
"sin",
"(",
"time",
"/",
"2.0",
")",
"*",
"1.5"
] | Vary the disc radius over time | [
"Vary",
"the",
"disc",
"radius",
"over",
"time"
] | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/tunnel.py#L86-L90 |
arpitbbhayani/flasksr | flasksr/sr/layoutsr.py | LayoutSR._aggregate | def _aggregate(self):
'''
The function aggreagtes all pre_stream, layout and post_stream and
components, and yields them one by one.
'''
# Yielding everything under pre_stream
for x in self._yield_all(self.pre_stream): yield x
# Yielding layout
for x in self._yield_all(self.layout): yield x
# Yield LayoutSR Specific Content
yield """
<div id="%s">
<script>
var MyFlaskSRMutationObserver = (function () {
var prefixes = ['WebKit', 'Moz', 'O', 'Ms', '']
for(var i=0; i < prefixes.length; i++) {
if(prefixes[i] + 'MutationObserver' in window) {
return window[prefixes[i] + 'MutationObserver'];
}
}
return false;
}());
if(MyFlaskSRMutationObserver) {
var target = document.getElementById('%s');
var observerFlaskSR = new MyFlaskSRMutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var obj = mutation.addedNodes[0];
if(obj instanceof HTMLElement) {
var referenceId = obj.getAttribute('sr-id');
if(referenceId) {
document.getElementById('%s').querySelectorAll("*[ref-sr-id='"+referenceId+"']")[0].innerHTML = obj.innerHTML;
obj.innerHTML = '';
}
}
});
});
var config = {
childList: true
}
observerFlaskSR.observe(target, config);
document.addEventListener("DOMContentLoaded", function(event) {
observerFlaskSR.disconnect();
});
}
else {
console.log("MutationObserver not found!");
}
</script>""" % (
self.stream_div_id,
self.stream_div_id,
self.stream_div_layout_id
)
# Yielding components
for x in self._yield_all(self.components): yield x
# Yield LayoutSR Specific Content
yield """</div>"""
# Yielding everything under post_stream
for x in self._yield_all(self.post_stream): yield x | python | def _aggregate(self):
'''
The function aggreagtes all pre_stream, layout and post_stream and
components, and yields them one by one.
'''
# Yielding everything under pre_stream
for x in self._yield_all(self.pre_stream): yield x
# Yielding layout
for x in self._yield_all(self.layout): yield x
# Yield LayoutSR Specific Content
yield """
<div id="%s">
<script>
var MyFlaskSRMutationObserver = (function () {
var prefixes = ['WebKit', 'Moz', 'O', 'Ms', '']
for(var i=0; i < prefixes.length; i++) {
if(prefixes[i] + 'MutationObserver' in window) {
return window[prefixes[i] + 'MutationObserver'];
}
}
return false;
}());
if(MyFlaskSRMutationObserver) {
var target = document.getElementById('%s');
var observerFlaskSR = new MyFlaskSRMutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var obj = mutation.addedNodes[0];
if(obj instanceof HTMLElement) {
var referenceId = obj.getAttribute('sr-id');
if(referenceId) {
document.getElementById('%s').querySelectorAll("*[ref-sr-id='"+referenceId+"']")[0].innerHTML = obj.innerHTML;
obj.innerHTML = '';
}
}
});
});
var config = {
childList: true
}
observerFlaskSR.observe(target, config);
document.addEventListener("DOMContentLoaded", function(event) {
observerFlaskSR.disconnect();
});
}
else {
console.log("MutationObserver not found!");
}
</script>""" % (
self.stream_div_id,
self.stream_div_id,
self.stream_div_layout_id
)
# Yielding components
for x in self._yield_all(self.components): yield x
# Yield LayoutSR Specific Content
yield """</div>"""
# Yielding everything under post_stream
for x in self._yield_all(self.post_stream): yield x | [
"def",
"_aggregate",
"(",
"self",
")",
":",
"# Yielding everything under pre_stream",
"for",
"x",
"in",
"self",
".",
"_yield_all",
"(",
"self",
".",
"pre_stream",
")",
":",
"yield",
"x",
"# Yielding layout",
"for",
"x",
"in",
"self",
".",
"_yield_all",
"(",
... | The function aggreagtes all pre_stream, layout and post_stream and
components, and yields them one by one. | [
"The",
"function",
"aggreagtes",
"all",
"pre_stream",
"layout",
"and",
"post_stream",
"and",
"components",
"and",
"yields",
"them",
"one",
"by",
"one",
"."
] | train | https://github.com/arpitbbhayani/flasksr/blob/69c7dc071f52ac9d3691ff98bcc94fcd55b1a264/flasksr/sr/layoutsr.py#L65-L128 |
icholy/durationpy | durationpy/duration.py | from_str | def from_str(duration):
"""Parse a duration string to a datetime.timedelta"""
if duration in ("0", "+0", "-0"):
return datetime.timedelta()
pattern = re.compile('([\d\.]+)([a-zµμ]+)')
total = 0
sign = -1 if duration[0] == '-' else 1
matches = pattern.findall(duration)
if not len(matches):
raise Exception("Invalid duration {}".format(duration))
for (value, unit) in matches:
if unit not in units:
raise Exception(
"Unknown unit {} in duration {}".format(unit, duration))
try:
total += float(value) * units[unit]
except:
raise Exception(
"Invalid value {} in duration {}".format(value, duration))
microseconds = total / _microsecond_size
return datetime.timedelta(microseconds=sign * microseconds) | python | def from_str(duration):
"""Parse a duration string to a datetime.timedelta"""
if duration in ("0", "+0", "-0"):
return datetime.timedelta()
pattern = re.compile('([\d\.]+)([a-zµμ]+)')
total = 0
sign = -1 if duration[0] == '-' else 1
matches = pattern.findall(duration)
if not len(matches):
raise Exception("Invalid duration {}".format(duration))
for (value, unit) in matches:
if unit not in units:
raise Exception(
"Unknown unit {} in duration {}".format(unit, duration))
try:
total += float(value) * units[unit]
except:
raise Exception(
"Invalid value {} in duration {}".format(value, duration))
microseconds = total / _microsecond_size
return datetime.timedelta(microseconds=sign * microseconds) | [
"def",
"from_str",
"(",
"duration",
")",
":",
"if",
"duration",
"in",
"(",
"\"0\"",
",",
"\"+0\"",
",",
"\"-0\"",
")",
":",
"return",
"datetime",
".",
"timedelta",
"(",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'([\\d\\.]+)([a-zµμ]+)')",
"",
"tota... | Parse a duration string to a datetime.timedelta | [
"Parse",
"a",
"duration",
"string",
"to",
"a",
"datetime",
".",
"timedelta"
] | train | https://github.com/icholy/durationpy/blob/c67ec62dc6e28807c8a06a23074459cf1671aac0/durationpy/duration.py#L33-L58 |
icholy/durationpy | durationpy/duration.py | to_str | def to_str(delta, extended=False):
"""Format a datetime.timedelta to a duration string"""
total_seconds = delta.total_seconds()
sign = "-" if total_seconds < 0 else ""
nanoseconds = abs(total_seconds * _second_size)
if total_seconds < 1:
result_str = _to_str_small(nanoseconds, extended)
else:
result_str = _to_str_large(nanoseconds, extended)
return "{}{}".format(sign, result_str) | python | def to_str(delta, extended=False):
"""Format a datetime.timedelta to a duration string"""
total_seconds = delta.total_seconds()
sign = "-" if total_seconds < 0 else ""
nanoseconds = abs(total_seconds * _second_size)
if total_seconds < 1:
result_str = _to_str_small(nanoseconds, extended)
else:
result_str = _to_str_large(nanoseconds, extended)
return "{}{}".format(sign, result_str) | [
"def",
"to_str",
"(",
"delta",
",",
"extended",
"=",
"False",
")",
":",
"total_seconds",
"=",
"delta",
".",
"total_seconds",
"(",
")",
"sign",
"=",
"\"-\"",
"if",
"total_seconds",
"<",
"0",
"else",
"\"\"",
"nanoseconds",
"=",
"abs",
"(",
"total_seconds",
... | Format a datetime.timedelta to a duration string | [
"Format",
"a",
"datetime",
".",
"timedelta",
"to",
"a",
"duration",
"string"
] | train | https://github.com/icholy/durationpy/blob/c67ec62dc6e28807c8a06a23074459cf1671aac0/durationpy/duration.py#L60-L72 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/alter.py | Alter.rename | def rename(self, old_table, new_table):
"""
Rename a table.
You must have ALTER and DROP privileges for the original table,
and CREATE and INSERT privileges for the new table.
"""
try:
command = 'RENAME TABLE {0} TO {1}'.format(wrap(old_table), wrap(new_table))
except:
command = 'ALTER TABLE {0} RENAME {1}'.format(wrap(old_table), wrap(new_table))
self.execute(command)
self._printer('Renamed {0} to {1}'.format(wrap(old_table), wrap(new_table)))
return old_table, new_table | python | def rename(self, old_table, new_table):
"""
Rename a table.
You must have ALTER and DROP privileges for the original table,
and CREATE and INSERT privileges for the new table.
"""
try:
command = 'RENAME TABLE {0} TO {1}'.format(wrap(old_table), wrap(new_table))
except:
command = 'ALTER TABLE {0} RENAME {1}'.format(wrap(old_table), wrap(new_table))
self.execute(command)
self._printer('Renamed {0} to {1}'.format(wrap(old_table), wrap(new_table)))
return old_table, new_table | [
"def",
"rename",
"(",
"self",
",",
"old_table",
",",
"new_table",
")",
":",
"try",
":",
"command",
"=",
"'RENAME TABLE {0} TO {1}'",
".",
"format",
"(",
"wrap",
"(",
"old_table",
")",
",",
"wrap",
"(",
"new_table",
")",
")",
"except",
":",
"command",
"="... | Rename a table.
You must have ALTER and DROP privileges for the original table,
and CREATE and INSERT privileges for the new table. | [
"Rename",
"a",
"table",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/alter.py#L6-L19 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/alter.py | Alter.create_database | def create_database(self, name):
"""Create a new database."""
statement = "CREATE DATABASE {0} DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci".format(wrap(name))
return self.execute(statement) | python | def create_database(self, name):
"""Create a new database."""
statement = "CREATE DATABASE {0} DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci".format(wrap(name))
return self.execute(statement) | [
"def",
"create_database",
"(",
"self",
",",
"name",
")",
":",
"statement",
"=",
"\"CREATE DATABASE {0} DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci\"",
".",
"format",
"(",
"wrap",
"(",
"name",
")",
")",
"return",
"self",
".",
"execute",
"(",
"statement",
"... | Create a new database. | [
"Create",
"a",
"new",
"database",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/alter.py#L25-L28 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/alter.py | Alter.create_table | def create_table(self, name, data, columns=None, add_pk=True):
"""Generate and execute a create table query by parsing a 2D dataset"""
# TODO: Issue occurs when bool values exist in data
# Remove if the table exists
if name in self.tables:
self.drop(name)
# Set headers list
if not columns:
columns = data[0]
# Validate data shape
for row in data:
assert len(row) == len(columns)
# Create dictionary of column types
col_types = {columns[i]: sql_column_type([d[i] for d in data], prefer_int=True, prefer_varchar=True)
for i in range(0, len(columns))}
# Join column types into SQL string
cols = ''.join(['\t{0} {1},\n'.format(name, type_) for name, type_ in col_types.items()])[:-2] + '\n'
statement = 'CREATE TABLE {0} ({1}{2})'.format(name, '\n', cols)
self.execute(statement)
if add_pk:
self.set_primary_key_auto()
return True | python | def create_table(self, name, data, columns=None, add_pk=True):
"""Generate and execute a create table query by parsing a 2D dataset"""
# TODO: Issue occurs when bool values exist in data
# Remove if the table exists
if name in self.tables:
self.drop(name)
# Set headers list
if not columns:
columns = data[0]
# Validate data shape
for row in data:
assert len(row) == len(columns)
# Create dictionary of column types
col_types = {columns[i]: sql_column_type([d[i] for d in data], prefer_int=True, prefer_varchar=True)
for i in range(0, len(columns))}
# Join column types into SQL string
cols = ''.join(['\t{0} {1},\n'.format(name, type_) for name, type_ in col_types.items()])[:-2] + '\n'
statement = 'CREATE TABLE {0} ({1}{2})'.format(name, '\n', cols)
self.execute(statement)
if add_pk:
self.set_primary_key_auto()
return True | [
"def",
"create_table",
"(",
"self",
",",
"name",
",",
"data",
",",
"columns",
"=",
"None",
",",
"add_pk",
"=",
"True",
")",
":",
"# TODO: Issue occurs when bool values exist in data",
"# Remove if the table exists",
"if",
"name",
"in",
"self",
".",
"tables",
":",
... | Generate and execute a create table query by parsing a 2D dataset | [
"Generate",
"and",
"execute",
"a",
"create",
"table",
"query",
"by",
"parsing",
"a",
"2D",
"dataset"
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/alter.py#L30-L55 |
ricardosasilva/pagseguro-python | pagseguro/api/v2/notification.py | Notification._get_notification | def _get_notification(self, email, token):
''' Consulta o status do pagamento '''
url = u'{notification_url}{notification_code}?email={email}&token={token}'.format(
notification_url=self.notification_url,
notification_code=self.notification_code,
email=email,
token=token)
req = requests.get(url)
if req.status_code == 200:
self.xml = req.text
logger.debug( u'XML com informacoes da transacao recebido: {0}'.format(self.xml) )
transaction_dict = xmltodict.parse(self.xml)
# Validar informações recebidas
transaction_schema(transaction_dict)
self.transaction = transaction_dict.get('transaction')
else:
raise PagSeguroApiException(
u'Erro ao fazer request para a API de notificacao:' +
' HTTP Status=%s - Response: %s' % (req.status_code, req.text)) | python | def _get_notification(self, email, token):
''' Consulta o status do pagamento '''
url = u'{notification_url}{notification_code}?email={email}&token={token}'.format(
notification_url=self.notification_url,
notification_code=self.notification_code,
email=email,
token=token)
req = requests.get(url)
if req.status_code == 200:
self.xml = req.text
logger.debug( u'XML com informacoes da transacao recebido: {0}'.format(self.xml) )
transaction_dict = xmltodict.parse(self.xml)
# Validar informações recebidas
transaction_schema(transaction_dict)
self.transaction = transaction_dict.get('transaction')
else:
raise PagSeguroApiException(
u'Erro ao fazer request para a API de notificacao:' +
' HTTP Status=%s - Response: %s' % (req.status_code, req.text)) | [
"def",
"_get_notification",
"(",
"self",
",",
"email",
",",
"token",
")",
":",
"url",
"=",
"u'{notification_url}{notification_code}?email={email}&token={token}'",
".",
"format",
"(",
"notification_url",
"=",
"self",
".",
"notification_url",
",",
"notification_code",
"="... | Consulta o status do pagamento | [
"Consulta",
"o",
"status",
"do",
"pagamento"
] | train | https://github.com/ricardosasilva/pagseguro-python/blob/8e39d1b0585684c460b86073d1fb3f33112b5b3d/pagseguro/api/v2/notification.py#L30-L48 |
ricardosasilva/pagseguro-python | pagseguro/api/v2/notification.py | Notification.items | def items(self):
''' Lista dos items do pagamento
'''
if type(self.transaction['items']['item']) == list:
return self.transaction['items']['item']
else:
return [self.transaction['items']['item'],] | python | def items(self):
''' Lista dos items do pagamento
'''
if type(self.transaction['items']['item']) == list:
return self.transaction['items']['item']
else:
return [self.transaction['items']['item'],] | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"type",
"(",
"self",
".",
"transaction",
"[",
"'items'",
"]",
"[",
"'item'",
"]",
")",
"==",
"list",
":",
"return",
"self",
".",
"transaction",
"[",
"'items'",
"]",
"[",
"'item'",
"]",
"else",
":",
"retu... | Lista dos items do pagamento | [
"Lista",
"dos",
"items",
"do",
"pagamento"
] | train | https://github.com/ricardosasilva/pagseguro-python/blob/8e39d1b0585684c460b86073d1fb3f33112b5b3d/pagseguro/api/v2/notification.py#L51-L57 |
PGower/PyCanvas | pycanvas/apis/polls.py | PollsAPI.create_single_poll | def create_single_poll(self, polls_question, polls_description=None):
"""
Create a single poll.
Create a new poll for the current user
"""
path = {}
data = {}
params = {}
# REQUIRED - polls[question]
"""The title of the poll."""
data["polls[question]"] = polls_question
# OPTIONAL - polls[description]
"""A brief description or instructions for the poll."""
if polls_description is not None:
data["polls[description]"] = polls_description
self.logger.debug("POST /api/v1/polls with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/polls".format(**path), data=data, params=params, no_data=True) | python | def create_single_poll(self, polls_question, polls_description=None):
"""
Create a single poll.
Create a new poll for the current user
"""
path = {}
data = {}
params = {}
# REQUIRED - polls[question]
"""The title of the poll."""
data["polls[question]"] = polls_question
# OPTIONAL - polls[description]
"""A brief description or instructions for the poll."""
if polls_description is not None:
data["polls[description]"] = polls_description
self.logger.debug("POST /api/v1/polls with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/polls".format(**path), data=data, params=params, no_data=True) | [
"def",
"create_single_poll",
"(",
"self",
",",
"polls_question",
",",
"polls_description",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - polls[question]\r",
"\"\"\"The title of the poll.\"\"\"",
"data",... | Create a single poll.
Create a new poll for the current user | [
"Create",
"a",
"single",
"poll",
".",
"Create",
"a",
"new",
"poll",
"for",
"the",
"current",
"user"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/polls.py#L49-L69 |
saghul/evergreen | evergreen/lib/socket.py | create_connection | def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
err = None
for res in getaddrinfo(host, port, 0 if has_ipv6 else AF_INET, SOCK_STREAM):
af, socktype, proto, _canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except error:
err = sys.exc_info()[1]
six.exc_clear()
if sock is not None:
sock.close()
if err is not None:
raise err
else:
raise error("getaddrinfo returns an empty list") | python | def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
err = None
for res in getaddrinfo(host, port, 0 if has_ipv6 else AF_INET, SOCK_STREAM):
af, socktype, proto, _canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except error:
err = sys.exc_info()[1]
six.exc_clear()
if sock is not None:
sock.close()
if err is not None:
raise err
else:
raise error("getaddrinfo returns an empty list") | [
"def",
"create_connection",
"(",
"address",
",",
"timeout",
"=",
"_GLOBAL_DEFAULT_TIMEOUT",
",",
"source_address",
"=",
"None",
")",
":",
"host",
",",
"port",
"=",
"address",
"err",
"=",
"None",
"for",
"res",
"in",
"getaddrinfo",
"(",
"host",
",",
"port",
... | Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default. | [
"Connect",
"to",
"*",
"address",
"*",
"and",
"return",
"the",
"socket",
"object",
"."
] | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/lib/socket.py#L504-L538 |
theonion/django-bulbs | bulbs/content/models.py | content_deleted | def content_deleted(sender, instance=None, **kwargs):
"""removes content from the ES index when deleted from DB
"""
if getattr(instance, "_index", True):
cls = instance.get_real_instance_class()
index = cls.search_objects.mapping.index
doc_type = cls.search_objects.mapping.doc_type
cls.search_objects.client.delete(index, doc_type, instance.id, ignore=[404]) | python | def content_deleted(sender, instance=None, **kwargs):
"""removes content from the ES index when deleted from DB
"""
if getattr(instance, "_index", True):
cls = instance.get_real_instance_class()
index = cls.search_objects.mapping.index
doc_type = cls.search_objects.mapping.doc_type
cls.search_objects.client.delete(index, doc_type, instance.id, ignore=[404]) | [
"def",
"content_deleted",
"(",
"sender",
",",
"instance",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"getattr",
"(",
"instance",
",",
"\"_index\"",
",",
"True",
")",
":",
"cls",
"=",
"instance",
".",
"get_real_instance_class",
"(",
")",
"index... | removes content from the ES index when deleted from DB | [
"removes",
"content",
"from",
"the",
"ES",
"index",
"when",
"deleted",
"from",
"DB"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L613-L621 |
theonion/django-bulbs | bulbs/content/models.py | Tag.save | def save(self, *args, **kwargs):
"""sets the `slug` values as the name
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()`
"""
self.slug = slugify(self.name)[:50]
return super(Tag, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""sets the `slug` values as the name
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()`
"""
self.slug = slugify(self.name)[:50]
return super(Tag, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"slug",
"=",
"slugify",
"(",
"self",
".",
"name",
")",
"[",
":",
"50",
"]",
"return",
"super",
"(",
"Tag",
",",
"self",
")",
".",
"save",
"(",
"*",
... | sets the `slug` values as the name
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()` | [
"sets",
"the",
"slug",
"values",
"as",
"the",
"name"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L69-L77 |
theonion/django-bulbs | bulbs/content/models.py | FeatureType.save | def save(self, *args, **kwargs):
"""sets the `slug` values as the name
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()`
"""
if self.slug is None or self.slug == "":
self.slug = slugify(self.name)
feature_type = super(FeatureType, self).save(*args, **kwargs)
if self.instant_article_is_dirty:
index_feature_type_content.delay(self.pk)
self._db_instant_article = self.instant_article
# Run all behaviors for `create`
if self.is_new:
update_feature_type_rates.delay(self.pk)
return feature_type | python | def save(self, *args, **kwargs):
"""sets the `slug` values as the name
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()`
"""
if self.slug is None or self.slug == "":
self.slug = slugify(self.name)
feature_type = super(FeatureType, self).save(*args, **kwargs)
if self.instant_article_is_dirty:
index_feature_type_content.delay(self.pk)
self._db_instant_article = self.instant_article
# Run all behaviors for `create`
if self.is_new:
update_feature_type_rates.delay(self.pk)
return feature_type | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"slug",
"is",
"None",
"or",
"self",
".",
"slug",
"==",
"\"\"",
":",
"self",
".",
"slug",
"=",
"slugify",
"(",
"self",
".",
"name",
")",
"feature... | sets the `slug` values as the name
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()` | [
"sets",
"the",
"slug",
"values",
"as",
"the",
"name"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L130-L151 |
theonion/django-bulbs | bulbs/content/models.py | Content.thumbnail | def thumbnail(self):
"""Read-only attribute that provides the value of the thumbnail to display.
"""
# check if there is a valid thumbnail override
if self.thumbnail_override.id is not None:
return self.thumbnail_override
# otherwise, just try to grab the first image
first_image = self.first_image
if first_image is not None:
return first_image
# no override for thumbnail and no non-none image field, just return override,
# which is a blank image field
return self.thumbnail_override | python | def thumbnail(self):
"""Read-only attribute that provides the value of the thumbnail to display.
"""
# check if there is a valid thumbnail override
if self.thumbnail_override.id is not None:
return self.thumbnail_override
# otherwise, just try to grab the first image
first_image = self.first_image
if first_image is not None:
return first_image
# no override for thumbnail and no non-none image field, just return override,
# which is a blank image field
return self.thumbnail_override | [
"def",
"thumbnail",
"(",
"self",
")",
":",
"# check if there is a valid thumbnail override",
"if",
"self",
".",
"thumbnail_override",
".",
"id",
"is",
"not",
"None",
":",
"return",
"self",
".",
"thumbnail_override",
"# otherwise, just try to grab the first image",
"first_... | Read-only attribute that provides the value of the thumbnail to display. | [
"Read",
"-",
"only",
"attribute",
"that",
"provides",
"the",
"value",
"of",
"the",
"thumbnail",
"to",
"display",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L261-L275 |
theonion/django-bulbs | bulbs/content/models.py | Content.first_image | def first_image(self):
"""Ready-only attribute that provides the value of the first non-none image that's
not the thumbnail override field.
"""
# loop through image fields and grab the first non-none one
for model_field in self._meta.fields:
if isinstance(model_field, ImageField):
if model_field.name is not 'thumbnail_override':
field_value = getattr(self, model_field.name)
if field_value.id is not None:
return field_value
# no non-none images, return None
return None | python | def first_image(self):
"""Ready-only attribute that provides the value of the first non-none image that's
not the thumbnail override field.
"""
# loop through image fields and grab the first non-none one
for model_field in self._meta.fields:
if isinstance(model_field, ImageField):
if model_field.name is not 'thumbnail_override':
field_value = getattr(self, model_field.name)
if field_value.id is not None:
return field_value
# no non-none images, return None
return None | [
"def",
"first_image",
"(",
"self",
")",
":",
"# loop through image fields and grab the first non-none one",
"for",
"model_field",
"in",
"self",
".",
"_meta",
".",
"fields",
":",
"if",
"isinstance",
"(",
"model_field",
",",
"ImageField",
")",
":",
"if",
"model_field"... | Ready-only attribute that provides the value of the first non-none image that's
not the thumbnail override field. | [
"Ready",
"-",
"only",
"attribute",
"that",
"provides",
"the",
"value",
"of",
"the",
"first",
"non",
"-",
"none",
"image",
"that",
"s",
"not",
"the",
"thumbnail",
"override",
"field",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L278-L291 |
theonion/django-bulbs | bulbs/content/models.py | Content.get_absolute_url | def get_absolute_url(self):
"""produces a url to link directly to this instance, given the URL config
:return: `str`
"""
try:
url = reverse("content-detail-view", kwargs={"pk": self.pk, "slug": self.slug})
except NoReverseMatch:
url = None
return url | python | def get_absolute_url(self):
"""produces a url to link directly to this instance, given the URL config
:return: `str`
"""
try:
url = reverse("content-detail-view", kwargs={"pk": self.pk, "slug": self.slug})
except NoReverseMatch:
url = None
return url | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"try",
":",
"url",
"=",
"reverse",
"(",
"\"content-detail-view\"",
",",
"kwargs",
"=",
"{",
"\"pk\"",
":",
"self",
".",
"pk",
",",
"\"slug\"",
":",
"self",
".",
"slug",
"}",
")",
"except",
"NoReverseMatch... | produces a url to link directly to this instance, given the URL config
:return: `str` | [
"produces",
"a",
"url",
"to",
"link",
"directly",
"to",
"this",
"instance",
"given",
"the",
"URL",
"config"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L306-L315 |
theonion/django-bulbs | bulbs/content/models.py | Content.is_published | def is_published(self):
"""determines if the content is/should be live
:return: `bool`
"""
if self.published:
now = timezone.now()
if now >= self.published:
return True
return False | python | def is_published(self):
"""determines if the content is/should be live
:return: `bool`
"""
if self.published:
now = timezone.now()
if now >= self.published:
return True
return False | [
"def",
"is_published",
"(",
"self",
")",
":",
"if",
"self",
".",
"published",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"if",
"now",
">=",
"self",
".",
"published",
":",
"return",
"True",
"return",
"False"
] | determines if the content is/should be live
:return: `bool` | [
"determines",
"if",
"the",
"content",
"is",
"/",
"should",
"be",
"live"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L346-L355 |
theonion/django-bulbs | bulbs/content/models.py | Content.ordered_tags | def ordered_tags(self):
"""gets the related tags
:return: `list` of `Tag` instances
"""
tags = list(self.tags.all())
return sorted(
tags,
key=lambda tag: ((type(tag) != Tag) * 100000) + tag.count(),
reverse=True
) | python | def ordered_tags(self):
"""gets the related tags
:return: `list` of `Tag` instances
"""
tags = list(self.tags.all())
return sorted(
tags,
key=lambda tag: ((type(tag) != Tag) * 100000) + tag.count(),
reverse=True
) | [
"def",
"ordered_tags",
"(",
"self",
")",
":",
"tags",
"=",
"list",
"(",
"self",
".",
"tags",
".",
"all",
"(",
")",
")",
"return",
"sorted",
"(",
"tags",
",",
"key",
"=",
"lambda",
"tag",
":",
"(",
"(",
"type",
"(",
"tag",
")",
"!=",
"Tag",
")",... | gets the related tags
:return: `list` of `Tag` instances | [
"gets",
"the",
"related",
"tags"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L357-L367 |
theonion/django-bulbs | bulbs/content/models.py | Content.save | def save(self, *args, **kwargs):
"""creates the slug, queues up for indexing and saves the instance
:param args: inline arguments (optional)
:param kwargs: keyword arguments
:return: `bulbs.content.Content`
"""
if not self.slug:
self.slug = slugify(self.build_slug())[:self._meta.get_field("slug").max_length]
if not self.is_indexed:
if kwargs is None:
kwargs = {}
kwargs["index"] = False
content = super(Content, self).save(*args, **kwargs)
index_content_contributions.delay(self.id)
index_content_report_content_proxy.delay(self.id)
post_to_instant_articles_api.delay(self.id)
return content | python | def save(self, *args, **kwargs):
"""creates the slug, queues up for indexing and saves the instance
:param args: inline arguments (optional)
:param kwargs: keyword arguments
:return: `bulbs.content.Content`
"""
if not self.slug:
self.slug = slugify(self.build_slug())[:self._meta.get_field("slug").max_length]
if not self.is_indexed:
if kwargs is None:
kwargs = {}
kwargs["index"] = False
content = super(Content, self).save(*args, **kwargs)
index_content_contributions.delay(self.id)
index_content_report_content_proxy.delay(self.id)
post_to_instant_articles_api.delay(self.id)
return content | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"slug",
":",
"self",
".",
"slug",
"=",
"slugify",
"(",
"self",
".",
"build_slug",
"(",
")",
")",
"[",
":",
"self",
".",
"_meta",
".",
"... | creates the slug, queues up for indexing and saves the instance
:param args: inline arguments (optional)
:param kwargs: keyword arguments
:return: `bulbs.content.Content` | [
"creates",
"the",
"slug",
"queues",
"up",
"for",
"indexing",
"and",
"saves",
"the",
"instance"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L380-L398 |
theonion/django-bulbs | bulbs/content/models.py | Content.percolate_special_coverage | def percolate_special_coverage(self, max_size=10, sponsored_only=False):
"""gets list of active, sponsored special coverages containing this content via
Elasticsearch Percolator (see SpecialCoverage._save_percolator)
Sorting:
1) Manually added
2) Most recent start date
"""
# Elasticsearch v1.4 percolator range query does not support DateTime range queries
# (PercolateContext.nowInMillisImpl is not implemented). Once using
# v1.6+ we can instead compare "start_date/end_date" to python DateTime
now_epoch = datetime_to_epoch_seconds(timezone.now())
MANUALLY_ADDED_BOOST = 10
SPONSORED_BOOST = 100 # Must be order of magnitude higher than "Manual" boost
# Unsponsored boosting to either lower priority or exclude
if sponsored_only:
# Omit unsponsored
unsponsored_boost = 0
else:
# Below sponsored (inverse boost, since we're filtering on "sponsored=False"
unsponsored_boost = (1.0 / SPONSORED_BOOST)
# ES v1.4 has more limited percolator capabilities than later
# implementations. As such, in order to get this to work, we need to
# sort via scoring_functions, and then manually filter out zero scores.
sponsored_filter = {
"query": {
"function_score": {
"functions": [
# Boost Recent Special Coverage
# Base score is start time
# Note: ES 1.4 sorting granularity is poor for times
# within 1 hour of each other.
{
# v1.4 "field_value_factor" does not yet support
# "missing" param, and so must filter on whether
# "start_date" field exists.
"filter": {
"exists": {
"field": "start_date",
},
},
"field_value_factor": {
"field": "start_date",
}
},
{
# Related to above, if "start_date" not found, omit
# via zero score.
"filter": {
"not": {
"exists": {
"field": "start_date",
},
},
},
"weight": 0,
},
# Ignore non-special-coverage percolator entries
{
"filter": {
"not": {
"prefix": {"_id": "specialcoverage"},
},
},
"weight": 0,
},
# Boost Manually Added Content
{
"filter": {
"terms": {
"included_ids": [self.id],
}
},
"weight": MANUALLY_ADDED_BOOST,
},
# Penalize Inactive (Zero Score Will be Omitted)
{
"filter": {
"or": [
{
"range": {
"start_date_epoch": {
"gt": now_epoch,
},
}
},
{
"range": {
"end_date_epoch": {
"lte": now_epoch,
},
}
},
],
},
"weight": 0,
},
# Penalize Unsponsored (will either exclude or lower
# based on "sponsored_only" flag)
{
"filter": {
"term": {
"sponsored": False,
}
},
"weight": unsponsored_boost,
},
],
},
},
"sort": "_score", # The only sort method supported by ES v1.4 percolator
"size": max_size, # Required for sort
}
results = _percolate(index=self.mapping.index,
doc_type=self.mapping.doc_type,
content_id=self.id,
body=sponsored_filter)
return [r["_id"] for r in results
# Zero score used to omit results via scoring function (ex: inactive)
if r['_score'] > 0] | python | def percolate_special_coverage(self, max_size=10, sponsored_only=False):
"""gets list of active, sponsored special coverages containing this content via
Elasticsearch Percolator (see SpecialCoverage._save_percolator)
Sorting:
1) Manually added
2) Most recent start date
"""
# Elasticsearch v1.4 percolator range query does not support DateTime range queries
# (PercolateContext.nowInMillisImpl is not implemented). Once using
# v1.6+ we can instead compare "start_date/end_date" to python DateTime
now_epoch = datetime_to_epoch_seconds(timezone.now())
MANUALLY_ADDED_BOOST = 10
SPONSORED_BOOST = 100 # Must be order of magnitude higher than "Manual" boost
# Unsponsored boosting to either lower priority or exclude
if sponsored_only:
# Omit unsponsored
unsponsored_boost = 0
else:
# Below sponsored (inverse boost, since we're filtering on "sponsored=False"
unsponsored_boost = (1.0 / SPONSORED_BOOST)
# ES v1.4 has more limited percolator capabilities than later
# implementations. As such, in order to get this to work, we need to
# sort via scoring_functions, and then manually filter out zero scores.
sponsored_filter = {
"query": {
"function_score": {
"functions": [
# Boost Recent Special Coverage
# Base score is start time
# Note: ES 1.4 sorting granularity is poor for times
# within 1 hour of each other.
{
# v1.4 "field_value_factor" does not yet support
# "missing" param, and so must filter on whether
# "start_date" field exists.
"filter": {
"exists": {
"field": "start_date",
},
},
"field_value_factor": {
"field": "start_date",
}
},
{
# Related to above, if "start_date" not found, omit
# via zero score.
"filter": {
"not": {
"exists": {
"field": "start_date",
},
},
},
"weight": 0,
},
# Ignore non-special-coverage percolator entries
{
"filter": {
"not": {
"prefix": {"_id": "specialcoverage"},
},
},
"weight": 0,
},
# Boost Manually Added Content
{
"filter": {
"terms": {
"included_ids": [self.id],
}
},
"weight": MANUALLY_ADDED_BOOST,
},
# Penalize Inactive (Zero Score Will be Omitted)
{
"filter": {
"or": [
{
"range": {
"start_date_epoch": {
"gt": now_epoch,
},
}
},
{
"range": {
"end_date_epoch": {
"lte": now_epoch,
},
}
},
],
},
"weight": 0,
},
# Penalize Unsponsored (will either exclude or lower
# based on "sponsored_only" flag)
{
"filter": {
"term": {
"sponsored": False,
}
},
"weight": unsponsored_boost,
},
],
},
},
"sort": "_score", # The only sort method supported by ES v1.4 percolator
"size": max_size, # Required for sort
}
results = _percolate(index=self.mapping.index,
doc_type=self.mapping.doc_type,
content_id=self.id,
body=sponsored_filter)
return [r["_id"] for r in results
# Zero score used to omit results via scoring function (ex: inactive)
if r['_score'] > 0] | [
"def",
"percolate_special_coverage",
"(",
"self",
",",
"max_size",
"=",
"10",
",",
"sponsored_only",
"=",
"False",
")",
":",
"# Elasticsearch v1.4 percolator range query does not support DateTime range queries",
"# (PercolateContext.nowInMillisImpl is not implemented). Once using",
"... | gets list of active, sponsored special coverages containing this content via
Elasticsearch Percolator (see SpecialCoverage._save_percolator)
Sorting:
1) Manually added
2) Most recent start date | [
"gets",
"list",
"of",
"active",
"sponsored",
"special",
"coverages",
"containing",
"this",
"content",
"via",
"Elasticsearch",
"Percolator",
"(",
"see",
"SpecialCoverage",
".",
"_save_percolator",
")"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L412-L543 |
theonion/django-bulbs | bulbs/content/models.py | LogEntryManager.log | def log(self, user, content, message):
"""creates a new log record
:param user: user
:param content: content instance
:param message: change information
"""
return self.create(
user=user,
content_type=ContentType.objects.get_for_model(content),
object_id=content.pk,
change_message=message
) | python | def log(self, user, content, message):
"""creates a new log record
:param user: user
:param content: content instance
:param message: change information
"""
return self.create(
user=user,
content_type=ContentType.objects.get_for_model(content),
object_id=content.pk,
change_message=message
) | [
"def",
"log",
"(",
"self",
",",
"user",
",",
"content",
",",
"message",
")",
":",
"return",
"self",
".",
"create",
"(",
"user",
"=",
"user",
",",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"content",
")",
",",
"objec... | creates a new log record
:param user: user
:param content: content instance
:param message: change information | [
"creates",
"a",
"new",
"log",
"record"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L552-L564 |
theonion/django-bulbs | bulbs/content/models.py | ObfuscatedUrlInfo.save | def save(self, *args, **kwargs):
"""sets uuid for url
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()`
"""
if not self.id: # this is a totally new instance, create uuid value
self.url_uuid = str(uuid.uuid4()).replace("-", "")
super(ObfuscatedUrlInfo, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""sets uuid for url
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()`
"""
if not self.id: # this is a totally new instance, create uuid value
self.url_uuid = str(uuid.uuid4()).replace("-", "")
super(ObfuscatedUrlInfo, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"id",
":",
"# this is a totally new instance, create uuid value",
"self",
".",
"url_uuid",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
... | sets uuid for url
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()` | [
"sets",
"uuid",
"for",
"url"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L597-L606 |
Sliim/soundcloud-syncer | ssyncer/splaylist.py | splaylist.write_playlist_file | def write_playlist_file(self, localdir):
""" Check if playlist exists in local directory. """
path = "{0}/playlists".format(localdir)
if not os.path.exists(path):
os.makedirs(path)
filepath = "{0}/{1}".format(path, self.gen_filename())
playlist = open(filepath, "w")
for track in self.get_tracks():
playlist.write("{0}/{1}.mp3\n".format(
os.path.abspath(track.gen_localdir(localdir)),
track.gen_filename()))
playlist.close() | python | def write_playlist_file(self, localdir):
""" Check if playlist exists in local directory. """
path = "{0}/playlists".format(localdir)
if not os.path.exists(path):
os.makedirs(path)
filepath = "{0}/{1}".format(path, self.gen_filename())
playlist = open(filepath, "w")
for track in self.get_tracks():
playlist.write("{0}/{1}.mp3\n".format(
os.path.abspath(track.gen_localdir(localdir)),
track.gen_filename()))
playlist.close() | [
"def",
"write_playlist_file",
"(",
"self",
",",
"localdir",
")",
":",
"path",
"=",
"\"{0}/playlists\"",
".",
"format",
"(",
"localdir",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
... | Check if playlist exists in local directory. | [
"Check",
"if",
"playlist",
"exists",
"in",
"local",
"directory",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/splaylist.py#L76-L88 |
anomaly/prestans | prestans/types/model.py | Model.getmembers | def getmembers(self):
"""
:return: list of members as name, type tuples
:rtype: list
"""
return filter(
lambda m: not m[0].startswith("__") and not inspect.isfunction(m[1]) and not inspect.ismethod(m[1]),
inspect.getmembers(self.__class__)
) | python | def getmembers(self):
"""
:return: list of members as name, type tuples
:rtype: list
"""
return filter(
lambda m: not m[0].startswith("__") and not inspect.isfunction(m[1]) and not inspect.ismethod(m[1]),
inspect.getmembers(self.__class__)
) | [
"def",
"getmembers",
"(",
"self",
")",
":",
"return",
"filter",
"(",
"lambda",
"m",
":",
"not",
"m",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"__\"",
")",
"and",
"not",
"inspect",
".",
"isfunction",
"(",
"m",
"[",
"1",
"]",
")",
"and",
"not",
"in... | :return: list of members as name, type tuples
:rtype: list | [
":",
"return",
":",
"list",
"of",
"members",
"as",
"name",
"type",
"tuples",
":",
"rtype",
":",
"list"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/model.py#L64-L72 |
anomaly/prestans | prestans/types/model.py | Model._create_instance_attributes | def _create_instance_attributes(self, arguments):
"""
Copies class level attribute templates and makes instance placeholders
This step is required for direct uses of Model classes. This creates a
copy of attribute_names ignores methods and private variables.
DataCollection types are deep copied to ignore memory reference conflicts.
DataType instances are initialized to None or default value.
"""
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
self._templates[attribute_name] = type_instance
value = None
if attribute_name in arguments:
value = arguments[attribute_name]
try:
self._attributes[attribute_name] = type_instance.validate(value)
# we can safely ignore required warnings during initialization
except exception.RequiredAttributeError:
self._attributes[attribute_name] = None | python | def _create_instance_attributes(self, arguments):
"""
Copies class level attribute templates and makes instance placeholders
This step is required for direct uses of Model classes. This creates a
copy of attribute_names ignores methods and private variables.
DataCollection types are deep copied to ignore memory reference conflicts.
DataType instances are initialized to None or default value.
"""
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
self._templates[attribute_name] = type_instance
value = None
if attribute_name in arguments:
value = arguments[attribute_name]
try:
self._attributes[attribute_name] = type_instance.validate(value)
# we can safely ignore required warnings during initialization
except exception.RequiredAttributeError:
self._attributes[attribute_name] = None | [
"def",
"_create_instance_attributes",
"(",
"self",
",",
"arguments",
")",
":",
"for",
"attribute_name",
",",
"type_instance",
"in",
"self",
".",
"getmembers",
"(",
")",
":",
"if",
"isinstance",
"(",
"type_instance",
",",
"DataType",
")",
":",
"self",
".",
"_... | Copies class level attribute templates and makes instance placeholders
This step is required for direct uses of Model classes. This creates a
copy of attribute_names ignores methods and private variables.
DataCollection types are deep copied to ignore memory reference conflicts.
DataType instances are initialized to None or default value. | [
"Copies",
"class",
"level",
"attribute",
"templates",
"and",
"makes",
"instance",
"placeholders"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/model.py#L160-L182 |
anomaly/prestans | prestans/types/model.py | Model.get_attribute_keys | def get_attribute_keys(self):
"""
Returns a list of managed attributes for the Model class
Implemented for use with data adapters, can be used to quickly make a list of the
attribute names in a prestans model
"""
_attribute_keys = list()
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
_attribute_keys.append(attribute_name)
return _attribute_keys | python | def get_attribute_keys(self):
"""
Returns a list of managed attributes for the Model class
Implemented for use with data adapters, can be used to quickly make a list of the
attribute names in a prestans model
"""
_attribute_keys = list()
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
_attribute_keys.append(attribute_name)
return _attribute_keys | [
"def",
"get_attribute_keys",
"(",
"self",
")",
":",
"_attribute_keys",
"=",
"list",
"(",
")",
"for",
"attribute_name",
",",
"type_instance",
"in",
"self",
".",
"getmembers",
"(",
")",
":",
"if",
"isinstance",
"(",
"type_instance",
",",
"DataType",
")",
":",
... | Returns a list of managed attributes for the Model class
Implemented for use with data adapters, can be used to quickly make a list of the
attribute names in a prestans model | [
"Returns",
"a",
"list",
"of",
"managed",
"attributes",
"for",
"the",
"Model",
"class"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/model.py#L184-L199 |
anomaly/prestans | prestans/types/model.py | Model.validate | def validate(self, value, attribute_filter=None, minified=False):
"""
:param value: serializable input to validate
:type value: dict | None
:param attribute_filter:
:type: prestans.parser.AttributeFilter | None
:param minified: whether or not the input is minified
:type minified: bool
:return: the validated model
:rtype: Model
"""
if self._required and (value is None or not isinstance(value, dict)):
"""
Model level validation requires a parsed dictionary
this is done by the serializer
"""
raise exception.RequiredAttributeError()
if not self._required and not value:
"""
Value was not provided by caller, but require a template
"""
return None
_model_instance = self.__class__()
rewrite_map = self.attribute_rewrite_map()
from prestans.parser import AttributeFilter
from prestans.parser import AttributeFilterImmutable
for attribute_name, type_instance in self.getmembers():
if not isinstance(type_instance, DataType):
raise TypeError("%s must be a DataType subclass" % attribute_name)
if isinstance(attribute_filter, (AttributeFilter, AttributeFilterImmutable)) and \
not attribute_filter.is_attribute_visible(attribute_name):
_model_instance._attributes[attribute_name] = None
continue
validation_input = None
input_value_key = attribute_name
# minification support
if minified is True:
input_value_key = rewrite_map[attribute_name]
if input_value_key in value:
validation_input = value[input_value_key]
try:
if isinstance(type_instance, DataCollection):
sub_attribute_filter = None
if attribute_filter and attribute_name in attribute_filter:
sub_attribute_filter = getattr(attribute_filter, attribute_name)
validated_object = type_instance.validate(
validation_input,
sub_attribute_filter,
minified
)
else:
validated_object = type_instance.validate(validation_input)
_model_instance._attributes[attribute_name] = validated_object
except exception.DataValidationException as exp:
raise exception.ValidationError(
message=str(exp),
attribute_name=attribute_name,
value=validation_input,
blueprint=type_instance.blueprint()
)
return _model_instance | python | def validate(self, value, attribute_filter=None, minified=False):
"""
:param value: serializable input to validate
:type value: dict | None
:param attribute_filter:
:type: prestans.parser.AttributeFilter | None
:param minified: whether or not the input is minified
:type minified: bool
:return: the validated model
:rtype: Model
"""
if self._required and (value is None or not isinstance(value, dict)):
"""
Model level validation requires a parsed dictionary
this is done by the serializer
"""
raise exception.RequiredAttributeError()
if not self._required and not value:
"""
Value was not provided by caller, but require a template
"""
return None
_model_instance = self.__class__()
rewrite_map = self.attribute_rewrite_map()
from prestans.parser import AttributeFilter
from prestans.parser import AttributeFilterImmutable
for attribute_name, type_instance in self.getmembers():
if not isinstance(type_instance, DataType):
raise TypeError("%s must be a DataType subclass" % attribute_name)
if isinstance(attribute_filter, (AttributeFilter, AttributeFilterImmutable)) and \
not attribute_filter.is_attribute_visible(attribute_name):
_model_instance._attributes[attribute_name] = None
continue
validation_input = None
input_value_key = attribute_name
# minification support
if minified is True:
input_value_key = rewrite_map[attribute_name]
if input_value_key in value:
validation_input = value[input_value_key]
try:
if isinstance(type_instance, DataCollection):
sub_attribute_filter = None
if attribute_filter and attribute_name in attribute_filter:
sub_attribute_filter = getattr(attribute_filter, attribute_name)
validated_object = type_instance.validate(
validation_input,
sub_attribute_filter,
minified
)
else:
validated_object = type_instance.validate(validation_input)
_model_instance._attributes[attribute_name] = validated_object
except exception.DataValidationException as exp:
raise exception.ValidationError(
message=str(exp),
attribute_name=attribute_name,
value=validation_input,
blueprint=type_instance.blueprint()
)
return _model_instance | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"attribute_filter",
"=",
"None",
",",
"minified",
"=",
"False",
")",
":",
"if",
"self",
".",
"_required",
"and",
"(",
"value",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
... | :param value: serializable input to validate
:type value: dict | None
:param attribute_filter:
:type: prestans.parser.AttributeFilter | None
:param minified: whether or not the input is minified
:type minified: bool
:return: the validated model
:rtype: Model | [
":",
"param",
"value",
":",
"serializable",
"input",
"to",
"validate",
":",
"type",
"value",
":",
"dict",
"|",
"None",
":",
"param",
"attribute_filter",
":",
":",
"type",
":",
"prestans",
".",
"parser",
".",
"AttributeFilter",
"|",
"None",
":",
"param",
... | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/model.py#L215-L292 |
anomaly/prestans | prestans/types/model.py | Model.attribute_rewrite_map | def attribute_rewrite_map(self):
"""
Example: long_name -> a_b
:return: the rewrite map
:rtype: dict
"""
rewrite_map = dict()
token_rewrite_map = self.generate_attribute_token_rewrite_map()
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
attribute_tokens = attribute_name.split('_')
rewritten_attribute_name = ''
for token in attribute_tokens:
rewritten_attribute_name += token_rewrite_map[token] + "_"
# remove the trailing underscore
rewritten_attribute_name = rewritten_attribute_name[:-1]
rewrite_map[attribute_name] = rewritten_attribute_name
return rewrite_map | python | def attribute_rewrite_map(self):
"""
Example: long_name -> a_b
:return: the rewrite map
:rtype: dict
"""
rewrite_map = dict()
token_rewrite_map = self.generate_attribute_token_rewrite_map()
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
attribute_tokens = attribute_name.split('_')
rewritten_attribute_name = ''
for token in attribute_tokens:
rewritten_attribute_name += token_rewrite_map[token] + "_"
# remove the trailing underscore
rewritten_attribute_name = rewritten_attribute_name[:-1]
rewrite_map[attribute_name] = rewritten_attribute_name
return rewrite_map | [
"def",
"attribute_rewrite_map",
"(",
"self",
")",
":",
"rewrite_map",
"=",
"dict",
"(",
")",
"token_rewrite_map",
"=",
"self",
".",
"generate_attribute_token_rewrite_map",
"(",
")",
"for",
"attribute_name",
",",
"type_instance",
"in",
"self",
".",
"getmembers",
"(... | Example: long_name -> a_b
:return: the rewrite map
:rtype: dict | [
"Example",
":",
"long_name",
"-",
">",
"a_b"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/model.py#L294-L318 |
anomaly/prestans | prestans/types/model.py | Model.as_serializable | def as_serializable(self, attribute_filter=None, minified=False):
"""
Returns a dictionary with attributes and pure python representation of
the data instances. If an attribute filter is provided as_serializable
will respect the visibility.
The response is used by serializers to return data to client
:param attribute_filter:
:type attribute_filter: prestans.parser.AttributeFilter
:param minified:
:type minified: bool
"""
from prestans.parser import AttributeFilter
from prestans.parser import AttributeFilterImmutable
from prestans.types import Array
model_dictionary = dict()
rewrite_map = self.attribute_rewrite_map()
# convert filter to immutable if it isn't already
if isinstance(attribute_filter, AttributeFilter):
attribute_filter = attribute_filter.as_immutable()
for attribute_name, type_instance in self.getmembers():
if isinstance(attribute_filter, (AttributeFilter, AttributeFilterImmutable)) and \
not attribute_filter.is_attribute_visible(attribute_name):
continue
# support minification
serialized_attribute_name = attribute_name
if minified is True:
serialized_attribute_name = rewrite_map[attribute_name]
if attribute_name not in self._attributes or self._attributes[attribute_name] is None:
if isinstance(type_instance, Array):
model_dictionary[serialized_attribute_name] = []
else:
model_dictionary[serialized_attribute_name] = None
continue
if isinstance(type_instance, DataCollection):
sub_attribute_filter = None
if isinstance(attribute_filter, (AttributeFilter, AttributeFilterImmutable)) and attribute_name in attribute_filter:
sub_attribute_filter = getattr(attribute_filter, attribute_name)
model_dictionary[serialized_attribute_name] = self._attributes[attribute_name].as_serializable(sub_attribute_filter, minified)
elif isinstance(type_instance, DataStructure):
python_value = self._attributes[attribute_name]
serializable_value = type_instance.as_serializable(python_value)
model_dictionary[serialized_attribute_name] = serializable_value
elif isinstance(type_instance, DataType):
model_dictionary[serialized_attribute_name] = self._attributes[attribute_name]
return model_dictionary | python | def as_serializable(self, attribute_filter=None, minified=False):
"""
Returns a dictionary with attributes and pure python representation of
the data instances. If an attribute filter is provided as_serializable
will respect the visibility.
The response is used by serializers to return data to client
:param attribute_filter:
:type attribute_filter: prestans.parser.AttributeFilter
:param minified:
:type minified: bool
"""
from prestans.parser import AttributeFilter
from prestans.parser import AttributeFilterImmutable
from prestans.types import Array
model_dictionary = dict()
rewrite_map = self.attribute_rewrite_map()
# convert filter to immutable if it isn't already
if isinstance(attribute_filter, AttributeFilter):
attribute_filter = attribute_filter.as_immutable()
for attribute_name, type_instance in self.getmembers():
if isinstance(attribute_filter, (AttributeFilter, AttributeFilterImmutable)) and \
not attribute_filter.is_attribute_visible(attribute_name):
continue
# support minification
serialized_attribute_name = attribute_name
if minified is True:
serialized_attribute_name = rewrite_map[attribute_name]
if attribute_name not in self._attributes or self._attributes[attribute_name] is None:
if isinstance(type_instance, Array):
model_dictionary[serialized_attribute_name] = []
else:
model_dictionary[serialized_attribute_name] = None
continue
if isinstance(type_instance, DataCollection):
sub_attribute_filter = None
if isinstance(attribute_filter, (AttributeFilter, AttributeFilterImmutable)) and attribute_name in attribute_filter:
sub_attribute_filter = getattr(attribute_filter, attribute_name)
model_dictionary[serialized_attribute_name] = self._attributes[attribute_name].as_serializable(sub_attribute_filter, minified)
elif isinstance(type_instance, DataStructure):
python_value = self._attributes[attribute_name]
serializable_value = type_instance.as_serializable(python_value)
model_dictionary[serialized_attribute_name] = serializable_value
elif isinstance(type_instance, DataType):
model_dictionary[serialized_attribute_name] = self._attributes[attribute_name]
return model_dictionary | [
"def",
"as_serializable",
"(",
"self",
",",
"attribute_filter",
"=",
"None",
",",
"minified",
"=",
"False",
")",
":",
"from",
"prestans",
".",
"parser",
"import",
"AttributeFilter",
"from",
"prestans",
".",
"parser",
"import",
"AttributeFilterImmutable",
"from",
... | Returns a dictionary with attributes and pure python representation of
the data instances. If an attribute filter is provided as_serializable
will respect the visibility.
The response is used by serializers to return data to client
:param attribute_filter:
:type attribute_filter: prestans.parser.AttributeFilter
:param minified:
:type minified: bool | [
"Returns",
"a",
"dictionary",
"with",
"attributes",
"and",
"pure",
"python",
"representation",
"of",
"the",
"data",
"instances",
".",
"If",
"an",
"attribute",
"filter",
"is",
"provided",
"as_serializable",
"will",
"respect",
"the",
"visibility",
"."
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/model.py#L434-L493 |
PGower/PyCanvas | pycanvas/apis/enrollments.py | EnrollmentsAPI.list_enrollments_courses | def list_enrollments_courses(self, course_id, grading_period_id=None, include=None, role=None, sis_account_id=None, sis_course_id=None, sis_section_id=None, sis_user_id=None, state=None, type=None, user_id=None):
"""
List enrollments.
Depending on the URL given, return either (1) all of the enrollments in
a course, (2) all of the enrollments in a section or (3) all of a user's
enrollments. This includes student, teacher, TA, and observer enrollments.
If a user has multiple enrollments in a context (e.g. as a teacher
and a student or in multiple course sections), each enrollment will be
listed separately.
note: Currently, only an admin user can return other users' enrollments. A
user can, however, return his/her own enrollments.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - type
"""A list of enrollment types to return. Accepted values are
'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment',
'DesignerEnrollment', and 'ObserverEnrollment.' If omitted, all enrollment
types are returned. This argument is ignored if `role` is given."""
if type is not None:
params["type"] = type
# OPTIONAL - role
"""A list of enrollment roles to return. Accepted values include course-level
roles created by the {api:RoleOverridesController#add_role Add Role API}
as well as the base enrollment types accepted by the `type` argument above."""
if role is not None:
params["role"] = role
# OPTIONAL - state
"""Filter by enrollment state. If omitted, 'active' and 'invited' enrollments
are returned. When querying a user's enrollments (either via user_id
argument or via user enrollments endpoint), the following additional
synthetic states are supported: "current_and_invited"|"current_and_future"|"current_and_concluded""""
if state is not None:
self._validate_enum(state, ["active", "invited", "creation_pending", "deleted", "rejected", "completed", "inactive"])
params["state"] = state
# OPTIONAL - include
"""Array of additional information to include on the enrollment or user records.
"avatar_url" and "group_ids" will be returned on the user record."""
if include is not None:
self._validate_enum(include, ["avatar_url", "group_ids", "locked", "observed_users", "can_be_removed"])
params["include"] = include
# OPTIONAL - user_id
"""Filter by user_id (only valid for course or section enrollment
queries). If set to the current user's id, this is a way to
determine if the user has any enrollments in the course or section,
independent of whether the user has permission to view other people
on the roster."""
if user_id is not None:
params["user_id"] = user_id
# OPTIONAL - grading_period_id
"""Return grades for the given grading_period. If this parameter is not
specified, the returned grades will be for the whole course."""
if grading_period_id is not None:
params["grading_period_id"] = grading_period_id
# OPTIONAL - sis_account_id
"""Returns only enrollments for the specified SIS account ID(s). Does not
look into subaccounts. May pass in array or string."""
if sis_account_id is not None:
params["sis_account_id"] = sis_account_id
# OPTIONAL - sis_course_id
"""Returns only enrollments matching the specified SIS course ID(s).
May pass in array or string."""
if sis_course_id is not None:
params["sis_course_id"] = sis_course_id
# OPTIONAL - sis_section_id
"""Returns only section enrollments matching the specified SIS section ID(s).
May pass in array or string."""
if sis_section_id is not None:
params["sis_section_id"] = sis_section_id
# OPTIONAL - sis_user_id
"""Returns only enrollments for the specified SIS user ID(s). May pass in
array or string."""
if sis_user_id is not None:
params["sis_user_id"] = sis_user_id
self.logger.debug("GET /api/v1/courses/{course_id}/enrollments with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/enrollments".format(**path), data=data, params=params, all_pages=True) | python | def list_enrollments_courses(self, course_id, grading_period_id=None, include=None, role=None, sis_account_id=None, sis_course_id=None, sis_section_id=None, sis_user_id=None, state=None, type=None, user_id=None):
"""
List enrollments.
Depending on the URL given, return either (1) all of the enrollments in
a course, (2) all of the enrollments in a section or (3) all of a user's
enrollments. This includes student, teacher, TA, and observer enrollments.
If a user has multiple enrollments in a context (e.g. as a teacher
and a student or in multiple course sections), each enrollment will be
listed separately.
note: Currently, only an admin user can return other users' enrollments. A
user can, however, return his/her own enrollments.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - type
"""A list of enrollment types to return. Accepted values are
'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment',
'DesignerEnrollment', and 'ObserverEnrollment.' If omitted, all enrollment
types are returned. This argument is ignored if `role` is given."""
if type is not None:
params["type"] = type
# OPTIONAL - role
"""A list of enrollment roles to return. Accepted values include course-level
roles created by the {api:RoleOverridesController#add_role Add Role API}
as well as the base enrollment types accepted by the `type` argument above."""
if role is not None:
params["role"] = role
# OPTIONAL - state
"""Filter by enrollment state. If omitted, 'active' and 'invited' enrollments
are returned. When querying a user's enrollments (either via user_id
argument or via user enrollments endpoint), the following additional
synthetic states are supported: "current_and_invited"|"current_and_future"|"current_and_concluded""""
if state is not None:
self._validate_enum(state, ["active", "invited", "creation_pending", "deleted", "rejected", "completed", "inactive"])
params["state"] = state
# OPTIONAL - include
"""Array of additional information to include on the enrollment or user records.
"avatar_url" and "group_ids" will be returned on the user record."""
if include is not None:
self._validate_enum(include, ["avatar_url", "group_ids", "locked", "observed_users", "can_be_removed"])
params["include"] = include
# OPTIONAL - user_id
"""Filter by user_id (only valid for course or section enrollment
queries). If set to the current user's id, this is a way to
determine if the user has any enrollments in the course or section,
independent of whether the user has permission to view other people
on the roster."""
if user_id is not None:
params["user_id"] = user_id
# OPTIONAL - grading_period_id
"""Return grades for the given grading_period. If this parameter is not
specified, the returned grades will be for the whole course."""
if grading_period_id is not None:
params["grading_period_id"] = grading_period_id
# OPTIONAL - sis_account_id
"""Returns only enrollments for the specified SIS account ID(s). Does not
look into subaccounts. May pass in array or string."""
if sis_account_id is not None:
params["sis_account_id"] = sis_account_id
# OPTIONAL - sis_course_id
"""Returns only enrollments matching the specified SIS course ID(s).
May pass in array or string."""
if sis_course_id is not None:
params["sis_course_id"] = sis_course_id
# OPTIONAL - sis_section_id
"""Returns only section enrollments matching the specified SIS section ID(s).
May pass in array or string."""
if sis_section_id is not None:
params["sis_section_id"] = sis_section_id
# OPTIONAL - sis_user_id
"""Returns only enrollments for the specified SIS user ID(s). May pass in
array or string."""
if sis_user_id is not None:
params["sis_user_id"] = sis_user_id
self.logger.debug("GET /api/v1/courses/{course_id}/enrollments with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/enrollments".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_enrollments_courses",
"(",
"self",
",",
"course_id",
",",
"grading_period_id",
"=",
"None",
",",
"include",
"=",
"None",
",",
"role",
"=",
"None",
",",
"sis_account_id",
"=",
"None",
",",
"sis_course_id",
"=",
"None",
",",
"sis_section_id",
"=",
... | List enrollments.
Depending on the URL given, return either (1) all of the enrollments in
a course, (2) all of the enrollments in a section or (3) all of a user's
enrollments. This includes student, teacher, TA, and observer enrollments.
If a user has multiple enrollments in a context (e.g. as a teacher
and a student or in multiple course sections), each enrollment will be
listed separately.
note: Currently, only an admin user can return other users' enrollments. A
user can, however, return his/her own enrollments. | [
"List",
"enrollments",
".",
"Depending",
"on",
"the",
"URL",
"given",
"return",
"either",
"(",
"1",
")",
"all",
"of",
"the",
"enrollments",
"in",
"a",
"course",
"(",
"2",
")",
"all",
"of",
"the",
"enrollments",
"in",
"a",
"section",
"or",
"(",
"3",
"... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/enrollments.py#L19-L113 |
PGower/PyCanvas | pycanvas/apis/enrollments.py | EnrollmentsAPI.enroll_user_courses | def enroll_user_courses(self, course_id, enrollment_type, enrollment_user_id, enrollment_associated_user_id=None, enrollment_course_section_id=None, enrollment_enrollment_state=None, enrollment_limit_privileges_to_course_section=None, enrollment_notify=None, enrollment_role=None, enrollment_role_id=None, enrollment_self_enrolled=None, enrollment_self_enrollment_code=None):
"""
Enroll a user.
Create a new user enrollment for a course or section.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - enrollment[user_id]
"""The ID of the user to be enrolled in the course."""
data["enrollment[user_id]"] = enrollment_user_id
# REQUIRED - enrollment[type]
"""Enroll the user as a student, teacher, TA, observer, or designer. If no
value is given, the type will be inferred by enrollment[role] if supplied,
otherwise 'StudentEnrollment' will be used."""
self._validate_enum(enrollment_type, ["StudentEnrollment", "TeacherEnrollment", "TaEnrollment", "ObserverEnrollment", "DesignerEnrollment"])
data["enrollment[type]"] = enrollment_type
# OPTIONAL - enrollment[role]
"""Assigns a custom course-level role to the user."""
if enrollment_role is not None:
data["enrollment[role]"] = enrollment_role
# OPTIONAL - enrollment[role_id]
"""Assigns a custom course-level role to the user."""
if enrollment_role_id is not None:
data["enrollment[role_id]"] = enrollment_role_id
# OPTIONAL - enrollment[enrollment_state]
"""If set to 'active,' student will be immediately enrolled in the course.
Otherwise they will be required to accept a course invitation. Default is
'invited.'.
If set to 'inactive', student will be listed in the course roster for
teachers, but will not be able to participate in the course until
their enrollment is activated."""
if enrollment_enrollment_state is not None:
self._validate_enum(enrollment_enrollment_state, ["active", "invited", "inactive"])
data["enrollment[enrollment_state]"] = enrollment_enrollment_state
# OPTIONAL - enrollment[course_section_id]
"""The ID of the course section to enroll the student in. If the
section-specific URL is used, this argument is redundant and will be
ignored."""
if enrollment_course_section_id is not None:
data["enrollment[course_section_id]"] = enrollment_course_section_id
# OPTIONAL - enrollment[limit_privileges_to_course_section]
"""If set, the enrollment will only allow the user to see and interact with
users enrolled in the section given by course_section_id.
* For teachers and TAs, this includes grading privileges.
* Section-limited students will not see any users (including teachers
and TAs) not enrolled in their sections.
* Users may have other enrollments that grant privileges to
multiple sections in the same course."""
if enrollment_limit_privileges_to_course_section is not None:
data["enrollment[limit_privileges_to_course_section]"] = enrollment_limit_privileges_to_course_section
# OPTIONAL - enrollment[notify]
"""If true, a notification will be sent to the enrolled user.
Notifications are not sent by default."""
if enrollment_notify is not None:
data["enrollment[notify]"] = enrollment_notify
# OPTIONAL - enrollment[self_enrollment_code]
"""If the current user is not allowed to manage enrollments in this
course, but the course allows self-enrollment, the user can self-
enroll as a student in the default section by passing in a valid
code. When self-enrolling, the user_id must be 'self'. The
enrollment_state will be set to 'active' and all other arguments
will be ignored."""
if enrollment_self_enrollment_code is not None:
data["enrollment[self_enrollment_code]"] = enrollment_self_enrollment_code
# OPTIONAL - enrollment[self_enrolled]
"""If true, marks the enrollment as a self-enrollment, which gives
students the ability to drop the course if desired. Defaults to false."""
if enrollment_self_enrolled is not None:
data["enrollment[self_enrolled]"] = enrollment_self_enrolled
# OPTIONAL - enrollment[associated_user_id]
"""For an observer enrollment, the ID of a student to observe. The
caller must have +manage_students+ permission in the course.
This is a one-off operation; to automatically observe all a
student's enrollments (for example, as a parent), please use
the {api:UserObserveesController#create User Observees API}."""
if enrollment_associated_user_id is not None:
data["enrollment[associated_user_id]"] = enrollment_associated_user_id
self.logger.debug("POST /api/v1/courses/{course_id}/enrollments with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/enrollments".format(**path), data=data, params=params, single_item=True) | python | def enroll_user_courses(self, course_id, enrollment_type, enrollment_user_id, enrollment_associated_user_id=None, enrollment_course_section_id=None, enrollment_enrollment_state=None, enrollment_limit_privileges_to_course_section=None, enrollment_notify=None, enrollment_role=None, enrollment_role_id=None, enrollment_self_enrolled=None, enrollment_self_enrollment_code=None):
"""
Enroll a user.
Create a new user enrollment for a course or section.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - enrollment[user_id]
"""The ID of the user to be enrolled in the course."""
data["enrollment[user_id]"] = enrollment_user_id
# REQUIRED - enrollment[type]
"""Enroll the user as a student, teacher, TA, observer, or designer. If no
value is given, the type will be inferred by enrollment[role] if supplied,
otherwise 'StudentEnrollment' will be used."""
self._validate_enum(enrollment_type, ["StudentEnrollment", "TeacherEnrollment", "TaEnrollment", "ObserverEnrollment", "DesignerEnrollment"])
data["enrollment[type]"] = enrollment_type
# OPTIONAL - enrollment[role]
"""Assigns a custom course-level role to the user."""
if enrollment_role is not None:
data["enrollment[role]"] = enrollment_role
# OPTIONAL - enrollment[role_id]
"""Assigns a custom course-level role to the user."""
if enrollment_role_id is not None:
data["enrollment[role_id]"] = enrollment_role_id
# OPTIONAL - enrollment[enrollment_state]
"""If set to 'active,' student will be immediately enrolled in the course.
Otherwise they will be required to accept a course invitation. Default is
'invited.'.
If set to 'inactive', student will be listed in the course roster for
teachers, but will not be able to participate in the course until
their enrollment is activated."""
if enrollment_enrollment_state is not None:
self._validate_enum(enrollment_enrollment_state, ["active", "invited", "inactive"])
data["enrollment[enrollment_state]"] = enrollment_enrollment_state
# OPTIONAL - enrollment[course_section_id]
"""The ID of the course section to enroll the student in. If the
section-specific URL is used, this argument is redundant and will be
ignored."""
if enrollment_course_section_id is not None:
data["enrollment[course_section_id]"] = enrollment_course_section_id
# OPTIONAL - enrollment[limit_privileges_to_course_section]
"""If set, the enrollment will only allow the user to see and interact with
users enrolled in the section given by course_section_id.
* For teachers and TAs, this includes grading privileges.
* Section-limited students will not see any users (including teachers
and TAs) not enrolled in their sections.
* Users may have other enrollments that grant privileges to
multiple sections in the same course."""
if enrollment_limit_privileges_to_course_section is not None:
data["enrollment[limit_privileges_to_course_section]"] = enrollment_limit_privileges_to_course_section
# OPTIONAL - enrollment[notify]
"""If true, a notification will be sent to the enrolled user.
Notifications are not sent by default."""
if enrollment_notify is not None:
data["enrollment[notify]"] = enrollment_notify
# OPTIONAL - enrollment[self_enrollment_code]
"""If the current user is not allowed to manage enrollments in this
course, but the course allows self-enrollment, the user can self-
enroll as a student in the default section by passing in a valid
code. When self-enrolling, the user_id must be 'self'. The
enrollment_state will be set to 'active' and all other arguments
will be ignored."""
if enrollment_self_enrollment_code is not None:
data["enrollment[self_enrollment_code]"] = enrollment_self_enrollment_code
# OPTIONAL - enrollment[self_enrolled]
"""If true, marks the enrollment as a self-enrollment, which gives
students the ability to drop the course if desired. Defaults to false."""
if enrollment_self_enrolled is not None:
data["enrollment[self_enrolled]"] = enrollment_self_enrolled
# OPTIONAL - enrollment[associated_user_id]
"""For an observer enrollment, the ID of a student to observe. The
caller must have +manage_students+ permission in the course.
This is a one-off operation; to automatically observe all a
student's enrollments (for example, as a parent), please use
the {api:UserObserveesController#create User Observees API}."""
if enrollment_associated_user_id is not None:
data["enrollment[associated_user_id]"] = enrollment_associated_user_id
self.logger.debug("POST /api/v1/courses/{course_id}/enrollments with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/enrollments".format(**path), data=data, params=params, single_item=True) | [
"def",
"enroll_user_courses",
"(",
"self",
",",
"course_id",
",",
"enrollment_type",
",",
"enrollment_user_id",
",",
"enrollment_associated_user_id",
"=",
"None",
",",
"enrollment_course_section_id",
"=",
"None",
",",
"enrollment_enrollment_state",
"=",
"None",
",",
"en... | Enroll a user.
Create a new user enrollment for a course or section. | [
"Enroll",
"a",
"user",
".",
"Create",
"a",
"new",
"user",
"enrollment",
"for",
"a",
"course",
"or",
"section",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/enrollments.py#L323-L420 |
PGower/PyCanvas | pycanvas/apis/enrollments.py | EnrollmentsAPI.conclude_deactivate_or_delete_enrollment | def conclude_deactivate_or_delete_enrollment(self, id, course_id, task=None):
"""
Conclude, deactivate, or delete an enrollment.
Conclude, deactivate, or delete an enrollment. If the +task+ argument isn't given, the enrollment
will be concluded.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - task
"""The action to take on the enrollment.
When inactive, a user will still appear in the course roster to admins, but be unable to participate.
("inactivate" and "deactivate" are equivalent tasks)"""
if task is not None:
self._validate_enum(task, ["conclude", "delete", "inactivate", "deactivate"])
params["task"] = task
self.logger.debug("DELETE /api/v1/courses/{course_id}/enrollments/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/courses/{course_id}/enrollments/{id}".format(**path), data=data, params=params, single_item=True) | python | def conclude_deactivate_or_delete_enrollment(self, id, course_id, task=None):
"""
Conclude, deactivate, or delete an enrollment.
Conclude, deactivate, or delete an enrollment. If the +task+ argument isn't given, the enrollment
will be concluded.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - task
"""The action to take on the enrollment.
When inactive, a user will still appear in the course roster to admins, but be unable to participate.
("inactivate" and "deactivate" are equivalent tasks)"""
if task is not None:
self._validate_enum(task, ["conclude", "delete", "inactivate", "deactivate"])
params["task"] = task
self.logger.debug("DELETE /api/v1/courses/{course_id}/enrollments/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/courses/{course_id}/enrollments/{id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"conclude_deactivate_or_delete_enrollment",
"(",
"self",
",",
"id",
",",
"course_id",
",",
"task",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",... | Conclude, deactivate, or delete an enrollment.
Conclude, deactivate, or delete an enrollment. If the +task+ argument isn't given, the enrollment
will be concluded. | [
"Conclude",
"deactivate",
"or",
"delete",
"an",
"enrollment",
".",
"Conclude",
"deactivate",
"or",
"delete",
"an",
"enrollment",
".",
"If",
"the",
"+",
"task",
"+",
"argument",
"isn",
"t",
"given",
"the",
"enrollment",
"will",
"be",
"concluded",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/enrollments.py#L521-L549 |
shmir/PyIxNetwork | ixnetwork/ixn_interface.py | filter_ints_based_on_vlan | def filter_ints_based_on_vlan(interfaces, vlan, count=1):
""" Filter list of interfaces based on VLAN presence or absence criteria.
:param interfaces: list of interfaces to filter.
:param vlan: boolean indicating whether to filter interfaces with or without VLAN.
:param vlan: number of expected VLANs (note that when vlanEnable == False, vlanCount == 1)
:return: interfaces with VLAN(s) if vlan == True and vlanCount == count else interfaces without
VLAN(s).
:todo: add vlanEnable and vlanCount to interface/range/deviceGroup classes.
"""
filtered_interfaces = []
for interface in interfaces:
if interface.obj_type() == 'interface':
ixn_vlan = interface.get_object_by_type('vlan')
vlanEnable = is_true(ixn_vlan.get_attribute('vlanEnable'))
vlanCount = int(ixn_vlan.get_attribute('vlanCount'))
elif interface.obj_type() == 'range':
ixn_vlan = interface.get_object_by_type('vlanRange')
vlanEnable = is_true(ixn_vlan.get_attribute('enabled'))
vlanCount = len(ixn_vlan.get_objects_by_type('vlanIdInfo'))
else:
ixn_vlan = interface.get_object_by_type('ethernet')
vlanEnable = is_true(ixn_vlan.get_attribute('useVlans'))
vlanCount = int(ixn_vlan.get_attribute('vlanCount'))
if not (vlanEnable ^ vlan) and vlanCount == count:
filtered_interfaces.append(interface)
return filtered_interfaces | python | def filter_ints_based_on_vlan(interfaces, vlan, count=1):
""" Filter list of interfaces based on VLAN presence or absence criteria.
:param interfaces: list of interfaces to filter.
:param vlan: boolean indicating whether to filter interfaces with or without VLAN.
:param vlan: number of expected VLANs (note that when vlanEnable == False, vlanCount == 1)
:return: interfaces with VLAN(s) if vlan == True and vlanCount == count else interfaces without
VLAN(s).
:todo: add vlanEnable and vlanCount to interface/range/deviceGroup classes.
"""
filtered_interfaces = []
for interface in interfaces:
if interface.obj_type() == 'interface':
ixn_vlan = interface.get_object_by_type('vlan')
vlanEnable = is_true(ixn_vlan.get_attribute('vlanEnable'))
vlanCount = int(ixn_vlan.get_attribute('vlanCount'))
elif interface.obj_type() == 'range':
ixn_vlan = interface.get_object_by_type('vlanRange')
vlanEnable = is_true(ixn_vlan.get_attribute('enabled'))
vlanCount = len(ixn_vlan.get_objects_by_type('vlanIdInfo'))
else:
ixn_vlan = interface.get_object_by_type('ethernet')
vlanEnable = is_true(ixn_vlan.get_attribute('useVlans'))
vlanCount = int(ixn_vlan.get_attribute('vlanCount'))
if not (vlanEnable ^ vlan) and vlanCount == count:
filtered_interfaces.append(interface)
return filtered_interfaces | [
"def",
"filter_ints_based_on_vlan",
"(",
"interfaces",
",",
"vlan",
",",
"count",
"=",
"1",
")",
":",
"filtered_interfaces",
"=",
"[",
"]",
"for",
"interface",
"in",
"interfaces",
":",
"if",
"interface",
".",
"obj_type",
"(",
")",
"==",
"'interface'",
":",
... | Filter list of interfaces based on VLAN presence or absence criteria.
:param interfaces: list of interfaces to filter.
:param vlan: boolean indicating whether to filter interfaces with or without VLAN.
:param vlan: number of expected VLANs (note that when vlanEnable == False, vlanCount == 1)
:return: interfaces with VLAN(s) if vlan == True and vlanCount == count else interfaces without
VLAN(s).
:todo: add vlanEnable and vlanCount to interface/range/deviceGroup classes. | [
"Filter",
"list",
"of",
"interfaces",
"based",
"on",
"VLAN",
"presence",
"or",
"absence",
"criteria",
"."
] | train | https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_interface.py#L13-L41 |
shmir/PyIxNetwork | ixnetwork/ixn_interface.py | IxnInterface._create | def _create(self, **attributes):
""" Create new interface on IxNetwork.
Set enabled and description (==name).
:return: interface object reference.
"""
attributes['enabled'] = True
if 'name' in self._data:
attributes['description'] = self._data['name']
obj_ref = self.api.add(self.obj_parent(), self.obj_type(), **attributes)
self.api.commit()
return self.api.remapIds(obj_ref) | python | def _create(self, **attributes):
""" Create new interface on IxNetwork.
Set enabled and description (==name).
:return: interface object reference.
"""
attributes['enabled'] = True
if 'name' in self._data:
attributes['description'] = self._data['name']
obj_ref = self.api.add(self.obj_parent(), self.obj_type(), **attributes)
self.api.commit()
return self.api.remapIds(obj_ref) | [
"def",
"_create",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"attributes",
"[",
"'enabled'",
"]",
"=",
"True",
"if",
"'name'",
"in",
"self",
".",
"_data",
":",
"attributes",
"[",
"'description'",
"]",
"=",
"self",
".",
"_data",
"[",
"'name'",
... | Create new interface on IxNetwork.
Set enabled and description (==name).
:return: interface object reference. | [
"Create",
"new",
"interface",
"on",
"IxNetwork",
"."
] | train | https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_interface.py#L55-L68 |
damoti/django-postgres-schema | postgres_schema/schema.py | DatabaseSchemaEditor._constraint_names | def _constraint_names(self, model, column_names=None, unique=None,
primary_key=None, index=None, foreign_key=None,
check=None):
"""
Returns all constraint names matching the columns and conditions
"""
column_names = list(column_names) if column_names else None
with self.connection.cursor() as cursor:
constraints = get_constraints(cursor, model._meta.db_table)
result = []
for name, infodict in constraints.items():
if column_names is None or column_names == infodict['columns']:
if unique is not None and infodict['unique'] != unique:
continue
if primary_key is not None and infodict['primary_key'] != primary_key:
continue
if index is not None and infodict['index'] != index:
continue
if check is not None and infodict['check'] != check:
continue
if foreign_key is not None and not infodict['foreign_key']:
continue
result.append(name)
return result | python | def _constraint_names(self, model, column_names=None, unique=None,
primary_key=None, index=None, foreign_key=None,
check=None):
"""
Returns all constraint names matching the columns and conditions
"""
column_names = list(column_names) if column_names else None
with self.connection.cursor() as cursor:
constraints = get_constraints(cursor, model._meta.db_table)
result = []
for name, infodict in constraints.items():
if column_names is None or column_names == infodict['columns']:
if unique is not None and infodict['unique'] != unique:
continue
if primary_key is not None and infodict['primary_key'] != primary_key:
continue
if index is not None and infodict['index'] != index:
continue
if check is not None and infodict['check'] != check:
continue
if foreign_key is not None and not infodict['foreign_key']:
continue
result.append(name)
return result | [
"def",
"_constraint_names",
"(",
"self",
",",
"model",
",",
"column_names",
"=",
"None",
",",
"unique",
"=",
"None",
",",
"primary_key",
"=",
"None",
",",
"index",
"=",
"None",
",",
"foreign_key",
"=",
"None",
",",
"check",
"=",
"None",
")",
":",
"colu... | Returns all constraint names matching the columns and conditions | [
"Returns",
"all",
"constraint",
"names",
"matching",
"the",
"columns",
"and",
"conditions"
] | train | https://github.com/damoti/django-postgres-schema/blob/49b7e721abaacc10ec281289df8a67bf8e8b50e0/postgres_schema/schema.py#L139-L163 |
anomaly/prestans | prestans/types/array.py | Array.is_scalar | def is_scalar(self):
"""
:return:
:rtype: bool
"""
return \
isinstance(self._element_template, Boolean) or \
isinstance(self._element_template, Float) or \
isinstance(self._element_template, Integer) or \
isinstance(self._element_template, String) | python | def is_scalar(self):
"""
:return:
:rtype: bool
"""
return \
isinstance(self._element_template, Boolean) or \
isinstance(self._element_template, Float) or \
isinstance(self._element_template, Integer) or \
isinstance(self._element_template, String) | [
"def",
"is_scalar",
"(",
"self",
")",
":",
"return",
"isinstance",
"(",
"self",
".",
"_element_template",
",",
"Boolean",
")",
"or",
"isinstance",
"(",
"self",
".",
"_element_template",
",",
"Float",
")",
"or",
"isinstance",
"(",
"self",
".",
"_element_templ... | :return:
:rtype: bool | [
":",
"return",
":",
":",
"rtype",
":",
"bool"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/array.py#L112-L121 |
anomaly/prestans | prestans/types/array.py | Array.validate | def validate(self, value, attribute_filter=None, minified=False):
"""
:param value:
:type value: list | None
:param attribute_filter:
:type attribute_filter: prestans.parser.AttributeFilter
:param minified:
:type minified: bool
:return:
"""
if not self._required and value is None:
return None
elif self._required and value is None:
raise exception.RequiredAttributeError()
_validated_value = self.__class__(
element_template=self._element_template,
min_length=self._min_length,
max_length=self._max_length
)
if not isinstance(value, (list, tuple)):
raise TypeError(value)
for array_element in value:
if isinstance(self._element_template, DataCollection):
validated_array_element = self._element_template.validate(array_element, attribute_filter, minified)
else:
validated_array_element = self._element_template.validate(array_element)
_validated_value.append(validated_array_element)
if self._min_length is not None and len(_validated_value) < self._min_length:
raise exception.LessThanMinimumError(value, self._min_length)
if self._max_length is not None and len(_validated_value) > self._max_length:
raise exception.MoreThanMaximumError(value, self._max_length)
return _validated_value | python | def validate(self, value, attribute_filter=None, minified=False):
"""
:param value:
:type value: list | None
:param attribute_filter:
:type attribute_filter: prestans.parser.AttributeFilter
:param minified:
:type minified: bool
:return:
"""
if not self._required and value is None:
return None
elif self._required and value is None:
raise exception.RequiredAttributeError()
_validated_value = self.__class__(
element_template=self._element_template,
min_length=self._min_length,
max_length=self._max_length
)
if not isinstance(value, (list, tuple)):
raise TypeError(value)
for array_element in value:
if isinstance(self._element_template, DataCollection):
validated_array_element = self._element_template.validate(array_element, attribute_filter, minified)
else:
validated_array_element = self._element_template.validate(array_element)
_validated_value.append(validated_array_element)
if self._min_length is not None and len(_validated_value) < self._min_length:
raise exception.LessThanMinimumError(value, self._min_length)
if self._max_length is not None and len(_validated_value) > self._max_length:
raise exception.MoreThanMaximumError(value, self._max_length)
return _validated_value | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"attribute_filter",
"=",
"None",
",",
"minified",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_required",
"and",
"value",
"is",
"None",
":",
"return",
"None",
"elif",
"self",
".",
"_required",
"... | :param value:
:type value: list | None
:param attribute_filter:
:type attribute_filter: prestans.parser.AttributeFilter
:param minified:
:type minified: bool
:return: | [
":",
"param",
"value",
":",
":",
"type",
"value",
":",
"list",
"|",
"None",
":",
"param",
"attribute_filter",
":",
":",
"type",
"attribute_filter",
":",
"prestans",
".",
"parser",
".",
"AttributeFilter",
":",
"param",
"minified",
":",
":",
"type",
"minifie... | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/types/array.py#L149-L189 |
anomaly/prestans | prestans/provider/auth.py | login_required | def login_required(http_method_handler):
"""
provides a decorator for RESTRequestHandler methods to check for authenticated users
RESTRequestHandler subclass must have a auth_context instance, refer to prestans.auth
for the parent class definition.
If decorator is used and no auth_context is provided the client will be denied access.
Handler will return a 401 Unauthorized if the user is not logged in, the service does
not redirect to login handler page, this is the client's responsibility.
auth_context_handler instance provides a message called get_current_user, use this
to obtain a reference to an authenticated user profile.
If all goes well, the original handler definition is executed.
"""
@wraps(http_method_handler)
def secure_http_method_handler(self, *args, **kwargs):
if not self.__provider_config__.authentication:
_message = "Service available to authenticated users only, no auth context provider set in handler"
authentication_error = prestans.exception.AuthenticationError(_message)
authentication_error.request = self.request
raise authentication_error
if not self.__provider_config__.authentication.is_authenticated_user():
authentication_error = prestans.exception.AuthenticationError()
authentication_error.request = self.request
raise authentication_error
http_method_handler(self, *args, **kwargs)
return secure_http_method_handler | python | def login_required(http_method_handler):
"""
provides a decorator for RESTRequestHandler methods to check for authenticated users
RESTRequestHandler subclass must have a auth_context instance, refer to prestans.auth
for the parent class definition.
If decorator is used and no auth_context is provided the client will be denied access.
Handler will return a 401 Unauthorized if the user is not logged in, the service does
not redirect to login handler page, this is the client's responsibility.
auth_context_handler instance provides a message called get_current_user, use this
to obtain a reference to an authenticated user profile.
If all goes well, the original handler definition is executed.
"""
@wraps(http_method_handler)
def secure_http_method_handler(self, *args, **kwargs):
if not self.__provider_config__.authentication:
_message = "Service available to authenticated users only, no auth context provider set in handler"
authentication_error = prestans.exception.AuthenticationError(_message)
authentication_error.request = self.request
raise authentication_error
if not self.__provider_config__.authentication.is_authenticated_user():
authentication_error = prestans.exception.AuthenticationError()
authentication_error.request = self.request
raise authentication_error
http_method_handler(self, *args, **kwargs)
return secure_http_method_handler | [
"def",
"login_required",
"(",
"http_method_handler",
")",
":",
"@",
"wraps",
"(",
"http_method_handler",
")",
"def",
"secure_http_method_handler",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"__provider_config__"... | provides a decorator for RESTRequestHandler methods to check for authenticated users
RESTRequestHandler subclass must have a auth_context instance, refer to prestans.auth
for the parent class definition.
If decorator is used and no auth_context is provided the client will be denied access.
Handler will return a 401 Unauthorized if the user is not logged in, the service does
not redirect to login handler page, this is the client's responsibility.
auth_context_handler instance provides a message called get_current_user, use this
to obtain a reference to an authenticated user profile.
If all goes well, the original handler definition is executed. | [
"provides",
"a",
"decorator",
"for",
"RESTRequestHandler",
"methods",
"to",
"check",
"for",
"authenticated",
"users"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/provider/auth.py#L83-L117 |
anomaly/prestans | prestans/provider/auth.py | role_required | def role_required(role_name=None):
"""
Authenticates a HTTP method handler based on a provided role
With a little help from Peter Cole's Blog
http://mrcoles.com/blog/3-decorator-examples-and-awesome-python/
"""
def _role_required(http_method_handler):
@wraps(http_method_handler)
def secure_http_method_handler(self, *args, **kwargs):
# role name must be provided
if role_name is None:
_message = "Role name must be provided"
authorization_error = prestans.exception.AuthorizationError(_message)
authorization_error.request = self.request
raise authorization_error
# authentication context must be set
if not self.__provider_config__.authentication:
_message = "Service available to authenticated users only, no auth context provider set in handler"
authentication_error = prestans.exception.AuthenticationError(_message)
authentication_error.request = self.request
raise authentication_error
# check for the role by calling current_user_has_role
if not self.__provider_config__.authentication.current_user_has_role(role_name):
authorization_error = prestans.exception.AuthorizationError(role_name)
authorization_error.request = self.request
raise authorization_error
http_method_handler(self, *args, **kwargs)
return wraps(http_method_handler)(secure_http_method_handler)
return _role_required | python | def role_required(role_name=None):
"""
Authenticates a HTTP method handler based on a provided role
With a little help from Peter Cole's Blog
http://mrcoles.com/blog/3-decorator-examples-and-awesome-python/
"""
def _role_required(http_method_handler):
@wraps(http_method_handler)
def secure_http_method_handler(self, *args, **kwargs):
# role name must be provided
if role_name is None:
_message = "Role name must be provided"
authorization_error = prestans.exception.AuthorizationError(_message)
authorization_error.request = self.request
raise authorization_error
# authentication context must be set
if not self.__provider_config__.authentication:
_message = "Service available to authenticated users only, no auth context provider set in handler"
authentication_error = prestans.exception.AuthenticationError(_message)
authentication_error.request = self.request
raise authentication_error
# check for the role by calling current_user_has_role
if not self.__provider_config__.authentication.current_user_has_role(role_name):
authorization_error = prestans.exception.AuthorizationError(role_name)
authorization_error.request = self.request
raise authorization_error
http_method_handler(self, *args, **kwargs)
return wraps(http_method_handler)(secure_http_method_handler)
return _role_required | [
"def",
"role_required",
"(",
"role_name",
"=",
"None",
")",
":",
"def",
"_role_required",
"(",
"http_method_handler",
")",
":",
"@",
"wraps",
"(",
"http_method_handler",
")",
"def",
"secure_http_method_handler",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
... | Authenticates a HTTP method handler based on a provided role
With a little help from Peter Cole's Blog
http://mrcoles.com/blog/3-decorator-examples-and-awesome-python/ | [
"Authenticates",
"a",
"HTTP",
"method",
"handler",
"based",
"on",
"a",
"provided",
"role"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/provider/auth.py#L120-L157 |
anomaly/prestans | prestans/provider/auth.py | access_required | def access_required(config=None):
"""
Authenticates a HTTP method handler based on a custom set of arguments
"""
def _access_required(http_method_handler):
def secure_http_method_handler(self, *args, **kwargs):
# authentication context must be set
if not self.__provider_config__.authentication:
_message = "Service available to authenticated users only, no auth context provider set in handler"
authentication_error = prestans.exception.AuthenticationError(_message)
authentication_error.request = self.request
raise authentication_error
# check for access by calling is_authorized_user
if not self.__provider_config__.authentication.is_authorized_user(config):
_message = "Service available to authorized users only"
authorization_error = prestans.exception.AuthorizationError(_message)
authorization_error.request = self.request
raise authorization_error
http_method_handler(self, *args, **kwargs)
return wraps(http_method_handler)(secure_http_method_handler)
return _access_required | python | def access_required(config=None):
"""
Authenticates a HTTP method handler based on a custom set of arguments
"""
def _access_required(http_method_handler):
def secure_http_method_handler(self, *args, **kwargs):
# authentication context must be set
if not self.__provider_config__.authentication:
_message = "Service available to authenticated users only, no auth context provider set in handler"
authentication_error = prestans.exception.AuthenticationError(_message)
authentication_error.request = self.request
raise authentication_error
# check for access by calling is_authorized_user
if not self.__provider_config__.authentication.is_authorized_user(config):
_message = "Service available to authorized users only"
authorization_error = prestans.exception.AuthorizationError(_message)
authorization_error.request = self.request
raise authorization_error
http_method_handler(self, *args, **kwargs)
return wraps(http_method_handler)(secure_http_method_handler)
return _access_required | [
"def",
"access_required",
"(",
"config",
"=",
"None",
")",
":",
"def",
"_access_required",
"(",
"http_method_handler",
")",
":",
"def",
"secure_http_method_handler",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# authentication context must... | Authenticates a HTTP method handler based on a custom set of arguments | [
"Authenticates",
"a",
"HTTP",
"method",
"handler",
"based",
"on",
"a",
"custom",
"set",
"of",
"arguments"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/provider/auth.py#L160-L187 |
anomaly/prestans | prestans/parser/attribute_filter_immutable.py | AttributeFilterImmutable.as_dict | def as_dict(self):
"""
turns attribute filter object into python dictionary
"""
output_dictionary = dict()
for key, value in iter(self._key_map.items()):
if isinstance(value, bool):
output_dictionary[key] = value
elif isinstance(value, self.__class__):
output_dictionary[key] = value.as_dict()
return output_dictionary | python | def as_dict(self):
"""
turns attribute filter object into python dictionary
"""
output_dictionary = dict()
for key, value in iter(self._key_map.items()):
if isinstance(value, bool):
output_dictionary[key] = value
elif isinstance(value, self.__class__):
output_dictionary[key] = value.as_dict()
return output_dictionary | [
"def",
"as_dict",
"(",
"self",
")",
":",
"output_dictionary",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"iter",
"(",
"self",
".",
"_key_map",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
... | turns attribute filter object into python dictionary | [
"turns",
"attribute",
"filter",
"object",
"into",
"python",
"dictionary"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/parser/attribute_filter_immutable.py#L63-L75 |
bast/flanders | cmake/autocmake/generate.py | gen_cmake_command | def gen_cmake_command(config):
"""
Generate CMake command.
"""
from autocmake.extract import extract_list
s = []
s.append("\n\ndef gen_cmake_command(options, arguments):")
s.append(' """')
s.append(" Generate CMake command based on options and arguments.")
s.append(' """')
s.append(" command = []")
for env in config['export']:
s.append(' command.append({0})'.format(env))
s.append(" command.append(arguments['--cmake-executable'])")
for definition in config['define']:
s.append(' command.append({0})'.format(definition))
s.append(" command.append('-DCMAKE_BUILD_TYPE={0}'.format(arguments['--type']))")
s.append(" command.append('-G\"{0}\"'.format(arguments['--generator']))")
s.append(" if arguments['--cmake-options'] != \"''\":")
s.append(" command.append(arguments['--cmake-options'])")
s.append(" if arguments['--prefix']:")
s.append(" command.append('-DCMAKE_INSTALL_PREFIX=\"{0}\"'.format(arguments['--prefix']))")
s.append("\n return ' '.join(command)")
return '\n'.join(s) | python | def gen_cmake_command(config):
"""
Generate CMake command.
"""
from autocmake.extract import extract_list
s = []
s.append("\n\ndef gen_cmake_command(options, arguments):")
s.append(' """')
s.append(" Generate CMake command based on options and arguments.")
s.append(' """')
s.append(" command = []")
for env in config['export']:
s.append(' command.append({0})'.format(env))
s.append(" command.append(arguments['--cmake-executable'])")
for definition in config['define']:
s.append(' command.append({0})'.format(definition))
s.append(" command.append('-DCMAKE_BUILD_TYPE={0}'.format(arguments['--type']))")
s.append(" command.append('-G\"{0}\"'.format(arguments['--generator']))")
s.append(" if arguments['--cmake-options'] != \"''\":")
s.append(" command.append(arguments['--cmake-options'])")
s.append(" if arguments['--prefix']:")
s.append(" command.append('-DCMAKE_INSTALL_PREFIX=\"{0}\"'.format(arguments['--prefix']))")
s.append("\n return ' '.join(command)")
return '\n'.join(s) | [
"def",
"gen_cmake_command",
"(",
"config",
")",
":",
"from",
"autocmake",
".",
"extract",
"import",
"extract_list",
"s",
"=",
"[",
"]",
"s",
".",
"append",
"(",
"\"\\n\\ndef gen_cmake_command(options, arguments):\"",
")",
"s",
".",
"append",
"(",
"' \"\"\"'",
... | Generate CMake command. | [
"Generate",
"CMake",
"command",
"."
] | train | https://github.com/bast/flanders/blob/792f9eed8511cb553e67a25b6c5ce60fd6ae97bc/cmake/autocmake/generate.py#L1-L31 |
bast/flanders | cmake/autocmake/generate.py | gen_setup | def gen_setup(config, default_build_type, relative_path, setup_script_name):
"""
Generate setup script.
"""
from autocmake.extract import extract_list
s = []
s.append('#!/usr/bin/env python')
s.append('\n{0}'.format(autogenerated_notice()))
s.append('\nimport os')
s.append('import sys')
s.append('assert sys.version_info >= (2, 6), \'Python >= 2.6 is required\'')
s.append("\nsys.path.insert(0, '{0}')".format(relative_path))
s.append('from autocmake import configure')
s.append('from autocmake.external import docopt')
s.append('\n\noptions = """')
s.append('Usage:')
s.append(' ./{0} [options] [<builddir>]'.format(setup_script_name))
s.append(' ./{0} (-h | --help)'.format(setup_script_name))
s.append('\nOptions:')
options = []
for opt in config['docopt']:
first = opt.split()[0].strip()
rest = ' '.join(opt.split()[1:]).strip()
options.append([first, rest])
options.append(['--type=<TYPE>', 'Set the CMake build type (debug, release, relwithdebinfo, minsizerel) [default: {0}].'.format(default_build_type)])
options.append(['--generator=<STRING>', 'Set the CMake build system generator [default: Unix Makefiles].'])
options.append(['--show', 'Show CMake command and exit.'])
options.append(['--cmake-executable=<CMAKE_EXECUTABLE>', 'Set the CMake executable [default: cmake].'])
options.append(['--cmake-options=<STRING>', "Define options to CMake [default: '']."])
options.append(['--prefix=<PATH>', 'Set the install path for make install.'])
options.append(['<builddir>', 'Build directory.'])
options.append(['-h --help', 'Show this screen.'])
s.append(align_options(options))
s.append('"""')
s.append(gen_cmake_command(config))
s.append("\n")
s.append("# parse command line args")
s.append("try:")
s.append(" arguments = docopt.docopt(options, argv=None)")
s.append("except docopt.DocoptExit:")
s.append(r" sys.stderr.write('ERROR: bad input to {0}\n'.format(sys.argv[0]))")
s.append(" sys.stderr.write(options)")
s.append(" sys.exit(-1)")
s.append("\n")
s.append("# use extensions to validate/post-process args")
s.append("if configure.module_exists('extensions'):")
s.append(" import extensions")
s.append(" arguments = extensions.postprocess_args(sys.argv, arguments)")
s.append("\n")
s.append("root_directory = os.path.dirname(os.path.realpath(__file__))")
s.append("\n")
s.append("build_path = arguments['<builddir>']")
s.append("\n")
s.append("# create cmake command")
s.append("cmake_command = '{0} -H{1}'.format(gen_cmake_command(options, arguments), root_directory)")
s.append("\n")
s.append("# run cmake")
s.append("configure.configure(root_directory, build_path, cmake_command, arguments['--show'])")
return s | python | def gen_setup(config, default_build_type, relative_path, setup_script_name):
"""
Generate setup script.
"""
from autocmake.extract import extract_list
s = []
s.append('#!/usr/bin/env python')
s.append('\n{0}'.format(autogenerated_notice()))
s.append('\nimport os')
s.append('import sys')
s.append('assert sys.version_info >= (2, 6), \'Python >= 2.6 is required\'')
s.append("\nsys.path.insert(0, '{0}')".format(relative_path))
s.append('from autocmake import configure')
s.append('from autocmake.external import docopt')
s.append('\n\noptions = """')
s.append('Usage:')
s.append(' ./{0} [options] [<builddir>]'.format(setup_script_name))
s.append(' ./{0} (-h | --help)'.format(setup_script_name))
s.append('\nOptions:')
options = []
for opt in config['docopt']:
first = opt.split()[0].strip()
rest = ' '.join(opt.split()[1:]).strip()
options.append([first, rest])
options.append(['--type=<TYPE>', 'Set the CMake build type (debug, release, relwithdebinfo, minsizerel) [default: {0}].'.format(default_build_type)])
options.append(['--generator=<STRING>', 'Set the CMake build system generator [default: Unix Makefiles].'])
options.append(['--show', 'Show CMake command and exit.'])
options.append(['--cmake-executable=<CMAKE_EXECUTABLE>', 'Set the CMake executable [default: cmake].'])
options.append(['--cmake-options=<STRING>', "Define options to CMake [default: '']."])
options.append(['--prefix=<PATH>', 'Set the install path for make install.'])
options.append(['<builddir>', 'Build directory.'])
options.append(['-h --help', 'Show this screen.'])
s.append(align_options(options))
s.append('"""')
s.append(gen_cmake_command(config))
s.append("\n")
s.append("# parse command line args")
s.append("try:")
s.append(" arguments = docopt.docopt(options, argv=None)")
s.append("except docopt.DocoptExit:")
s.append(r" sys.stderr.write('ERROR: bad input to {0}\n'.format(sys.argv[0]))")
s.append(" sys.stderr.write(options)")
s.append(" sys.exit(-1)")
s.append("\n")
s.append("# use extensions to validate/post-process args")
s.append("if configure.module_exists('extensions'):")
s.append(" import extensions")
s.append(" arguments = extensions.postprocess_args(sys.argv, arguments)")
s.append("\n")
s.append("root_directory = os.path.dirname(os.path.realpath(__file__))")
s.append("\n")
s.append("build_path = arguments['<builddir>']")
s.append("\n")
s.append("# create cmake command")
s.append("cmake_command = '{0} -H{1}'.format(gen_cmake_command(options, arguments), root_directory)")
s.append("\n")
s.append("# run cmake")
s.append("configure.configure(root_directory, build_path, cmake_command, arguments['--show'])")
return s | [
"def",
"gen_setup",
"(",
"config",
",",
"default_build_type",
",",
"relative_path",
",",
"setup_script_name",
")",
":",
"from",
"autocmake",
".",
"extract",
"import",
"extract_list",
"s",
"=",
"[",
"]",
"s",
".",
"append",
"(",
"'#!/usr/bin/env python'",
")",
... | Generate setup script. | [
"Generate",
"setup",
"script",
"."
] | train | https://github.com/bast/flanders/blob/792f9eed8511cb553e67a25b6c5ce60fd6ae97bc/cmake/autocmake/generate.py#L48-L118 |
bast/flanders | cmake/autocmake/generate.py | gen_cmakelists | def gen_cmakelists(project_name, project_language, min_cmake_version, default_build_type, relative_path, modules):
"""
Generate CMakeLists.txt.
"""
import os
s = []
s.append(autogenerated_notice())
s.append('\n# set minimum cmake version')
s.append('cmake_minimum_required(VERSION {0} FATAL_ERROR)'.format(min_cmake_version))
s.append('\n# project name')
s.append('project({0} {1})'.format(project_name, project_language))
s.append('\n# do not rebuild if rules (compiler flags) change')
s.append('set(CMAKE_SKIP_RULE_DEPENDENCY TRUE)')
build_type_capitalized = {'debug': 'Debug',
'release': 'Release',
'relwithdebinfo': 'RelWithDebInfo',
'minsizerel': 'MinSizeRel'}
_build_type = build_type_capitalized[default_build_type]
s.append('\n# if CMAKE_BUILD_TYPE undefined, we set it to {0}'.format(_build_type))
s.append('if(NOT CMAKE_BUILD_TYPE)')
s.append(' set(CMAKE_BUILD_TYPE "{0}")'.format(_build_type))
s.append('endif()')
if len(modules) > 0:
s.append('\n# directories which hold included cmake modules')
module_paths = [module.path for module in modules]
module_paths.append('downloaded') # this is done to be able to find fetched modules when testing
module_paths = list(set(module_paths))
module_paths.sort() # we do this to always get the same order and to minimize diffs
for directory in module_paths:
rel_cmake_module_path = os.path.join(relative_path, directory)
# on windows cmake corrects this so we have to make it wrong again
rel_cmake_module_path = rel_cmake_module_path.replace('\\', '/')
s.append('set(CMAKE_MODULE_PATH ${{CMAKE_MODULE_PATH}} ${{PROJECT_SOURCE_DIR}}/{0})'.format(rel_cmake_module_path))
if len(modules) > 0:
s.append('\n# included cmake modules')
for module in modules:
s.append('include({0})'.format(os.path.splitext(module.name)[0]))
return s | python | def gen_cmakelists(project_name, project_language, min_cmake_version, default_build_type, relative_path, modules):
"""
Generate CMakeLists.txt.
"""
import os
s = []
s.append(autogenerated_notice())
s.append('\n# set minimum cmake version')
s.append('cmake_minimum_required(VERSION {0} FATAL_ERROR)'.format(min_cmake_version))
s.append('\n# project name')
s.append('project({0} {1})'.format(project_name, project_language))
s.append('\n# do not rebuild if rules (compiler flags) change')
s.append('set(CMAKE_SKIP_RULE_DEPENDENCY TRUE)')
build_type_capitalized = {'debug': 'Debug',
'release': 'Release',
'relwithdebinfo': 'RelWithDebInfo',
'minsizerel': 'MinSizeRel'}
_build_type = build_type_capitalized[default_build_type]
s.append('\n# if CMAKE_BUILD_TYPE undefined, we set it to {0}'.format(_build_type))
s.append('if(NOT CMAKE_BUILD_TYPE)')
s.append(' set(CMAKE_BUILD_TYPE "{0}")'.format(_build_type))
s.append('endif()')
if len(modules) > 0:
s.append('\n# directories which hold included cmake modules')
module_paths = [module.path for module in modules]
module_paths.append('downloaded') # this is done to be able to find fetched modules when testing
module_paths = list(set(module_paths))
module_paths.sort() # we do this to always get the same order and to minimize diffs
for directory in module_paths:
rel_cmake_module_path = os.path.join(relative_path, directory)
# on windows cmake corrects this so we have to make it wrong again
rel_cmake_module_path = rel_cmake_module_path.replace('\\', '/')
s.append('set(CMAKE_MODULE_PATH ${{CMAKE_MODULE_PATH}} ${{PROJECT_SOURCE_DIR}}/{0})'.format(rel_cmake_module_path))
if len(modules) > 0:
s.append('\n# included cmake modules')
for module in modules:
s.append('include({0})'.format(os.path.splitext(module.name)[0]))
return s | [
"def",
"gen_cmakelists",
"(",
"project_name",
",",
"project_language",
",",
"min_cmake_version",
",",
"default_build_type",
",",
"relative_path",
",",
"modules",
")",
":",
"import",
"os",
"s",
"=",
"[",
"]",
"s",
".",
"append",
"(",
"autogenerated_notice",
"(",
... | Generate CMakeLists.txt. | [
"Generate",
"CMakeLists",
".",
"txt",
"."
] | train | https://github.com/bast/flanders/blob/792f9eed8511cb553e67a25b6c5ce60fd6ae97bc/cmake/autocmake/generate.py#L121-L169 |
bast/flanders | cmake/autocmake/generate.py | align_options | def align_options(options):
"""
Indents flags and aligns help texts.
"""
l = 0
for opt in options:
if len(opt[0]) > l:
l = len(opt[0])
s = []
for opt in options:
s.append(' {0}{1} {2}'.format(opt[0], ' ' * (l - len(opt[0])), opt[1]))
return '\n'.join(s) | python | def align_options(options):
"""
Indents flags and aligns help texts.
"""
l = 0
for opt in options:
if len(opt[0]) > l:
l = len(opt[0])
s = []
for opt in options:
s.append(' {0}{1} {2}'.format(opt[0], ' ' * (l - len(opt[0])), opt[1]))
return '\n'.join(s) | [
"def",
"align_options",
"(",
"options",
")",
":",
"l",
"=",
"0",
"for",
"opt",
"in",
"options",
":",
"if",
"len",
"(",
"opt",
"[",
"0",
"]",
")",
">",
"l",
":",
"l",
"=",
"len",
"(",
"opt",
"[",
"0",
"]",
")",
"s",
"=",
"[",
"]",
"for",
"... | Indents flags and aligns help texts. | [
"Indents",
"flags",
"and",
"aligns",
"help",
"texts",
"."
] | train | https://github.com/bast/flanders/blob/792f9eed8511cb553e67a25b6c5ce60fd6ae97bc/cmake/autocmake/generate.py#L172-L183 |
Rockhopper-Technologies/pluginlib | pluginlib/_loader.py | format_exception | def format_exception(etype, value, tback, limit=None):
"""
Python 2 compatible version of traceback.format_exception
Accepts negative limits like the Python 3 version
"""
rtn = ['Traceback (most recent call last):\n']
if limit is None or limit >= 0:
rtn.extend(traceback.format_tb(tback, limit))
else:
rtn.extend(traceback.format_list(traceback.extract_tb(tback)[limit:]))
rtn.extend(traceback.format_exception_only(etype, value))
return rtn | python | def format_exception(etype, value, tback, limit=None):
"""
Python 2 compatible version of traceback.format_exception
Accepts negative limits like the Python 3 version
"""
rtn = ['Traceback (most recent call last):\n']
if limit is None or limit >= 0:
rtn.extend(traceback.format_tb(tback, limit))
else:
rtn.extend(traceback.format_list(traceback.extract_tb(tback)[limit:]))
rtn.extend(traceback.format_exception_only(etype, value))
return rtn | [
"def",
"format_exception",
"(",
"etype",
",",
"value",
",",
"tback",
",",
"limit",
"=",
"None",
")",
":",
"rtn",
"=",
"[",
"'Traceback (most recent call last):\\n'",
"]",
"if",
"limit",
"is",
"None",
"or",
"limit",
">=",
"0",
":",
"rtn",
".",
"extend",
"... | Python 2 compatible version of traceback.format_exception
Accepts negative limits like the Python 3 version | [
"Python",
"2",
"compatible",
"version",
"of",
"traceback",
".",
"format_exception",
"Accepts",
"negative",
"limits",
"like",
"the",
"Python",
"3",
"version"
] | train | https://github.com/Rockhopper-Technologies/pluginlib/blob/8beb78984dd9c97c493642df9da9f1b5a1c5e2b2/pluginlib/_loader.py#L30-L45 |
Rockhopper-Technologies/pluginlib | pluginlib/_loader.py | _import_module | def _import_module(name, path=None):
"""
Args:
name(str):
* Full name of object
* name can also be an EntryPoint object, name and path will be determined dynamically
path(str): Module directory
Returns:
object: module object or advertised object for EntryPoint
Loads a module using importlib catching exceptions
If path is given, the traceback will be formatted to give more friendly and direct information
"""
# If name is an entry point, try to parse it
epoint = None
if isinstance(name, EntryPoint):
epoint = name
name = epoint.module_name
if path is None:
try:
loader = pkgutil.get_loader(name)
except ImportError:
pass
else:
if loader:
path = os.path.dirname(loader.get_filename(name))
LOGGER.debug('Attempting to load module %s from %s', name, path)
try:
if epoint:
mod = epoint.load()
else:
mod = importlib.import_module(name)
except Exception as e: # pylint: disable=broad-except
etype = e.__class__
tback = getattr(e, '__traceback__', sys.exc_info()[2])
# Create traceback starting at module for friendly output
start = 0
here = 0
tb_list = traceback.extract_tb(tback)
if path:
for idx, entry in enumerate(tb_list):
# Find index for traceback starting with module we tried to load
if os.path.dirname(entry[0]) == path:
start = idx
break
# Find index for traceback starting with this file
elif os.path.splitext(entry[0])[0] == os.path.splitext(__file__)[0]:
here = idx
if start == 0 and isinstance(e, SyntaxError):
limit = 0
else:
limit = 0 - len(tb_list) + max(start, here)
# pylint: disable=wrong-spelling-in-comment
# friendly = ''.join(traceback.format_exception(etype, e, tback, limit))
friendly = ''.join(format_exception(etype, e, tback, limit))
# Format exception
msg = 'Error while importing candidate plugin module %s from %s' % (name, path)
exception = PluginImportError('%s: %s' % (msg, repr(e)), friendly=friendly)
raise_with_traceback(exception, tback)
return mod | python | def _import_module(name, path=None):
"""
Args:
name(str):
* Full name of object
* name can also be an EntryPoint object, name and path will be determined dynamically
path(str): Module directory
Returns:
object: module object or advertised object for EntryPoint
Loads a module using importlib catching exceptions
If path is given, the traceback will be formatted to give more friendly and direct information
"""
# If name is an entry point, try to parse it
epoint = None
if isinstance(name, EntryPoint):
epoint = name
name = epoint.module_name
if path is None:
try:
loader = pkgutil.get_loader(name)
except ImportError:
pass
else:
if loader:
path = os.path.dirname(loader.get_filename(name))
LOGGER.debug('Attempting to load module %s from %s', name, path)
try:
if epoint:
mod = epoint.load()
else:
mod = importlib.import_module(name)
except Exception as e: # pylint: disable=broad-except
etype = e.__class__
tback = getattr(e, '__traceback__', sys.exc_info()[2])
# Create traceback starting at module for friendly output
start = 0
here = 0
tb_list = traceback.extract_tb(tback)
if path:
for idx, entry in enumerate(tb_list):
# Find index for traceback starting with module we tried to load
if os.path.dirname(entry[0]) == path:
start = idx
break
# Find index for traceback starting with this file
elif os.path.splitext(entry[0])[0] == os.path.splitext(__file__)[0]:
here = idx
if start == 0 and isinstance(e, SyntaxError):
limit = 0
else:
limit = 0 - len(tb_list) + max(start, here)
# pylint: disable=wrong-spelling-in-comment
# friendly = ''.join(traceback.format_exception(etype, e, tback, limit))
friendly = ''.join(format_exception(etype, e, tback, limit))
# Format exception
msg = 'Error while importing candidate plugin module %s from %s' % (name, path)
exception = PluginImportError('%s: %s' % (msg, repr(e)), friendly=friendly)
raise_with_traceback(exception, tback)
return mod | [
"def",
"_import_module",
"(",
"name",
",",
"path",
"=",
"None",
")",
":",
"# If name is an entry point, try to parse it",
"epoint",
"=",
"None",
"if",
"isinstance",
"(",
"name",
",",
"EntryPoint",
")",
":",
"epoint",
"=",
"name",
"name",
"=",
"epoint",
".",
... | Args:
name(str):
* Full name of object
* name can also be an EntryPoint object, name and path will be determined dynamically
path(str): Module directory
Returns:
object: module object or advertised object for EntryPoint
Loads a module using importlib catching exceptions
If path is given, the traceback will be formatted to give more friendly and direct information | [
"Args",
":",
"name",
"(",
"str",
")",
":",
"*",
"Full",
"name",
"of",
"object",
"*",
"name",
"can",
"also",
"be",
"an",
"EntryPoint",
"object",
"name",
"and",
"path",
"will",
"be",
"determined",
"dynamically",
"path",
"(",
"str",
")",
":",
"Module",
... | train | https://github.com/Rockhopper-Technologies/pluginlib/blob/8beb78984dd9c97c493642df9da9f1b5a1c5e2b2/pluginlib/_loader.py#L48-L120 |
Rockhopper-Technologies/pluginlib | pluginlib/_loader.py | _recursive_import | def _recursive_import(package):
"""
Args:
package(py:term:`package`): Package to walk
Import all modules from a package recursively
"""
prefix = '%s.' % (package.__name__)
path = getattr(package, '__path__', None)
if path:
for submod in pkgutil.walk_packages(path, prefix=prefix):
_import_module(submod[1], submod[0].path) | python | def _recursive_import(package):
"""
Args:
package(py:term:`package`): Package to walk
Import all modules from a package recursively
"""
prefix = '%s.' % (package.__name__)
path = getattr(package, '__path__', None)
if path:
for submod in pkgutil.walk_packages(path, prefix=prefix):
_import_module(submod[1], submod[0].path) | [
"def",
"_recursive_import",
"(",
"package",
")",
":",
"prefix",
"=",
"'%s.'",
"%",
"(",
"package",
".",
"__name__",
")",
"path",
"=",
"getattr",
"(",
"package",
",",
"'__path__'",
",",
"None",
")",
"if",
"path",
":",
"for",
"submod",
"in",
"pkgutil",
"... | Args:
package(py:term:`package`): Package to walk
Import all modules from a package recursively | [
"Args",
":",
"package",
"(",
"py",
":",
"term",
":",
"package",
")",
":",
"Package",
"to",
"walk"
] | train | https://github.com/Rockhopper-Technologies/pluginlib/blob/8beb78984dd9c97c493642df9da9f1b5a1c5e2b2/pluginlib/_loader.py#L123-L137 |
Rockhopper-Technologies/pluginlib | pluginlib/_loader.py | PluginLoader.load_modules | def load_modules(self):
"""
Locate and import modules from locations specified during initialization.
Locations include:
- Program's standard library (``library``)
- `Entry points <Entry point_>`_ (``entry_point``)
- Specified modules (``modules``)
- Specified paths (``paths``)
If a malformed child plugin class is imported, a :py:exc:`PluginWarning` will be issued,
the class is skipped, and loading operations continue.
If an invalid `entry point <Entry point_>`_ is specified, an :py:exc:`EntryPointWarning`
is issued and loading operations continue.
"""
# Start with standard library
if self.library:
LOGGER.info('Loading plugins from standard library')
libmod = _import_module(self.library)
_recursive_import(libmod)
# Get entry points
if self.entry_point:
LOGGER.info('Loading plugins from entry points group %s', self.entry_point)
for epoint in iter_entry_points(group=self.entry_point):
try:
mod = _import_module(epoint)
except PluginImportError as e:
warnings.warn("Module %s can not be loaded for entry point %s: %s" %
(epoint.module_name, epoint.name, e), EntryPointWarning)
continue
# If we have a package, walk it
if ismodule(mod):
_recursive_import(mod)
else:
warnings.warn("Entry point '%s' is not a module or package" % epoint.name,
EntryPointWarning)
# Load auxiliary modules
if self.modules:
for mod in self.modules:
LOGGER.info('Loading plugins from %s', mod)
_recursive_import(_import_module(mod))
# Load auxiliary paths
if self.paths:
auth_paths_mod = importlib.import_module(self.prefix_package)
initial_path = auth_paths_mod.__path__[:]
# Append each path to module path
for path in self.paths:
modpath = os.path.realpath(path)
if os.path.isdir(modpath):
LOGGER.info('Adding %s as a plugin search path', path)
if modpath not in auth_paths_mod.__path__:
auth_paths_mod.__path__.append(modpath)
else:
LOGGER.info("Configured plugin path '%s' is not a valid directory", path)
# Walk packages
try:
_recursive_import(auth_paths_mod)
finally:
# Restore Path
auth_paths_mod.__path__[:] = initial_path
self.loaded = True | python | def load_modules(self):
"""
Locate and import modules from locations specified during initialization.
Locations include:
- Program's standard library (``library``)
- `Entry points <Entry point_>`_ (``entry_point``)
- Specified modules (``modules``)
- Specified paths (``paths``)
If a malformed child plugin class is imported, a :py:exc:`PluginWarning` will be issued,
the class is skipped, and loading operations continue.
If an invalid `entry point <Entry point_>`_ is specified, an :py:exc:`EntryPointWarning`
is issued and loading operations continue.
"""
# Start with standard library
if self.library:
LOGGER.info('Loading plugins from standard library')
libmod = _import_module(self.library)
_recursive_import(libmod)
# Get entry points
if self.entry_point:
LOGGER.info('Loading plugins from entry points group %s', self.entry_point)
for epoint in iter_entry_points(group=self.entry_point):
try:
mod = _import_module(epoint)
except PluginImportError as e:
warnings.warn("Module %s can not be loaded for entry point %s: %s" %
(epoint.module_name, epoint.name, e), EntryPointWarning)
continue
# If we have a package, walk it
if ismodule(mod):
_recursive_import(mod)
else:
warnings.warn("Entry point '%s' is not a module or package" % epoint.name,
EntryPointWarning)
# Load auxiliary modules
if self.modules:
for mod in self.modules:
LOGGER.info('Loading plugins from %s', mod)
_recursive_import(_import_module(mod))
# Load auxiliary paths
if self.paths:
auth_paths_mod = importlib.import_module(self.prefix_package)
initial_path = auth_paths_mod.__path__[:]
# Append each path to module path
for path in self.paths:
modpath = os.path.realpath(path)
if os.path.isdir(modpath):
LOGGER.info('Adding %s as a plugin search path', path)
if modpath not in auth_paths_mod.__path__:
auth_paths_mod.__path__.append(modpath)
else:
LOGGER.info("Configured plugin path '%s' is not a valid directory", path)
# Walk packages
try:
_recursive_import(auth_paths_mod)
finally:
# Restore Path
auth_paths_mod.__path__[:] = initial_path
self.loaded = True | [
"def",
"load_modules",
"(",
"self",
")",
":",
"# Start with standard library",
"if",
"self",
".",
"library",
":",
"LOGGER",
".",
"info",
"(",
"'Loading plugins from standard library'",
")",
"libmod",
"=",
"_import_module",
"(",
"self",
".",
"library",
")",
"_recur... | Locate and import modules from locations specified during initialization.
Locations include:
- Program's standard library (``library``)
- `Entry points <Entry point_>`_ (``entry_point``)
- Specified modules (``modules``)
- Specified paths (``paths``)
If a malformed child plugin class is imported, a :py:exc:`PluginWarning` will be issued,
the class is skipped, and loading operations continue.
If an invalid `entry point <Entry point_>`_ is specified, an :py:exc:`EntryPointWarning`
is issued and loading operations continue. | [
"Locate",
"and",
"import",
"modules",
"from",
"locations",
"specified",
"during",
"initialization",
"."
] | train | https://github.com/Rockhopper-Technologies/pluginlib/blob/8beb78984dd9c97c493642df9da9f1b5a1c5e2b2/pluginlib/_loader.py#L251-L323 |
Rockhopper-Technologies/pluginlib | pluginlib/_loader.py | PluginLoader.plugins | def plugins(self):
"""
Newest version of all plugins in the group filtered by ``blacklist``
Returns:
dict: Nested dictionary of plugins accessible through dot-notation.
Plugins are returned in a nested dictionary, but can also be accessed through dot-notion.
Just as when accessing an undefined dictionary key with index-notation,
a :py:exc:`KeyError` will be raised if the plugin type or plugin does not exist.
Parent types are always included.
Child plugins will only be included if a valid, non-blacklisted plugin is available.
"""
if not self.loaded:
self.load_modules()
# pylint: disable=protected-access
return get_plugins()[self.group]._filter(blacklist=self.blacklist, newest_only=True,
type_filter=self.type_filter) | python | def plugins(self):
"""
Newest version of all plugins in the group filtered by ``blacklist``
Returns:
dict: Nested dictionary of plugins accessible through dot-notation.
Plugins are returned in a nested dictionary, but can also be accessed through dot-notion.
Just as when accessing an undefined dictionary key with index-notation,
a :py:exc:`KeyError` will be raised if the plugin type or plugin does not exist.
Parent types are always included.
Child plugins will only be included if a valid, non-blacklisted plugin is available.
"""
if not self.loaded:
self.load_modules()
# pylint: disable=protected-access
return get_plugins()[self.group]._filter(blacklist=self.blacklist, newest_only=True,
type_filter=self.type_filter) | [
"def",
"plugins",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"loaded",
":",
"self",
".",
"load_modules",
"(",
")",
"# pylint: disable=protected-access",
"return",
"get_plugins",
"(",
")",
"[",
"self",
".",
"group",
"]",
".",
"_filter",
"(",
"blacklis... | Newest version of all plugins in the group filtered by ``blacklist``
Returns:
dict: Nested dictionary of plugins accessible through dot-notation.
Plugins are returned in a nested dictionary, but can also be accessed through dot-notion.
Just as when accessing an undefined dictionary key with index-notation,
a :py:exc:`KeyError` will be raised if the plugin type or plugin does not exist.
Parent types are always included.
Child plugins will only be included if a valid, non-blacklisted plugin is available. | [
"Newest",
"version",
"of",
"all",
"plugins",
"in",
"the",
"group",
"filtered",
"by",
"blacklist"
] | train | https://github.com/Rockhopper-Technologies/pluginlib/blob/8beb78984dd9c97c493642df9da9f1b5a1c5e2b2/pluginlib/_loader.py#L326-L346 |
Rockhopper-Technologies/pluginlib | pluginlib/_loader.py | PluginLoader.plugins_all | def plugins_all(self):
"""
All resulting versions of all plugins in the group filtered by ``blacklist``
Returns:
dict: Nested dictionary of plugins accessible through dot-notation.
Similar to :py:attr:`plugins`, but lowest level is a regular dictionary of
all unfiltered plugin versions for the given plugin type and name.
Parent types are always included.
Child plugins will only be included if at least one valid, non-blacklisted plugin
is available.
"""
if not self.loaded:
self.load_modules()
# pylint: disable=protected-access
return get_plugins()[self.group]._filter(blacklist=self.blacklist,
type_filter=self.type_filter) | python | def plugins_all(self):
"""
All resulting versions of all plugins in the group filtered by ``blacklist``
Returns:
dict: Nested dictionary of plugins accessible through dot-notation.
Similar to :py:attr:`plugins`, but lowest level is a regular dictionary of
all unfiltered plugin versions for the given plugin type and name.
Parent types are always included.
Child plugins will only be included if at least one valid, non-blacklisted plugin
is available.
"""
if not self.loaded:
self.load_modules()
# pylint: disable=protected-access
return get_plugins()[self.group]._filter(blacklist=self.blacklist,
type_filter=self.type_filter) | [
"def",
"plugins_all",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"loaded",
":",
"self",
".",
"load_modules",
"(",
")",
"# pylint: disable=protected-access",
"return",
"get_plugins",
"(",
")",
"[",
"self",
".",
"group",
"]",
".",
"_filter",
"(",
"blac... | All resulting versions of all plugins in the group filtered by ``blacklist``
Returns:
dict: Nested dictionary of plugins accessible through dot-notation.
Similar to :py:attr:`plugins`, but lowest level is a regular dictionary of
all unfiltered plugin versions for the given plugin type and name.
Parent types are always included.
Child plugins will only be included if at least one valid, non-blacklisted plugin
is available. | [
"All",
"resulting",
"versions",
"of",
"all",
"plugins",
"in",
"the",
"group",
"filtered",
"by",
"blacklist"
] | train | https://github.com/Rockhopper-Technologies/pluginlib/blob/8beb78984dd9c97c493642df9da9f1b5a1c5e2b2/pluginlib/_loader.py#L349-L369 |
Rockhopper-Technologies/pluginlib | pluginlib/_loader.py | PluginLoader.get_plugin | def get_plugin(self, plugin_type, name, version=None):
"""
Args:
plugin_type(str): Parent type
name(str): Plugin name
version(str): Plugin version
Returns:
:py:class:`Plugin`: Plugin, or :py:data:`None` if plugin can't be found
Retrieve a specific plugin. ``blacklist`` and ``type_filter`` still apply.
If ``version`` is not specified, the newest available version is returned.
"""
if not self.loaded:
self.load_modules()
# pylint: disable=protected-access
return get_plugins()[self.group]._filter(blacklist=self.blacklist,
newest_only=True,
type_filter=self.type_filter,
type=plugin_type,
name=name,
version=version) | python | def get_plugin(self, plugin_type, name, version=None):
"""
Args:
plugin_type(str): Parent type
name(str): Plugin name
version(str): Plugin version
Returns:
:py:class:`Plugin`: Plugin, or :py:data:`None` if plugin can't be found
Retrieve a specific plugin. ``blacklist`` and ``type_filter`` still apply.
If ``version`` is not specified, the newest available version is returned.
"""
if not self.loaded:
self.load_modules()
# pylint: disable=protected-access
return get_plugins()[self.group]._filter(blacklist=self.blacklist,
newest_only=True,
type_filter=self.type_filter,
type=plugin_type,
name=name,
version=version) | [
"def",
"get_plugin",
"(",
"self",
",",
"plugin_type",
",",
"name",
",",
"version",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"loaded",
":",
"self",
".",
"load_modules",
"(",
")",
"# pylint: disable=protected-access",
"return",
"get_plugins",
"(",
")",... | Args:
plugin_type(str): Parent type
name(str): Plugin name
version(str): Plugin version
Returns:
:py:class:`Plugin`: Plugin, or :py:data:`None` if plugin can't be found
Retrieve a specific plugin. ``blacklist`` and ``type_filter`` still apply.
If ``version`` is not specified, the newest available version is returned. | [
"Args",
":",
"plugin_type",
"(",
"str",
")",
":",
"Parent",
"type",
"name",
"(",
"str",
")",
":",
"Plugin",
"name",
"version",
"(",
"str",
")",
":",
"Plugin",
"version"
] | train | https://github.com/Rockhopper-Technologies/pluginlib/blob/8beb78984dd9c97c493642df9da9f1b5a1c5e2b2/pluginlib/_loader.py#L371-L395 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.