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 |
|---|---|---|---|---|---|---|---|---|---|---|
theonion/django-bulbs | bulbs/campaigns/models.py | Campaign.save | def save(self, *args, **kwargs):
"""Kicks off celery task to re-save associated special coverages to percolator
:param args: inline arguments (optional)
:param kwargs: keyword arguments
:return: `bulbs.campaigns.Campaign`
"""
campaign = super(Campaign, self).save(*args, **kwargs)
save_campaign_special_coverage_percolator.delay(self.tunic_campaign_id)
return campaign | python | def save(self, *args, **kwargs):
"""Kicks off celery task to re-save associated special coverages to percolator
:param args: inline arguments (optional)
:param kwargs: keyword arguments
:return: `bulbs.campaigns.Campaign`
"""
campaign = super(Campaign, self).save(*args, **kwargs)
save_campaign_special_coverage_percolator.delay(self.tunic_campaign_id)
return campaign | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"campaign",
"=",
"super",
"(",
"Campaign",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"save_campaign_special_coverage_percolator",
".",... | Kicks off celery task to re-save associated special coverages to percolator
:param args: inline arguments (optional)
:param kwargs: keyword arguments
:return: `bulbs.campaigns.Campaign` | [
"Kicks",
"off",
"celery",
"task",
"to",
"re",
"-",
"save",
"associated",
"special",
"coverages",
"to",
"percolator"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/campaigns/models.py#L28-L37 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/structure/__init__.py | Count.count_rows_duplicates | def count_rows_duplicates(self, table, cols='*'):
"""Get the number of rows that do not contain distinct values."""
return self.count_rows(table, '*') - self.count_rows_distinct(table, cols) | python | def count_rows_duplicates(self, table, cols='*'):
"""Get the number of rows that do not contain distinct values."""
return self.count_rows(table, '*') - self.count_rows_distinct(table, cols) | [
"def",
"count_rows_duplicates",
"(",
"self",
",",
"table",
",",
"cols",
"=",
"'*'",
")",
":",
"return",
"self",
".",
"count_rows",
"(",
"table",
",",
"'*'",
")",
"-",
"self",
".",
"count_rows_distinct",
"(",
"table",
",",
"cols",
")"
] | Get the number of rows that do not contain distinct values. | [
"Get",
"the",
"number",
"of",
"rows",
"that",
"do",
"not",
"contain",
"distinct",
"values",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/__init__.py#L8-L10 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/structure/__init__.py | Count.count_rows | def count_rows(self, table, cols='*'):
"""Get the number of rows in a particular table."""
query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table))
result = self.fetch(query)
return result if result is not None else 0 | python | def count_rows(self, table, cols='*'):
"""Get the number of rows in a particular table."""
query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table))
result = self.fetch(query)
return result if result is not None else 0 | [
"def",
"count_rows",
"(",
"self",
",",
"table",
",",
"cols",
"=",
"'*'",
")",
":",
"query",
"=",
"'SELECT COUNT({0}) FROM {1}'",
".",
"format",
"(",
"join_cols",
"(",
"cols",
")",
",",
"wrap",
"(",
"table",
")",
")",
"result",
"=",
"self",
".",
"fetch"... | Get the number of rows in a particular table. | [
"Get",
"the",
"number",
"of",
"rows",
"in",
"a",
"particular",
"table",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/__init__.py#L16-L20 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/structure/__init__.py | Count.count_rows_distinct | def count_rows_distinct(self, table, cols='*'):
"""Get the number distinct of rows in a particular table."""
return self.fetch('SELECT COUNT(DISTINCT {0}) FROM {1}'.format(join_cols(cols), wrap(table))) | python | def count_rows_distinct(self, table, cols='*'):
"""Get the number distinct of rows in a particular table."""
return self.fetch('SELECT COUNT(DISTINCT {0}) FROM {1}'.format(join_cols(cols), wrap(table))) | [
"def",
"count_rows_distinct",
"(",
"self",
",",
"table",
",",
"cols",
"=",
"'*'",
")",
":",
"return",
"self",
".",
"fetch",
"(",
"'SELECT COUNT(DISTINCT {0}) FROM {1}'",
".",
"format",
"(",
"join_cols",
"(",
"cols",
")",
",",
"wrap",
"(",
"table",
")",
")"... | Get the number distinct of rows in a particular table. | [
"Get",
"the",
"number",
"distinct",
"of",
"rows",
"in",
"a",
"particular",
"table",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/__init__.py#L26-L28 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/structure/__init__.py | Structure.get_unique_column | def get_unique_column(self, table):
"""Determine if any of the columns in a table contain exclusively unique values."""
for col in self.get_columns(table):
if self.count_rows_duplicates(table, col) == 0:
return col | python | def get_unique_column(self, table):
"""Determine if any of the columns in a table contain exclusively unique values."""
for col in self.get_columns(table):
if self.count_rows_duplicates(table, col) == 0:
return col | [
"def",
"get_unique_column",
"(",
"self",
",",
"table",
")",
":",
"for",
"col",
"in",
"self",
".",
"get_columns",
"(",
"table",
")",
":",
"if",
"self",
".",
"count_rows_duplicates",
"(",
"table",
",",
"col",
")",
"==",
"0",
":",
"return",
"col"
] | Determine if any of the columns in a table contain exclusively unique values. | [
"Determine",
"if",
"any",
"of",
"the",
"columns",
"in",
"a",
"table",
"contain",
"exclusively",
"unique",
"values",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/__init__.py#L49-L53 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/structure/__init__.py | Structure.get_duplicate_vals | def get_duplicate_vals(self, table, column):
"""Retrieve duplicate values in a column of a table."""
query = 'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'.format(join_cols(column), wrap(table))
return self.fetch(query) | python | def get_duplicate_vals(self, table, column):
"""Retrieve duplicate values in a column of a table."""
query = 'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'.format(join_cols(column), wrap(table))
return self.fetch(query) | [
"def",
"get_duplicate_vals",
"(",
"self",
",",
"table",
",",
"column",
")",
":",
"query",
"=",
"'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'",
".",
"format",
"(",
"join_cols",
"(",
"column",
")",
",",
"wrap",
"(",
"table",
")",
")",
"return",
"self",
... | Retrieve duplicate values in a column of a table. | [
"Retrieve",
"duplicate",
"values",
"in",
"a",
"column",
"of",
"a",
"table",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/__init__.py#L55-L58 |
theonion/django-bulbs | bulbs/utils/metadata.py | BaseSimpleMetadata.get_field_info | def get_field_info(self, field):
"""
This method is basically a mirror from rest_framework==3.3.3
We are currently pinned to rest_framework==3.1.1. If we upgrade,
this can be refactored and simplified to rely more heavily on
rest_framework's built in logic.
"""
field_info = self.get_attributes(field)
field_info["required"] = getattr(field, "required", False)
field_info["type"] = self.get_label_lookup(field)
if getattr(field, "child", None):
field_info["child"] = self.get_field_info(field.child)
elif getattr(field, "fields", None):
field_info["children"] = self.get_serializer_info(field)
if (not isinstance(field, (serializers.RelatedField, serializers.ManyRelatedField)) and
hasattr(field, "choices")):
field_info["choices"] = [
{
"value": choice_value,
"display_name": force_text(choice_name, strings_only=True)
}
for choice_value, choice_name in field.choices.items()
]
return field_info | python | def get_field_info(self, field):
"""
This method is basically a mirror from rest_framework==3.3.3
We are currently pinned to rest_framework==3.1.1. If we upgrade,
this can be refactored and simplified to rely more heavily on
rest_framework's built in logic.
"""
field_info = self.get_attributes(field)
field_info["required"] = getattr(field, "required", False)
field_info["type"] = self.get_label_lookup(field)
if getattr(field, "child", None):
field_info["child"] = self.get_field_info(field.child)
elif getattr(field, "fields", None):
field_info["children"] = self.get_serializer_info(field)
if (not isinstance(field, (serializers.RelatedField, serializers.ManyRelatedField)) and
hasattr(field, "choices")):
field_info["choices"] = [
{
"value": choice_value,
"display_name": force_text(choice_name, strings_only=True)
}
for choice_value, choice_name in field.choices.items()
]
return field_info | [
"def",
"get_field_info",
"(",
"self",
",",
"field",
")",
":",
"field_info",
"=",
"self",
".",
"get_attributes",
"(",
"field",
")",
"field_info",
"[",
"\"required\"",
"]",
"=",
"getattr",
"(",
"field",
",",
"\"required\"",
",",
"False",
")",
"field_info",
"... | This method is basically a mirror from rest_framework==3.3.3
We are currently pinned to rest_framework==3.1.1. If we upgrade,
this can be refactored and simplified to rely more heavily on
rest_framework's built in logic. | [
"This",
"method",
"is",
"basically",
"a",
"mirror",
"from",
"rest_framework",
"==",
"3",
".",
"3",
".",
"3"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/utils/metadata.py#L40-L68 |
Sanji-IO/sanji | sanji/model/__init__.py | Model.maxId | def maxId(self):
"""int: current max id of objects"""
if len(self.model.db) == 0:
return 0
return max(map(lambda obj: obj["id"], self.model.db)) | python | def maxId(self):
"""int: current max id of objects"""
if len(self.model.db) == 0:
return 0
return max(map(lambda obj: obj["id"], self.model.db)) | [
"def",
"maxId",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"model",
".",
"db",
")",
"==",
"0",
":",
"return",
"0",
"return",
"max",
"(",
"map",
"(",
"lambda",
"obj",
":",
"obj",
"[",
"\"id\"",
"]",
",",
"self",
".",
"model",
".",
"... | int: current max id of objects | [
"int",
":",
"current",
"max",
"id",
"of",
"objects"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model/__init__.py#L47-L52 |
Sanji-IO/sanji | sanji/model/__init__.py | Model.add | def add(self, obj):
"""Add a object
Args:
Object: Object will be added
Returns:
Object: Object with id
Raises:
TypeError: If add object is not a dict
MultipleInvalid: If input object is invaild
"""
if not isinstance(obj, dict):
raise TypeError("Add object should be a dict object")
obj = self.validation(obj)
obj["id"] = self.maxId + 1
obj = self._cast_model(obj)
self.model.db.append(obj)
if not self._batch.enable.is_set():
self.model.save_db()
return obj | python | def add(self, obj):
"""Add a object
Args:
Object: Object will be added
Returns:
Object: Object with id
Raises:
TypeError: If add object is not a dict
MultipleInvalid: If input object is invaild
"""
if not isinstance(obj, dict):
raise TypeError("Add object should be a dict object")
obj = self.validation(obj)
obj["id"] = self.maxId + 1
obj = self._cast_model(obj)
self.model.db.append(obj)
if not self._batch.enable.is_set():
self.model.save_db()
return obj | [
"def",
"add",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Add object should be a dict object\"",
")",
"obj",
"=",
"self",
".",
"validation",
"(",
"obj",
")",
"obj",
"[",
... | Add a object
Args:
Object: Object will be added
Returns:
Object: Object with id
Raises:
TypeError: If add object is not a dict
MultipleInvalid: If input object is invaild | [
"Add",
"a",
"object",
"Args",
":",
"Object",
":",
"Object",
"will",
"be",
"added",
"Returns",
":",
"Object",
":",
"Object",
"with",
"id",
"Raises",
":",
"TypeError",
":",
"If",
"add",
"object",
"is",
"not",
"a",
"dict",
"MultipleInvalid",
":",
"If",
"i... | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model/__init__.py#L69-L88 |
Sanji-IO/sanji | sanji/model/__init__.py | Model.get | def get(self, id):
"""Get a object by id
Args:
id (int): Object id
Returns:
Object: Object with specified id
None: If object not found
"""
for obj in self.model.db:
if obj["id"] == id:
return self._cast_model(obj)
return None | python | def get(self, id):
"""Get a object by id
Args:
id (int): Object id
Returns:
Object: Object with specified id
None: If object not found
"""
for obj in self.model.db:
if obj["id"] == id:
return self._cast_model(obj)
return None | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"for",
"obj",
"in",
"self",
".",
"model",
".",
"db",
":",
"if",
"obj",
"[",
"\"id\"",
"]",
"==",
"id",
":",
"return",
"self",
".",
"_cast_model",
"(",
"obj",
")",
"return",
"None"
] | Get a object by id
Args:
id (int): Object id
Returns:
Object: Object with specified id
None: If object not found | [
"Get",
"a",
"object",
"by",
"id",
"Args",
":",
"id",
"(",
"int",
")",
":",
"Object",
"id"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model/__init__.py#L90-L103 |
Sanji-IO/sanji | sanji/model/__init__.py | Model.remove | def remove(self, id):
"""Remove a object by id
Args:
id (int): Object's id should be deleted
Returns:
len(int): affected rows
"""
before_len = len(self.model.db)
self.model.db = [t for t in self.model.db if t["id"] != id]
if not self._batch.enable.is_set():
self.model.save_db()
return before_len - len(self.model.db) | python | def remove(self, id):
"""Remove a object by id
Args:
id (int): Object's id should be deleted
Returns:
len(int): affected rows
"""
before_len = len(self.model.db)
self.model.db = [t for t in self.model.db if t["id"] != id]
if not self._batch.enable.is_set():
self.model.save_db()
return before_len - len(self.model.db) | [
"def",
"remove",
"(",
"self",
",",
"id",
")",
":",
"before_len",
"=",
"len",
"(",
"self",
".",
"model",
".",
"db",
")",
"self",
".",
"model",
".",
"db",
"=",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"model",
".",
"db",
"if",
"t",
"[",
"\"id\"... | Remove a object by id
Args:
id (int): Object's id should be deleted
Returns:
len(int): affected rows | [
"Remove",
"a",
"object",
"by",
"id",
"Args",
":",
"id",
"(",
"int",
")",
":",
"Object",
"s",
"id",
"should",
"be",
"deleted",
"Returns",
":",
"len",
"(",
"int",
")",
":",
"affected",
"rows"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model/__init__.py#L105-L116 |
Sanji-IO/sanji | sanji/model/__init__.py | Model.removeAll | def removeAll(self):
"""Remove all objects
Returns:
len(int): affected rows
"""
before_len = len(self.model.db)
self.model.db = []
if not self._batch.enable.is_set():
self.model.save_db()
return before_len - len(self.model.db) | python | def removeAll(self):
"""Remove all objects
Returns:
len(int): affected rows
"""
before_len = len(self.model.db)
self.model.db = []
if not self._batch.enable.is_set():
self.model.save_db()
return before_len - len(self.model.db) | [
"def",
"removeAll",
"(",
"self",
")",
":",
"before_len",
"=",
"len",
"(",
"self",
".",
"model",
".",
"db",
")",
"self",
".",
"model",
".",
"db",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"_batch",
".",
"enable",
".",
"is_set",
"(",
")",
":",
"se... | Remove all objects
Returns:
len(int): affected rows | [
"Remove",
"all",
"objects",
"Returns",
":",
"len",
"(",
"int",
")",
":",
"affected",
"rows"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model/__init__.py#L118-L127 |
Sanji-IO/sanji | sanji/model/__init__.py | Model.update | def update(self, id, newObj):
"""Update a object
Args:
id (int): Target Object ID
newObj (object): New object will be merged into original object
Returns:
Object: Updated object
None: If specified object id is not found
MultipleInvalid: If input object is invaild
"""
newObj = self.validation(newObj)
for obj in self.model.db:
if obj["id"] != id:
continue
newObj.pop("id", None)
obj.update(newObj)
obj = self._cast_model(obj)
if not self._batch.enable.is_set():
self.model.save_db()
return obj
return None | python | def update(self, id, newObj):
"""Update a object
Args:
id (int): Target Object ID
newObj (object): New object will be merged into original object
Returns:
Object: Updated object
None: If specified object id is not found
MultipleInvalid: If input object is invaild
"""
newObj = self.validation(newObj)
for obj in self.model.db:
if obj["id"] != id:
continue
newObj.pop("id", None)
obj.update(newObj)
obj = self._cast_model(obj)
if not self._batch.enable.is_set():
self.model.save_db()
return obj
return None | [
"def",
"update",
"(",
"self",
",",
"id",
",",
"newObj",
")",
":",
"newObj",
"=",
"self",
".",
"validation",
"(",
"newObj",
")",
"for",
"obj",
"in",
"self",
".",
"model",
".",
"db",
":",
"if",
"obj",
"[",
"\"id\"",
"]",
"!=",
"id",
":",
"continue"... | Update a object
Args:
id (int): Target Object ID
newObj (object): New object will be merged into original object
Returns:
Object: Updated object
None: If specified object id is not found
MultipleInvalid: If input object is invaild | [
"Update",
"a",
"object",
"Args",
":",
"id",
"(",
"int",
")",
":",
"Target",
"Object",
"ID",
"newObj",
"(",
"object",
")",
":",
"New",
"object",
"will",
"be",
"merged",
"into",
"original",
"object",
"Returns",
":",
"Object",
":",
"Updated",
"object",
"N... | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model/__init__.py#L129-L151 |
Sanji-IO/sanji | sanji/model/__init__.py | Model.set | def set(self, id, newObj):
"""Set a object
Args:
id (int): Target Object ID
newObj (object): New object will be set
Returns:
Object: New object
None: If specified object id is not found
MultipleInvalid: If input object is invaild
"""
newObj = self.validation(newObj)
for index in xrange(0, len(self.model.db)):
if self.model.db[index]["id"] != id:
continue
newObj["id"] = id
self.model.db[index] = self._cast_model(newObj)
if not self._batch.enable.is_set():
self.model.save_db()
return self.model.db[index]
return None | python | def set(self, id, newObj):
"""Set a object
Args:
id (int): Target Object ID
newObj (object): New object will be set
Returns:
Object: New object
None: If specified object id is not found
MultipleInvalid: If input object is invaild
"""
newObj = self.validation(newObj)
for index in xrange(0, len(self.model.db)):
if self.model.db[index]["id"] != id:
continue
newObj["id"] = id
self.model.db[index] = self._cast_model(newObj)
if not self._batch.enable.is_set():
self.model.save_db()
return self.model.db[index]
return None | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"newObj",
")",
":",
"newObj",
"=",
"self",
".",
"validation",
"(",
"newObj",
")",
"for",
"index",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"self",
".",
"model",
".",
"db",
")",
")",
":",
"if",
"self"... | Set a object
Args:
id (int): Target Object ID
newObj (object): New object will be set
Returns:
Object: New object
None: If specified object id is not found
MultipleInvalid: If input object is invaild | [
"Set",
"a",
"object",
"Args",
":",
"id",
"(",
"int",
")",
":",
"Target",
"Object",
"ID",
"newObj",
"(",
"object",
")",
":",
"New",
"object",
"will",
"be",
"set",
"Returns",
":",
"Object",
":",
"New",
"object",
"None",
":",
"If",
"specified",
"object"... | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model/__init__.py#L153-L174 |
Sanji-IO/sanji | sanji/model/__init__.py | Model.getAll | def getAll(self):
"""Get all objects
Returns:
List: list of all objects
"""
objs = []
for obj in self.model.db:
objs.append(self._cast_model(obj))
return objs | python | def getAll(self):
"""Get all objects
Returns:
List: list of all objects
"""
objs = []
for obj in self.model.db:
objs.append(self._cast_model(obj))
return objs | [
"def",
"getAll",
"(",
"self",
")",
":",
"objs",
"=",
"[",
"]",
"for",
"obj",
"in",
"self",
".",
"model",
".",
"db",
":",
"objs",
".",
"append",
"(",
"self",
".",
"_cast_model",
"(",
"obj",
")",
")",
"return",
"objs"
] | Get all objects
Returns:
List: list of all objects | [
"Get",
"all",
"objects",
"Returns",
":",
"List",
":",
"list",
"of",
"all",
"objects"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model/__init__.py#L176-L185 |
saghul/evergreen | evergreen/io/util.py | StringBuffer._double_prefix | def _double_prefix(self):
"""Grow the given deque by doubling, but don't split the second chunk just
because the first one is small.
"""
new_len = max(len(self._buf[0]) * 2, (len(self._buf[0]) + len(self._buf[1])))
self._merge_prefix(new_len) | python | def _double_prefix(self):
"""Grow the given deque by doubling, but don't split the second chunk just
because the first one is small.
"""
new_len = max(len(self._buf[0]) * 2, (len(self._buf[0]) + len(self._buf[1])))
self._merge_prefix(new_len) | [
"def",
"_double_prefix",
"(",
"self",
")",
":",
"new_len",
"=",
"max",
"(",
"len",
"(",
"self",
".",
"_buf",
"[",
"0",
"]",
")",
"*",
"2",
",",
"(",
"len",
"(",
"self",
".",
"_buf",
"[",
"0",
"]",
")",
"+",
"len",
"(",
"self",
".",
"_buf",
... | Grow the given deque by doubling, but don't split the second chunk just
because the first one is small. | [
"Grow",
"the",
"given",
"deque",
"by",
"doubling",
"but",
"don",
"t",
"split",
"the",
"second",
"chunk",
"just",
"because",
"the",
"first",
"one",
"is",
"small",
"."
] | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/io/util.py#L94-L99 |
saghul/evergreen | evergreen/io/util.py | StringBuffer._merge_prefix | def _merge_prefix(self, size):
"""Replace the first entries in a deque of strings with a single
string of up to size bytes.
>>> d = collections.deque(['abc', 'de', 'fghi', 'j'])
>>> _merge_prefix(d, 5); print(d)
deque(['abcde', 'fghi', 'j'])
Strings will be split as necessary to reach the desired size.
>>> _merge_prefix(d, 7); print(d)
deque(['abcdefg', 'hi', 'j'])
>>> _merge_prefix(d, 3); print(d)
deque(['abc', 'defg', 'hi', 'j'])
>>> _merge_prefix(d, 100); print(d)
deque(['abcdefghij'])
"""
if len(self._buf) == 1 and len(self._buf[0]) <= size:
return
prefix = []
remaining = size
while self._buf and remaining > 0:
chunk = self._buf.popleft()
if len(chunk) > remaining:
self._buf.appendleft(chunk[remaining:])
chunk = chunk[:remaining]
prefix.append(chunk)
remaining -= len(chunk)
if prefix:
self._buf.appendleft(b''.join(prefix))
if not self._buf:
self._buf.appendleft(b'') | python | def _merge_prefix(self, size):
"""Replace the first entries in a deque of strings with a single
string of up to size bytes.
>>> d = collections.deque(['abc', 'de', 'fghi', 'j'])
>>> _merge_prefix(d, 5); print(d)
deque(['abcde', 'fghi', 'j'])
Strings will be split as necessary to reach the desired size.
>>> _merge_prefix(d, 7); print(d)
deque(['abcdefg', 'hi', 'j'])
>>> _merge_prefix(d, 3); print(d)
deque(['abc', 'defg', 'hi', 'j'])
>>> _merge_prefix(d, 100); print(d)
deque(['abcdefghij'])
"""
if len(self._buf) == 1 and len(self._buf[0]) <= size:
return
prefix = []
remaining = size
while self._buf and remaining > 0:
chunk = self._buf.popleft()
if len(chunk) > remaining:
self._buf.appendleft(chunk[remaining:])
chunk = chunk[:remaining]
prefix.append(chunk)
remaining -= len(chunk)
if prefix:
self._buf.appendleft(b''.join(prefix))
if not self._buf:
self._buf.appendleft(b'') | [
"def",
"_merge_prefix",
"(",
"self",
",",
"size",
")",
":",
"if",
"len",
"(",
"self",
".",
"_buf",
")",
"==",
"1",
"and",
"len",
"(",
"self",
".",
"_buf",
"[",
"0",
"]",
")",
"<=",
"size",
":",
"return",
"prefix",
"=",
"[",
"]",
"remaining",
"=... | Replace the first entries in a deque of strings with a single
string of up to size bytes.
>>> d = collections.deque(['abc', 'de', 'fghi', 'j'])
>>> _merge_prefix(d, 5); print(d)
deque(['abcde', 'fghi', 'j'])
Strings will be split as necessary to reach the desired size.
>>> _merge_prefix(d, 7); print(d)
deque(['abcdefg', 'hi', 'j'])
>>> _merge_prefix(d, 3); print(d)
deque(['abc', 'defg', 'hi', 'j'])
>>> _merge_prefix(d, 100); print(d)
deque(['abcdefghij']) | [
"Replace",
"the",
"first",
"entries",
"in",
"a",
"deque",
"of",
"strings",
"with",
"a",
"single",
"string",
"of",
"up",
"to",
"size",
"bytes",
"."
] | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/io/util.py#L101-L133 |
theonion/django-bulbs | bulbs/special_coverage/utils.py | get_sponsored_special_coverages | def get_sponsored_special_coverages():
""":returns: Django query for all active special coverages with active campaigns."""
now = timezone.now()
qs = SpecialCoverage.objects.filter(
tunic_campaign_id__isnull=False,
)
return qs.filter(
start_date__lte=now,
end_date__gt=now
) | qs.filter(
start_date__lte=now,
end_date__isnull=True
) | python | def get_sponsored_special_coverages():
""":returns: Django query for all active special coverages with active campaigns."""
now = timezone.now()
qs = SpecialCoverage.objects.filter(
tunic_campaign_id__isnull=False,
)
return qs.filter(
start_date__lte=now,
end_date__gt=now
) | qs.filter(
start_date__lte=now,
end_date__isnull=True
) | [
"def",
"get_sponsored_special_coverages",
"(",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"qs",
"=",
"SpecialCoverage",
".",
"objects",
".",
"filter",
"(",
"tunic_campaign_id__isnull",
"=",
"False",
",",
")",
"return",
"qs",
".",
"filter",
"(",
... | :returns: Django query for all active special coverages with active campaigns. | [
":",
"returns",
":",
"Django",
"query",
"for",
"all",
"active",
"special",
"coverages",
"with",
"active",
"campaigns",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/utils.py#L10-L22 |
theonion/django-bulbs | bulbs/special_coverage/utils.py | get_sponsored_special_coverage_query | def get_sponsored_special_coverage_query(only_recent=False):
"""
Reference to all SpecialCovearge queries.
:param only_recent: references RECENT_SPONSORED_OFFSET_HOURS from django settings.
Used to return sponsored content within a given configuration of hours.
:returns: Djes.LazySearch query matching all active speical coverages.
"""
special_coverages = get_sponsored_special_coverages()
es_query = SearchParty(special_coverages).search()
if only_recent:
offset = getattr(settings, "RECENT_SPONSORED_OFFSET_HOURS", 0)
es_query = es_query.filter(
Published(after=timezone.now() - timezone.timedelta(hours=offset))
)
return es_query | python | def get_sponsored_special_coverage_query(only_recent=False):
"""
Reference to all SpecialCovearge queries.
:param only_recent: references RECENT_SPONSORED_OFFSET_HOURS from django settings.
Used to return sponsored content within a given configuration of hours.
:returns: Djes.LazySearch query matching all active speical coverages.
"""
special_coverages = get_sponsored_special_coverages()
es_query = SearchParty(special_coverages).search()
if only_recent:
offset = getattr(settings, "RECENT_SPONSORED_OFFSET_HOURS", 0)
es_query = es_query.filter(
Published(after=timezone.now() - timezone.timedelta(hours=offset))
)
return es_query | [
"def",
"get_sponsored_special_coverage_query",
"(",
"only_recent",
"=",
"False",
")",
":",
"special_coverages",
"=",
"get_sponsored_special_coverages",
"(",
")",
"es_query",
"=",
"SearchParty",
"(",
"special_coverages",
")",
".",
"search",
"(",
")",
"if",
"only_recent... | Reference to all SpecialCovearge queries.
:param only_recent: references RECENT_SPONSORED_OFFSET_HOURS from django settings.
Used to return sponsored content within a given configuration of hours.
:returns: Djes.LazySearch query matching all active speical coverages. | [
"Reference",
"to",
"all",
"SpecialCovearge",
"queries",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/utils.py#L25-L40 |
TurboGears/backlash | backlash/debug.py | DebuggedApplication.debug_application | def debug_application(self, environ, start_response):
"""Run the application and conserve the traceback frames."""
app_iter = None
try:
app_iter = self.app(environ, start_response)
for item in app_iter:
yield item
if hasattr(app_iter, 'close'):
app_iter.close()
except Exception:
if hasattr(app_iter, 'close'):
app_iter.close()
context = RequestContext({'environ':dict(environ)})
for injector in self.context_injectors:
context.update(injector(environ))
traceback = get_current_traceback(skip=1, show_hidden_frames=self.show_hidden_frames,
context=context)
for frame in traceback.frames:
self.frames[frame.id] = frame
self.tracebacks[traceback.id] = traceback
try:
start_response('500 INTERNAL SERVER ERROR', [
('Content-Type', 'text/html; charset=utf-8'),
# Disable Chrome's XSS protection, the debug
# output can cause false-positives.
('X-XSS-Protection', '0'),
])
except Exception:
# if we end up here there has been output but an error
# occurred. in that situation we can do nothing fancy any
# more, better log something into the error log and fall
# back gracefully.
environ['wsgi.errors'].write(
'Debugging middleware caught exception in streamed '
'response at a point where response headers were already '
'sent.\n')
else:
yield traceback.render_full(
evalex=self.evalex,
secret=self.secret
).encode('utf-8', 'replace')
# This will lead to double logging in case backlash logger is set to DEBUG
# but this is actually wanted as some environments, like WebTest, swallow
# wsgi.environ making the traceback totally disappear.
log.debug(traceback.plaintext)
traceback.log(environ['wsgi.errors']) | python | def debug_application(self, environ, start_response):
"""Run the application and conserve the traceback frames."""
app_iter = None
try:
app_iter = self.app(environ, start_response)
for item in app_iter:
yield item
if hasattr(app_iter, 'close'):
app_iter.close()
except Exception:
if hasattr(app_iter, 'close'):
app_iter.close()
context = RequestContext({'environ':dict(environ)})
for injector in self.context_injectors:
context.update(injector(environ))
traceback = get_current_traceback(skip=1, show_hidden_frames=self.show_hidden_frames,
context=context)
for frame in traceback.frames:
self.frames[frame.id] = frame
self.tracebacks[traceback.id] = traceback
try:
start_response('500 INTERNAL SERVER ERROR', [
('Content-Type', 'text/html; charset=utf-8'),
# Disable Chrome's XSS protection, the debug
# output can cause false-positives.
('X-XSS-Protection', '0'),
])
except Exception:
# if we end up here there has been output but an error
# occurred. in that situation we can do nothing fancy any
# more, better log something into the error log and fall
# back gracefully.
environ['wsgi.errors'].write(
'Debugging middleware caught exception in streamed '
'response at a point where response headers were already '
'sent.\n')
else:
yield traceback.render_full(
evalex=self.evalex,
secret=self.secret
).encode('utf-8', 'replace')
# This will lead to double logging in case backlash logger is set to DEBUG
# but this is actually wanted as some environments, like WebTest, swallow
# wsgi.environ making the traceback totally disappear.
log.debug(traceback.plaintext)
traceback.log(environ['wsgi.errors']) | [
"def",
"debug_application",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"app_iter",
"=",
"None",
"try",
":",
"app_iter",
"=",
"self",
".",
"app",
"(",
"environ",
",",
"start_response",
")",
"for",
"item",
"in",
"app_iter",
":",
"yield",
... | Run the application and conserve the traceback frames. | [
"Run",
"the",
"application",
"and",
"conserve",
"the",
"traceback",
"frames",
"."
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/debug.py#L75-L124 |
TurboGears/backlash | backlash/debug.py | DebuggedApplication.display_console | def display_console(self, request):
"""Display a standalone shell."""
if 0 not in self.frames:
self.frames[0] = _ConsoleFrame(self.console_init_func())
return Response(render_console_html(secret=self.secret),
content_type='text/html') | python | def display_console(self, request):
"""Display a standalone shell."""
if 0 not in self.frames:
self.frames[0] = _ConsoleFrame(self.console_init_func())
return Response(render_console_html(secret=self.secret),
content_type='text/html') | [
"def",
"display_console",
"(",
"self",
",",
"request",
")",
":",
"if",
"0",
"not",
"in",
"self",
".",
"frames",
":",
"self",
".",
"frames",
"[",
"0",
"]",
"=",
"_ConsoleFrame",
"(",
"self",
".",
"console_init_func",
"(",
")",
")",
"return",
"Response",... | Display a standalone shell. | [
"Display",
"a",
"standalone",
"shell",
"."
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/debug.py#L130-L135 |
TurboGears/backlash | backlash/debug.py | DebuggedApplication.paste_traceback | def paste_traceback(self, request, traceback):
"""Paste the traceback and return a JSON response."""
rv = traceback.paste()
return Response(json.dumps(rv), content_type='application/json') | python | def paste_traceback(self, request, traceback):
"""Paste the traceback and return a JSON response."""
rv = traceback.paste()
return Response(json.dumps(rv), content_type='application/json') | [
"def",
"paste_traceback",
"(",
"self",
",",
"request",
",",
"traceback",
")",
":",
"rv",
"=",
"traceback",
".",
"paste",
"(",
")",
"return",
"Response",
"(",
"json",
".",
"dumps",
"(",
"rv",
")",
",",
"content_type",
"=",
"'application/json'",
")"
] | Paste the traceback and return a JSON response. | [
"Paste",
"the",
"traceback",
"and",
"return",
"a",
"JSON",
"response",
"."
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/debug.py#L137-L140 |
theonion/django-bulbs | bulbs/contributions/filters.py | ESPublishedFilterBackend.filter_queryset | def filter_queryset(self, request, queryset, view):
"""Apply the relevant behaviors to the view queryset."""
start_value = self.get_start(request)
if start_value:
queryset = self.apply_published_filter(queryset, "after", start_value)
end_value = self.get_end(request)
if end_value:
# Forces the end_value to be the last second of the date provided in the query.
# Necessary currently as our Published filter for es only applies to gte & lte.
queryset = self.apply_published_filter(queryset, "before", end_value)
return queryset | python | def filter_queryset(self, request, queryset, view):
"""Apply the relevant behaviors to the view queryset."""
start_value = self.get_start(request)
if start_value:
queryset = self.apply_published_filter(queryset, "after", start_value)
end_value = self.get_end(request)
if end_value:
# Forces the end_value to be the last second of the date provided in the query.
# Necessary currently as our Published filter for es only applies to gte & lte.
queryset = self.apply_published_filter(queryset, "before", end_value)
return queryset | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"start_value",
"=",
"self",
".",
"get_start",
"(",
"request",
")",
"if",
"start_value",
":",
"queryset",
"=",
"self",
".",
"apply_published_filter",
"(",
"queryset... | Apply the relevant behaviors to the view queryset. | [
"Apply",
"the",
"relevant",
"behaviors",
"to",
"the",
"view",
"queryset",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/contributions/filters.py#L16-L26 |
theonion/django-bulbs | bulbs/contributions/filters.py | ESPublishedFilterBackend.apply_published_filter | def apply_published_filter(self, queryset, operation, value):
"""
Add the appropriate Published filter to a given elasticsearch query.
:param queryset: The DJES queryset object to be filtered.
:param operation: The type of filter (before/after).
:param value: The date or datetime value being applied to the filter.
"""
if operation not in ["after", "before"]:
raise ValueError("""Publish filters only use before or after for range filters.""")
return queryset.filter(Published(**{operation: value})) | python | def apply_published_filter(self, queryset, operation, value):
"""
Add the appropriate Published filter to a given elasticsearch query.
:param queryset: The DJES queryset object to be filtered.
:param operation: The type of filter (before/after).
:param value: The date or datetime value being applied to the filter.
"""
if operation not in ["after", "before"]:
raise ValueError("""Publish filters only use before or after for range filters.""")
return queryset.filter(Published(**{operation: value})) | [
"def",
"apply_published_filter",
"(",
"self",
",",
"queryset",
",",
"operation",
",",
"value",
")",
":",
"if",
"operation",
"not",
"in",
"[",
"\"after\"",
",",
"\"before\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"\"\"Publish filters only use before or after for ra... | Add the appropriate Published filter to a given elasticsearch query.
:param queryset: The DJES queryset object to be filtered.
:param operation: The type of filter (before/after).
:param value: The date or datetime value being applied to the filter. | [
"Add",
"the",
"appropriate",
"Published",
"filter",
"to",
"a",
"given",
"elasticsearch",
"query",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/contributions/filters.py#L28-L38 |
theonion/django-bulbs | bulbs/contributions/filters.py | ESPublishedFilterBackend.get_date_datetime_param | def get_date_datetime_param(self, request, param):
"""Check the request for the provided query parameter and returns a rounded value.
:param request: WSGI request object to retrieve query parameter data.
:param param: the name of the query parameter.
"""
if param in request.GET:
param_value = request.GET.get(param, None)
# Match and interpret param if formatted as a date.
date_match = dateparse.date_re.match(param_value)
if date_match:
return timezone.datetime.combine(
dateparse.parse_date(date_match.group(0)), timezone.datetime.min.time()
)
datetime_match = dateparse.datetime_re.match(param_value)
if datetime_match:
return timezone.datetime.combine(
dateparse.parse_datetime(datetime_match.group(0)).date(),
timezone.datetime.min.time()
)
return None | python | def get_date_datetime_param(self, request, param):
"""Check the request for the provided query parameter and returns a rounded value.
:param request: WSGI request object to retrieve query parameter data.
:param param: the name of the query parameter.
"""
if param in request.GET:
param_value = request.GET.get(param, None)
# Match and interpret param if formatted as a date.
date_match = dateparse.date_re.match(param_value)
if date_match:
return timezone.datetime.combine(
dateparse.parse_date(date_match.group(0)), timezone.datetime.min.time()
)
datetime_match = dateparse.datetime_re.match(param_value)
if datetime_match:
return timezone.datetime.combine(
dateparse.parse_datetime(datetime_match.group(0)).date(),
timezone.datetime.min.time()
)
return None | [
"def",
"get_date_datetime_param",
"(",
"self",
",",
"request",
",",
"param",
")",
":",
"if",
"param",
"in",
"request",
".",
"GET",
":",
"param_value",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"param",
",",
"None",
")",
"# Match and interpret param if for... | Check the request for the provided query parameter and returns a rounded value.
:param request: WSGI request object to retrieve query parameter data.
:param param: the name of the query parameter. | [
"Check",
"the",
"request",
"for",
"the",
"provided",
"query",
"parameter",
"and",
"returns",
"a",
"rounded",
"value",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/contributions/filters.py#L52-L72 |
Sanji-IO/sanji | sanji/session.py | Session.create | def create(self, message, mid=None, age=60, force=True):
"""
create session
force if you pass `force = False`, it may raise SessionError
due to duplicate message id
"""
with self.session_lock:
if not hasattr(message, "id"):
message.__setattr__("id", "event-%s" % (uuid.uuid4().hex,))
if self.session_list.get(message.id, None) is not None:
if force is False:
raise SessionError("Message id: %s duplicate!" %
message.id)
else:
message = Message(message.to_dict(), generate_id=True)
session = {
"status": Status.CREATED,
"message": message,
"age": age,
"mid": mid,
"created_at": time(),
"is_published": Event(),
"is_resolved": Event()
}
self.session_list.update({
message.id: session
})
return session | python | def create(self, message, mid=None, age=60, force=True):
"""
create session
force if you pass `force = False`, it may raise SessionError
due to duplicate message id
"""
with self.session_lock:
if not hasattr(message, "id"):
message.__setattr__("id", "event-%s" % (uuid.uuid4().hex,))
if self.session_list.get(message.id, None) is not None:
if force is False:
raise SessionError("Message id: %s duplicate!" %
message.id)
else:
message = Message(message.to_dict(), generate_id=True)
session = {
"status": Status.CREATED,
"message": message,
"age": age,
"mid": mid,
"created_at": time(),
"is_published": Event(),
"is_resolved": Event()
}
self.session_list.update({
message.id: session
})
return session | [
"def",
"create",
"(",
"self",
",",
"message",
",",
"mid",
"=",
"None",
",",
"age",
"=",
"60",
",",
"force",
"=",
"True",
")",
":",
"with",
"self",
".",
"session_lock",
":",
"if",
"not",
"hasattr",
"(",
"message",
",",
"\"id\"",
")",
":",
"message",... | create session
force if you pass `force = False`, it may raise SessionError
due to duplicate message id | [
"create",
"session",
"force",
"if",
"you",
"pass",
"force",
"=",
"False",
"it",
"may",
"raise",
"SessionError",
"due",
"to",
"duplicate",
"message",
"id"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/session.py#L85-L114 |
PGower/PyCanvas | pycanvas/apis/quiz_submissions.py | QuizSubmissionsAPI.get_all_quiz_submissions | def get_all_quiz_submissions(self, quiz_id, course_id, include=None):
"""
Get all quiz submissions.
Get a list of all submissions for this quiz. Users who can view or manage
grades for a course will have submissions from multiple users returned. A
user who can only submit will have only their own submissions returned. When
a user has an in-progress submission, only that submission is returned. When
there isn't an in-progress quiz_submission, all completed submissions,
including previous attempts, are returned.
<b>200 OK</b> response code is returned if the request was successful.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# OPTIONAL - include
"""Associations to include with the quiz submission."""
if include is not None:
self._validate_enum(include, ["submission", "quiz", "user"])
params["include"] = include
self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions".format(**path), data=data, params=params, no_data=True) | python | def get_all_quiz_submissions(self, quiz_id, course_id, include=None):
"""
Get all quiz submissions.
Get a list of all submissions for this quiz. Users who can view or manage
grades for a course will have submissions from multiple users returned. A
user who can only submit will have only their own submissions returned. When
a user has an in-progress submission, only that submission is returned. When
there isn't an in-progress quiz_submission, all completed submissions,
including previous attempts, are returned.
<b>200 OK</b> response code is returned if the request was successful.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# OPTIONAL - include
"""Associations to include with the quiz submission."""
if include is not None:
self._validate_enum(include, ["submission", "quiz", "user"])
params["include"] = include
self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions".format(**path), data=data, params=params, no_data=True) | [
"def",
"get_all_quiz_submissions",
"(",
"self",
",",
"quiz_id",
",",
"course_id",
",",
"include",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
... | Get all quiz submissions.
Get a list of all submissions for this quiz. Users who can view or manage
grades for a course will have submissions from multiple users returned. A
user who can only submit will have only their own submissions returned. When
a user has an in-progress submission, only that submission is returned. When
there isn't an in-progress quiz_submission, all completed submissions,
including previous attempts, are returned.
<b>200 OK</b> response code is returned if the request was successful. | [
"Get",
"all",
"quiz",
"submissions",
".",
"Get",
"a",
"list",
"of",
"all",
"submissions",
"for",
"this",
"quiz",
".",
"Users",
"who",
"can",
"view",
"or",
"manage",
"grades",
"for",
"a",
"course",
"will",
"have",
"submissions",
"from",
"multiple",
"users",... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quiz_submissions.py#L19-L51 |
PGower/PyCanvas | pycanvas/apis/quiz_submissions.py | QuizSubmissionsAPI.create_quiz_submission_start_quiz_taking_session | def create_quiz_submission_start_quiz_taking_session(self, quiz_id, course_id, access_code=None, preview=None):
"""
Create the quiz submission (start a quiz-taking session).
Start taking a Quiz by creating a QuizSubmission which you can use to answer
questions and submit your answers.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>400 Bad Request</b> if the quiz is locked
* <b>403 Forbidden</b> if an invalid access code is specified
* <b>403 Forbidden</b> if the Quiz's IP filter restriction does not pass
* <b>409 Conflict</b> if a QuizSubmission already exists for this user and quiz
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# OPTIONAL - access_code
"""Access code for the Quiz, if any."""
if access_code is not None:
data["access_code"] = access_code
# OPTIONAL - preview
"""Whether this should be a preview QuizSubmission and not count towards
the user's course record. Teachers only."""
if preview is not None:
data["preview"] = preview
self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions".format(**path), data=data, params=params, no_data=True) | python | def create_quiz_submission_start_quiz_taking_session(self, quiz_id, course_id, access_code=None, preview=None):
"""
Create the quiz submission (start a quiz-taking session).
Start taking a Quiz by creating a QuizSubmission which you can use to answer
questions and submit your answers.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>400 Bad Request</b> if the quiz is locked
* <b>403 Forbidden</b> if an invalid access code is specified
* <b>403 Forbidden</b> if the Quiz's IP filter restriction does not pass
* <b>409 Conflict</b> if a QuizSubmission already exists for this user and quiz
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# OPTIONAL - access_code
"""Access code for the Quiz, if any."""
if access_code is not None:
data["access_code"] = access_code
# OPTIONAL - preview
"""Whether this should be a preview QuizSubmission and not count towards
the user's course record. Teachers only."""
if preview is not None:
data["preview"] = preview
self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions".format(**path), data=data, params=params, no_data=True) | [
"def",
"create_quiz_submission_start_quiz_taking_session",
"(",
"self",
",",
"quiz_id",
",",
"course_id",
",",
"access_code",
"=",
"None",
",",
"preview",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQU... | Create the quiz submission (start a quiz-taking session).
Start taking a Quiz by creating a QuizSubmission which you can use to answer
questions and submit your answers.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>400 Bad Request</b> if the quiz is locked
* <b>403 Forbidden</b> if an invalid access code is specified
* <b>403 Forbidden</b> if the Quiz's IP filter restriction does not pass
* <b>409 Conflict</b> if a QuizSubmission already exists for this user and quiz | [
"Create",
"the",
"quiz",
"submission",
"(",
"start",
"a",
"quiz",
"-",
"taking",
"session",
")",
".",
"Start",
"taking",
"a",
"Quiz",
"by",
"creating",
"a",
"QuizSubmission",
"which",
"you",
"can",
"use",
"to",
"answer",
"questions",
"and",
"submit",
"your... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quiz_submissions.py#L115-L154 |
PGower/PyCanvas | pycanvas/apis/quiz_submissions.py | QuizSubmissionsAPI.update_student_question_scores_and_comments | def update_student_question_scores_and_comments(self, id, quiz_id, attempt, course_id, fudge_points=None, questions=None):
"""
Update student question scores and comments.
Update the amount of points a student has scored for questions they've
answered, provide comments for the student about their answer(s), or simply
fudge the total score by a specific amount of points.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>403 Forbidden</b> if you are not a teacher in this course
* <b>400 Bad Request</b> if the attempt parameter is missing or invalid
* <b>400 Bad Request</b> if the specified QS attempt is not yet complete
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# REQUIRED - attempt
"""The attempt number of the quiz submission that should be updated. This
attempt MUST be already completed."""
data["attempt"] = attempt
# OPTIONAL - fudge_points
"""Amount of positive or negative points to fudge the total score by."""
if fudge_points is not None:
data["fudge_points"] = fudge_points
# OPTIONAL - questions
"""A set of scores and comments for each question answered by the student.
The keys are the question IDs, and the values are hashes of `score` and
`comment` entries. See {Appendix: Manual Scoring} for more on this
parameter."""
if questions is not None:
data["questions"] = questions
self.logger.debug("PUT /api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions/{id}".format(**path), data=data, params=params, no_data=True) | python | def update_student_question_scores_and_comments(self, id, quiz_id, attempt, course_id, fudge_points=None, questions=None):
"""
Update student question scores and comments.
Update the amount of points a student has scored for questions they've
answered, provide comments for the student about their answer(s), or simply
fudge the total score by a specific amount of points.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>403 Forbidden</b> if you are not a teacher in this course
* <b>400 Bad Request</b> if the attempt parameter is missing or invalid
* <b>400 Bad Request</b> if the specified QS attempt is not yet complete
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# REQUIRED - attempt
"""The attempt number of the quiz submission that should be updated. This
attempt MUST be already completed."""
data["attempt"] = attempt
# OPTIONAL - fudge_points
"""Amount of positive or negative points to fudge the total score by."""
if fudge_points is not None:
data["fudge_points"] = fudge_points
# OPTIONAL - questions
"""A set of scores and comments for each question answered by the student.
The keys are the question IDs, and the values are hashes of `score` and
`comment` entries. See {Appendix: Manual Scoring} for more on this
parameter."""
if questions is not None:
data["questions"] = questions
self.logger.debug("PUT /api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions/{id}".format(**path), data=data, params=params, no_data=True) | [
"def",
"update_student_question_scores_and_comments",
"(",
"self",
",",
"id",
",",
"quiz_id",
",",
"attempt",
",",
"course_id",
",",
"fudge_points",
"=",
"None",
",",
"questions",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params... | Update student question scores and comments.
Update the amount of points a student has scored for questions they've
answered, provide comments for the student about their answer(s), or simply
fudge the total score by a specific amount of points.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>403 Forbidden</b> if you are not a teacher in this course
* <b>400 Bad Request</b> if the attempt parameter is missing or invalid
* <b>400 Bad Request</b> if the specified QS attempt is not yet complete | [
"Update",
"student",
"question",
"scores",
"and",
"comments",
".",
"Update",
"the",
"amount",
"of",
"points",
"a",
"student",
"has",
"scored",
"for",
"questions",
"they",
"ve",
"answered",
"provide",
"comments",
"for",
"the",
"student",
"about",
"their",
"answ... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quiz_submissions.py#L156-L206 |
PGower/PyCanvas | pycanvas/apis/quiz_submissions.py | QuizSubmissionsAPI.complete_quiz_submission_turn_it_in | def complete_quiz_submission_turn_it_in(self, id, quiz_id, attempt, course_id, validation_token, access_code=None):
"""
Complete the quiz submission (turn it in).
Complete the quiz submission by marking it as complete and grading it. When
the quiz submission has been marked as complete, no further modifications
will be allowed.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>403 Forbidden</b> if an invalid access code is specified
* <b>403 Forbidden</b> if the Quiz's IP filter restriction does not pass
* <b>403 Forbidden</b> if an invalid token is specified
* <b>400 Bad Request</b> if the QS is already complete
* <b>400 Bad Request</b> if the attempt parameter is missing
* <b>400 Bad Request</b> if the attempt parameter is not the latest attempt
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# REQUIRED - attempt
"""The attempt number of the quiz submission that should be completed. Note
that this must be the latest attempt index, as earlier attempts can not
be modified."""
data["attempt"] = attempt
# REQUIRED - validation_token
"""The unique validation token you received when this Quiz Submission was
created."""
data["validation_token"] = validation_token
# OPTIONAL - access_code
"""Access code for the Quiz, if any."""
if access_code is not None:
data["access_code"] = access_code
self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions/{id}/complete with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions/{id}/complete".format(**path), data=data, params=params, no_data=True) | python | def complete_quiz_submission_turn_it_in(self, id, quiz_id, attempt, course_id, validation_token, access_code=None):
"""
Complete the quiz submission (turn it in).
Complete the quiz submission by marking it as complete and grading it. When
the quiz submission has been marked as complete, no further modifications
will be allowed.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>403 Forbidden</b> if an invalid access code is specified
* <b>403 Forbidden</b> if the Quiz's IP filter restriction does not pass
* <b>403 Forbidden</b> if an invalid token is specified
* <b>400 Bad Request</b> if the QS is already complete
* <b>400 Bad Request</b> if the attempt parameter is missing
* <b>400 Bad Request</b> if the attempt parameter is not the latest attempt
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# REQUIRED - attempt
"""The attempt number of the quiz submission that should be completed. Note
that this must be the latest attempt index, as earlier attempts can not
be modified."""
data["attempt"] = attempt
# REQUIRED - validation_token
"""The unique validation token you received when this Quiz Submission was
created."""
data["validation_token"] = validation_token
# OPTIONAL - access_code
"""Access code for the Quiz, if any."""
if access_code is not None:
data["access_code"] = access_code
self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions/{id}/complete with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions/{id}/complete".format(**path), data=data, params=params, no_data=True) | [
"def",
"complete_quiz_submission_turn_it_in",
"(",
"self",
",",
"id",
",",
"quiz_id",
",",
"attempt",
",",
"course_id",
",",
"validation_token",
",",
"access_code",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
... | Complete the quiz submission (turn it in).
Complete the quiz submission by marking it as complete and grading it. When
the quiz submission has been marked as complete, no further modifications
will be allowed.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>403 Forbidden</b> if an invalid access code is specified
* <b>403 Forbidden</b> if the Quiz's IP filter restriction does not pass
* <b>403 Forbidden</b> if an invalid token is specified
* <b>400 Bad Request</b> if the QS is already complete
* <b>400 Bad Request</b> if the attempt parameter is missing
* <b>400 Bad Request</b> if the attempt parameter is not the latest attempt | [
"Complete",
"the",
"quiz",
"submission",
"(",
"turn",
"it",
"in",
")",
".",
"Complete",
"the",
"quiz",
"submission",
"by",
"marking",
"it",
"as",
"complete",
"and",
"grading",
"it",
".",
"When",
"the",
"quiz",
"submission",
"has",
"been",
"marked",
"as",
... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quiz_submissions.py#L208-L259 |
LIVVkit/LIVVkit | livvkit/util/options.py | parse_args | def parse_args(args=None):
"""
Handles the parsing of options for LIVVkit's command line interface
Args:
args: The list of arguments, typically sys.argv[1:]
"""
parser = argparse.ArgumentParser(description="Main script to run LIVVkit.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
fromfile_prefix_chars='@')
parser.add_argument('-o', '--out-dir',
default=os.path.join(os.getcwd(), "vv_" + time.strftime("%Y-%m-%d")),
help='Location to output the LIVVkit webpages.'
)
parser.add_argument('-v', '--verify',
nargs=2,
default=None,
help=' '.join(['Specify the locations of the test and bench bundle to',
'compare (respectively).'
])
)
parser.add_argument('-V', '--validate',
action='store',
nargs='+',
default=None,
help=' '.join(['Specify the location of the configuration files for',
'validation tests.'
])
)
# FIXME: this just short-circuits to the validation option, and should become its own module
parser.add_argument('-e', '--extension',
action='store',
nargs='+',
default=None,
dest='validate',
metavar='EXTENSION',
help=' '.join(['Specify the location of the configuration files for',
'LIVVkit extensions.'
])
)
parser.add_argument('-p', '--publish',
action='store_true',
help=' '.join(['Also produce a publication quality copy of the figure in',
'the output directory (eps, 600d pi).'
])
)
parser.add_argument('-s', '--serve',
nargs='?', type=int, const=8000,
help=' '.join(['Start a simple HTTP server for the output website specified',
'by OUT_DIR on port SERVE.'
])
)
parser.add_argument('--version',
action='version',
version='LIVVkit {}'.format(livvkit.__version__),
help="Show LIVVkit's version number and exit"
)
return init(parser.parse_args(args)) | python | def parse_args(args=None):
"""
Handles the parsing of options for LIVVkit's command line interface
Args:
args: The list of arguments, typically sys.argv[1:]
"""
parser = argparse.ArgumentParser(description="Main script to run LIVVkit.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
fromfile_prefix_chars='@')
parser.add_argument('-o', '--out-dir',
default=os.path.join(os.getcwd(), "vv_" + time.strftime("%Y-%m-%d")),
help='Location to output the LIVVkit webpages.'
)
parser.add_argument('-v', '--verify',
nargs=2,
default=None,
help=' '.join(['Specify the locations of the test and bench bundle to',
'compare (respectively).'
])
)
parser.add_argument('-V', '--validate',
action='store',
nargs='+',
default=None,
help=' '.join(['Specify the location of the configuration files for',
'validation tests.'
])
)
# FIXME: this just short-circuits to the validation option, and should become its own module
parser.add_argument('-e', '--extension',
action='store',
nargs='+',
default=None,
dest='validate',
metavar='EXTENSION',
help=' '.join(['Specify the location of the configuration files for',
'LIVVkit extensions.'
])
)
parser.add_argument('-p', '--publish',
action='store_true',
help=' '.join(['Also produce a publication quality copy of the figure in',
'the output directory (eps, 600d pi).'
])
)
parser.add_argument('-s', '--serve',
nargs='?', type=int, const=8000,
help=' '.join(['Start a simple HTTP server for the output website specified',
'by OUT_DIR on port SERVE.'
])
)
parser.add_argument('--version',
action='version',
version='LIVVkit {}'.format(livvkit.__version__),
help="Show LIVVkit's version number and exit"
)
return init(parser.parse_args(args)) | [
"def",
"parse_args",
"(",
"args",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Main script to run LIVVkit.\"",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
",",
"fromfile_prefix_... | Handles the parsing of options for LIVVkit's command line interface
Args:
args: The list of arguments, typically sys.argv[1:] | [
"Handles",
"the",
"parsing",
"of",
"options",
"for",
"LIVVkit",
"s",
"command",
"line",
"interface"
] | train | https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/options.py#L43-L108 |
LIVVkit/LIVVkit | livvkit/util/options.py | init | def init(options):
""" Initialize some defaults """
# Set matlplotlib's backend so LIVVkit can plot to files.
import matplotlib
matplotlib.use('agg')
livvkit.output_dir = os.path.abspath(options.out_dir)
livvkit.index_dir = livvkit.output_dir
livvkit.verify = True if options.verify is not None else False
livvkit.validate = True if options.validate is not None else False
livvkit.publish = options.publish
# Get a list of bundles that provide model specific implementations
available_bundles = [mod for imp, mod, ispkg in pkgutil.iter_modules(bundles.__path__)]
if options.verify is not None:
livvkit.model_dir = os.path.normpath(options.verify[0])
livvkit.bench_dir = os.path.normpath(options.verify[1])
if not os.path.isdir(livvkit.model_dir):
print("")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" UH OH!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" Your comparison directory does not exist; please check")
print(" the path:")
print("\n"+livvkit.model_dir+"\n\n")
sys.exit(1)
if not os.path.isdir(livvkit.bench_dir):
print("")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" UH OH!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" Your benchmark directory does not exist; please check")
print(" the path:")
print("\n"+livvkit.bench_dir+"\n\n")
sys.exit(1)
livvkit.model_bundle = os.path.basename(livvkit.model_dir)
livvkit.bench_bundle = os.path.basename(livvkit.bench_dir)
if livvkit.model_bundle in available_bundles:
livvkit.numerics_model_config = os.path.join(
livvkit.bundle_dir, livvkit.model_bundle, "numerics.json")
livvkit.numerics_model_module = importlib.import_module(
".".join(["livvkit.bundles", livvkit.model_bundle, "numerics"]))
livvkit.verification_model_config = os.path.join(
livvkit.bundle_dir, livvkit.model_bundle, "verification.json")
livvkit.verification_model_module = importlib.import_module(
".".join(["livvkit.bundles", livvkit.model_bundle, "verification"]))
livvkit.performance_model_config = os.path.join(
livvkit.bundle_dir, livvkit.model_bundle, "performance.json")
# NOTE: This isn't used right now...
# livvkit.performance_model_module = importlib.import_module(
# ".".join(["livvkit.bundles", livvkit.model_bundle, "performance"]))
else:
# TODO: Should implement some error checking here...
livvkit.verify = False
if options.validate is not None:
livvkit.validation_model_configs = options.validate
if not (livvkit.verify or livvkit.validate) and not options.serve:
print("")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" UH OH!")
print("----------------------------------------------------------")
print(" No verification or validation tests found/submitted!")
print("")
print(" Use either one or both of the --verify and")
print(" --validate options to run tests. For more ")
print(" information use the --help option, view the README")
print(" or check https://livvkit.github.io/Docs/")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("")
sys.exit(1)
return options | python | def init(options):
""" Initialize some defaults """
# Set matlplotlib's backend so LIVVkit can plot to files.
import matplotlib
matplotlib.use('agg')
livvkit.output_dir = os.path.abspath(options.out_dir)
livvkit.index_dir = livvkit.output_dir
livvkit.verify = True if options.verify is not None else False
livvkit.validate = True if options.validate is not None else False
livvkit.publish = options.publish
# Get a list of bundles that provide model specific implementations
available_bundles = [mod for imp, mod, ispkg in pkgutil.iter_modules(bundles.__path__)]
if options.verify is not None:
livvkit.model_dir = os.path.normpath(options.verify[0])
livvkit.bench_dir = os.path.normpath(options.verify[1])
if not os.path.isdir(livvkit.model_dir):
print("")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" UH OH!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" Your comparison directory does not exist; please check")
print(" the path:")
print("\n"+livvkit.model_dir+"\n\n")
sys.exit(1)
if not os.path.isdir(livvkit.bench_dir):
print("")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" UH OH!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" Your benchmark directory does not exist; please check")
print(" the path:")
print("\n"+livvkit.bench_dir+"\n\n")
sys.exit(1)
livvkit.model_bundle = os.path.basename(livvkit.model_dir)
livvkit.bench_bundle = os.path.basename(livvkit.bench_dir)
if livvkit.model_bundle in available_bundles:
livvkit.numerics_model_config = os.path.join(
livvkit.bundle_dir, livvkit.model_bundle, "numerics.json")
livvkit.numerics_model_module = importlib.import_module(
".".join(["livvkit.bundles", livvkit.model_bundle, "numerics"]))
livvkit.verification_model_config = os.path.join(
livvkit.bundle_dir, livvkit.model_bundle, "verification.json")
livvkit.verification_model_module = importlib.import_module(
".".join(["livvkit.bundles", livvkit.model_bundle, "verification"]))
livvkit.performance_model_config = os.path.join(
livvkit.bundle_dir, livvkit.model_bundle, "performance.json")
# NOTE: This isn't used right now...
# livvkit.performance_model_module = importlib.import_module(
# ".".join(["livvkit.bundles", livvkit.model_bundle, "performance"]))
else:
# TODO: Should implement some error checking here...
livvkit.verify = False
if options.validate is not None:
livvkit.validation_model_configs = options.validate
if not (livvkit.verify or livvkit.validate) and not options.serve:
print("")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(" UH OH!")
print("----------------------------------------------------------")
print(" No verification or validation tests found/submitted!")
print("")
print(" Use either one or both of the --verify and")
print(" --validate options to run tests. For more ")
print(" information use the --help option, view the README")
print(" or check https://livvkit.github.io/Docs/")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("")
sys.exit(1)
return options | [
"def",
"init",
"(",
"options",
")",
":",
"# Set matlplotlib's backend so LIVVkit can plot to files.",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"'agg'",
")",
"livvkit",
".",
"output_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"options",
".",
... | Initialize some defaults | [
"Initialize",
"some",
"defaults"
] | train | https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/options.py#L111-L191 |
PGower/PyCanvas | pycanvas/apis/group_categories.py | GroupCategoriesAPI.list_group_categories_for_context_accounts | def list_group_categories_for_context_accounts(self, account_id):
"""
List group categories for a context.
Returns a list of group categories in a context
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
self.logger.debug("GET /api/v1/accounts/{account_id}/group_categories with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/group_categories".format(**path), data=data, params=params, all_pages=True) | python | def list_group_categories_for_context_accounts(self, account_id):
"""
List group categories for a context.
Returns a list of group categories in a context
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
self.logger.debug("GET /api/v1/accounts/{account_id}/group_categories with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/group_categories".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_group_categories_for_context_accounts",
"(",
"self",
",",
"account_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"account_id\"",
"]",
"=",
"... | List group categories for a context.
Returns a list of group categories in a context | [
"List",
"group",
"categories",
"for",
"a",
"context",
".",
"Returns",
"a",
"list",
"of",
"group",
"categories",
"in",
"a",
"context"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/group_categories.py#L19-L34 |
PGower/PyCanvas | pycanvas/apis/group_categories.py | GroupCategoriesAPI.list_group_categories_for_context_courses | def list_group_categories_for_context_courses(self, course_id):
"""
List group categories for a context.
Returns a list of group categories in a context
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
self.logger.debug("GET /api/v1/courses/{course_id}/group_categories with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/group_categories".format(**path), data=data, params=params, all_pages=True) | python | def list_group_categories_for_context_courses(self, course_id):
"""
List group categories for a context.
Returns a list of group categories in a context
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
self.logger.debug("GET /api/v1/courses/{course_id}/group_categories with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/group_categories".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_group_categories_for_context_courses",
"(",
"self",
",",
"course_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"course_id\"",
"]",
"=",
"cour... | List group categories for a context.
Returns a list of group categories in a context | [
"List",
"group",
"categories",
"for",
"a",
"context",
".",
"Returns",
"a",
"list",
"of",
"group",
"categories",
"in",
"a",
"context"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/group_categories.py#L36-L51 |
PGower/PyCanvas | pycanvas/apis/group_categories.py | GroupCategoriesAPI.get_single_group_category | def get_single_group_category(self, group_category_id):
"""
Get a single group category.
Returns the data for a single group category, or a 401 if the caller doesn't have
the rights to see it.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
self.logger.debug("GET /api/v1/group_categories/{group_category_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/group_categories/{group_category_id}".format(**path), data=data, params=params, single_item=True) | python | def get_single_group_category(self, group_category_id):
"""
Get a single group category.
Returns the data for a single group category, or a 401 if the caller doesn't have
the rights to see it.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
self.logger.debug("GET /api/v1/group_categories/{group_category_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/group_categories/{group_category_id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"get_single_group_category",
"(",
"self",
",",
"group_category_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_category_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_category_id\"",
"]",
"=",... | Get a single group category.
Returns the data for a single group category, or a 401 if the caller doesn't have
the rights to see it. | [
"Get",
"a",
"single",
"group",
"category",
".",
"Returns",
"the",
"data",
"for",
"a",
"single",
"group",
"category",
"or",
"a",
"401",
"if",
"the",
"caller",
"doesn",
"t",
"have",
"the",
"rights",
"to",
"see",
"it",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/group_categories.py#L53-L69 |
PGower/PyCanvas | pycanvas/apis/group_categories.py | GroupCategoriesAPI.create_group_category_accounts | def create_group_category_accounts(self, name, account_id, auto_leader=None, create_group_count=None, group_limit=None, self_signup=None, split_group_count=None):
"""
Create a Group Category.
Create a new group category
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - name
"""Name of the group category"""
data["name"] = name
# OPTIONAL - self_signup
"""Allow students to sign up for a group themselves (Course Only).
valid values are:
"enabled":: allows students to self sign up for any group in course
"restricted":: allows students to self sign up only for groups in the
same section null disallows self sign up"""
if self_signup is not None:
self._validate_enum(self_signup, ["enabled", "restricted"])
data["self_signup"] = self_signup
# OPTIONAL - auto_leader
"""Assigns group leaders automatically when generating and allocating students to groups
Valid values are:
"first":: the first student to be allocated to a group is the leader
"random":: a random student from all members is chosen as the leader"""
if auto_leader is not None:
self._validate_enum(auto_leader, ["first", "random"])
data["auto_leader"] = auto_leader
# OPTIONAL - group_limit
"""Limit the maximum number of users in each group (Course Only). Requires
self signup."""
if group_limit is not None:
data["group_limit"] = group_limit
# OPTIONAL - create_group_count
"""Create this number of groups (Course Only)."""
if create_group_count is not None:
data["create_group_count"] = create_group_count
# OPTIONAL - split_group_count
"""(Deprecated)
Create this number of groups, and evenly distribute students
among them. not allowed with "enable_self_signup". because
the group assignment happens synchronously, it's recommended
that you instead use the assign_unassigned_members endpoint.
(Course Only)"""
if split_group_count is not None:
data["split_group_count"] = split_group_count
self.logger.debug("POST /api/v1/accounts/{account_id}/group_categories with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/group_categories".format(**path), data=data, params=params, single_item=True) | python | def create_group_category_accounts(self, name, account_id, auto_leader=None, create_group_count=None, group_limit=None, self_signup=None, split_group_count=None):
"""
Create a Group Category.
Create a new group category
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - name
"""Name of the group category"""
data["name"] = name
# OPTIONAL - self_signup
"""Allow students to sign up for a group themselves (Course Only).
valid values are:
"enabled":: allows students to self sign up for any group in course
"restricted":: allows students to self sign up only for groups in the
same section null disallows self sign up"""
if self_signup is not None:
self._validate_enum(self_signup, ["enabled", "restricted"])
data["self_signup"] = self_signup
# OPTIONAL - auto_leader
"""Assigns group leaders automatically when generating and allocating students to groups
Valid values are:
"first":: the first student to be allocated to a group is the leader
"random":: a random student from all members is chosen as the leader"""
if auto_leader is not None:
self._validate_enum(auto_leader, ["first", "random"])
data["auto_leader"] = auto_leader
# OPTIONAL - group_limit
"""Limit the maximum number of users in each group (Course Only). Requires
self signup."""
if group_limit is not None:
data["group_limit"] = group_limit
# OPTIONAL - create_group_count
"""Create this number of groups (Course Only)."""
if create_group_count is not None:
data["create_group_count"] = create_group_count
# OPTIONAL - split_group_count
"""(Deprecated)
Create this number of groups, and evenly distribute students
among them. not allowed with "enable_self_signup". because
the group assignment happens synchronously, it's recommended
that you instead use the assign_unassigned_members endpoint.
(Course Only)"""
if split_group_count is not None:
data["split_group_count"] = split_group_count
self.logger.debug("POST /api/v1/accounts/{account_id}/group_categories with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/group_categories".format(**path), data=data, params=params, single_item=True) | [
"def",
"create_group_category_accounts",
"(",
"self",
",",
"name",
",",
"account_id",
",",
"auto_leader",
"=",
"None",
",",
"create_group_count",
"=",
"None",
",",
"group_limit",
"=",
"None",
",",
"self_signup",
"=",
"None",
",",
"split_group_count",
"=",
"None"... | Create a Group Category.
Create a new group category | [
"Create",
"a",
"Group",
"Category",
".",
"Create",
"a",
"new",
"group",
"category"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/group_categories.py#L71-L130 |
PGower/PyCanvas | pycanvas/apis/group_categories.py | GroupCategoriesAPI.delete_group_category | def delete_group_category(self, group_category_id):
"""
Delete a Group Category.
Deletes a group category and all groups under it. Protected group
categories can not be deleted, i.e. "communities" and "student_organized".
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
self.logger.debug("DELETE /api/v1/group_categories/{group_category_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/group_categories/{group_category_id}".format(**path), data=data, params=params, no_data=True) | python | def delete_group_category(self, group_category_id):
"""
Delete a Group Category.
Deletes a group category and all groups under it. Protected group
categories can not be deleted, i.e. "communities" and "student_organized".
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
self.logger.debug("DELETE /api/v1/group_categories/{group_category_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/group_categories/{group_category_id}".format(**path), data=data, params=params, no_data=True) | [
"def",
"delete_group_category",
"(",
"self",
",",
"group_category_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_category_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_category_id\"",
"]",
"=",
"... | Delete a Group Category.
Deletes a group category and all groups under it. Protected group
categories can not be deleted, i.e. "communities" and "student_organized". | [
"Delete",
"a",
"Group",
"Category",
".",
"Deletes",
"a",
"group",
"category",
"and",
"all",
"groups",
"under",
"it",
".",
"Protected",
"group",
"categories",
"can",
"not",
"be",
"deleted",
"i",
".",
"e",
".",
"communities",
"and",
"student_organized",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/group_categories.py#L255-L271 |
PGower/PyCanvas | pycanvas/apis/group_categories.py | GroupCategoriesAPI.list_groups_in_group_category | def list_groups_in_group_category(self, group_category_id):
"""
List groups in group category.
Returns a list of groups in a group category
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
self.logger.debug("GET /api/v1/group_categories/{group_category_id}/groups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/group_categories/{group_category_id}/groups".format(**path), data=data, params=params, all_pages=True) | python | def list_groups_in_group_category(self, group_category_id):
"""
List groups in group category.
Returns a list of groups in a group category
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
self.logger.debug("GET /api/v1/group_categories/{group_category_id}/groups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/group_categories/{group_category_id}/groups".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_groups_in_group_category",
"(",
"self",
",",
"group_category_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_category_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_category_id\"",
"]",
... | List groups in group category.
Returns a list of groups in a group category | [
"List",
"groups",
"in",
"group",
"category",
".",
"Returns",
"a",
"list",
"of",
"groups",
"in",
"a",
"group",
"category"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/group_categories.py#L273-L288 |
PGower/PyCanvas | pycanvas/apis/group_categories.py | GroupCategoriesAPI.list_users_in_group_category | def list_users_in_group_category(self, group_category_id, search_term=None, unassigned=None):
"""
List users in group category.
Returns a list of users in the group category.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
# OPTIONAL - search_term
"""The partial name or full ID of the users to match and return in the results
list. Must be at least 3 characters."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - unassigned
"""Set this value to true if you wish only to search unassigned users in the
group category."""
if unassigned is not None:
params["unassigned"] = unassigned
self.logger.debug("GET /api/v1/group_categories/{group_category_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/group_categories/{group_category_id}/users".format(**path), data=data, params=params, all_pages=True) | python | def list_users_in_group_category(self, group_category_id, search_term=None, unassigned=None):
"""
List users in group category.
Returns a list of users in the group category.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
# OPTIONAL - search_term
"""The partial name or full ID of the users to match and return in the results
list. Must be at least 3 characters."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - unassigned
"""Set this value to true if you wish only to search unassigned users in the
group category."""
if unassigned is not None:
params["unassigned"] = unassigned
self.logger.debug("GET /api/v1/group_categories/{group_category_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/group_categories/{group_category_id}/users".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_users_in_group_category",
"(",
"self",
",",
"group_category_id",
",",
"search_term",
"=",
"None",
",",
"unassigned",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_category_... | List users in group category.
Returns a list of users in the group category. | [
"List",
"users",
"in",
"group",
"category",
".",
"Returns",
"a",
"list",
"of",
"users",
"in",
"the",
"group",
"category",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/group_categories.py#L290-L317 |
PGower/PyCanvas | pycanvas/apis/group_categories.py | GroupCategoriesAPI.assign_unassigned_members | def assign_unassigned_members(self, group_category_id, sync=None):
"""
Assign unassigned members.
Assign all unassigned members as evenly as possible among the existing
student groups.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
# OPTIONAL - sync
"""The assigning is done asynchronously by default. If you would like to
override this and have the assigning done synchronously, set this value
to true."""
if sync is not None:
data["sync"] = sync
self.logger.debug("POST /api/v1/group_categories/{group_category_id}/assign_unassigned_members with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/group_categories/{group_category_id}/assign_unassigned_members".format(**path), data=data, params=params, single_item=True) | python | def assign_unassigned_members(self, group_category_id, sync=None):
"""
Assign unassigned members.
Assign all unassigned members as evenly as possible among the existing
student groups.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_category_id
"""ID"""
path["group_category_id"] = group_category_id
# OPTIONAL - sync
"""The assigning is done asynchronously by default. If you would like to
override this and have the assigning done synchronously, set this value
to true."""
if sync is not None:
data["sync"] = sync
self.logger.debug("POST /api/v1/group_categories/{group_category_id}/assign_unassigned_members with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/group_categories/{group_category_id}/assign_unassigned_members".format(**path), data=data, params=params, single_item=True) | [
"def",
"assign_unassigned_members",
"(",
"self",
",",
"group_category_id",
",",
"sync",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_category_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"g... | Assign unassigned members.
Assign all unassigned members as evenly as possible among the existing
student groups. | [
"Assign",
"unassigned",
"members",
".",
"Assign",
"all",
"unassigned",
"members",
"as",
"evenly",
"as",
"possible",
"among",
"the",
"existing",
"student",
"groups",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/group_categories.py#L319-L342 |
ricardosasilva/pagseguro-python | pagseguro/api/v2/payment.py | Payment.set_client | def set_client(self, *args, **kwargs):
''' Se você possui informações cadastradas sobre o comprador você pode utilizar
este método para enviar estas informações para o PagSeguro. É uma boa prática pois
evita que seu cliente tenha que preencher estas informações novamente na página
do PagSeguro.
Args:
name (str): (opcional) Nome do cliente
email (str): (opcional) Email do cliente
phone_area_code (str): (opcional) Código de área do telefone do cliente. Um número com 2 digitos.
phone_number (str): (opcional) O número de telefone do cliente.
cpf: (str): (opcional) Número do cpf do comprador
born_date: (date): Data de nascimento no formato dd/MM/yyyy
Exemplo:
>>> from pagseguro import Payment
>>> from pagseguro import local_settings
>>> payment = Payment(email=local_settings.PAGSEGURO_ACCOUNT_EMAIL, token=local_settings.PAGSEGURO_TOKEN, sandbox=True)
>>> payment.set_client(name=u'Adam Yauch', phone_area_code=11)
'''
self.client = {}
for arg, value in kwargs.iteritems():
if value:
self.client[arg] = value
client_schema(self.client) | python | def set_client(self, *args, **kwargs):
''' Se você possui informações cadastradas sobre o comprador você pode utilizar
este método para enviar estas informações para o PagSeguro. É uma boa prática pois
evita que seu cliente tenha que preencher estas informações novamente na página
do PagSeguro.
Args:
name (str): (opcional) Nome do cliente
email (str): (opcional) Email do cliente
phone_area_code (str): (opcional) Código de área do telefone do cliente. Um número com 2 digitos.
phone_number (str): (opcional) O número de telefone do cliente.
cpf: (str): (opcional) Número do cpf do comprador
born_date: (date): Data de nascimento no formato dd/MM/yyyy
Exemplo:
>>> from pagseguro import Payment
>>> from pagseguro import local_settings
>>> payment = Payment(email=local_settings.PAGSEGURO_ACCOUNT_EMAIL, token=local_settings.PAGSEGURO_TOKEN, sandbox=True)
>>> payment.set_client(name=u'Adam Yauch', phone_area_code=11)
'''
self.client = {}
for arg, value in kwargs.iteritems():
if value:
self.client[arg] = value
client_schema(self.client) | [
"def",
"set_client",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
"=",
"{",
"}",
"for",
"arg",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"value",
":",
"self",
".",
"client",
... | Se você possui informações cadastradas sobre o comprador você pode utilizar
este método para enviar estas informações para o PagSeguro. É uma boa prática pois
evita que seu cliente tenha que preencher estas informações novamente na página
do PagSeguro.
Args:
name (str): (opcional) Nome do cliente
email (str): (opcional) Email do cliente
phone_area_code (str): (opcional) Código de área do telefone do cliente. Um número com 2 digitos.
phone_number (str): (opcional) O número de telefone do cliente.
cpf: (str): (opcional) Número do cpf do comprador
born_date: (date): Data de nascimento no formato dd/MM/yyyy
Exemplo:
>>> from pagseguro import Payment
>>> from pagseguro import local_settings
>>> payment = Payment(email=local_settings.PAGSEGURO_ACCOUNT_EMAIL, token=local_settings.PAGSEGURO_TOKEN, sandbox=True)
>>> payment.set_client(name=u'Adam Yauch', phone_area_code=11) | [
"Se",
"você",
"possui",
"informações",
"cadastradas",
"sobre",
"o",
"comprador",
"você",
"pode",
"utilizar",
"este",
"método",
"para",
"enviar",
"estas",
"informações",
"para",
"o",
"PagSeguro",
".",
"É",
"uma",
"boa",
"prática",
"pois",
"evita",
"que",
"seu",... | train | https://github.com/ricardosasilva/pagseguro-python/blob/8e39d1b0585684c460b86073d1fb3f33112b5b3d/pagseguro/api/v2/payment.py#L104-L128 |
ricardosasilva/pagseguro-python | pagseguro/api/v2/payment.py | Payment.set_shipping | def set_shipping(self, *args, **kwargs):
''' Define os atributos do frete
Args:
type (int): (opcional) Tipo de frete. Os valores válidos são: 1 para 'Encomenda normal (PAC).',
2 para 'SEDEX' e 3 para 'Tipo de frete não especificado.'
cost (float): (opcional) Valor total do frete. Deve ser maior que 0.00 e menor ou igual a 9999999.00.
street (str): (opcional) Nome da rua do endereço de envio do produto
address_number: (opcional) Número do endereço de envio do produto.
complement: (opcional) Complemento (bloco, apartamento, etc.) do endereço de envio do produto.
district: (opcional) Bairro do endereço de envio do produto.
postal_code: (opcional) CEP do endereço de envio do produto.
city: (opcional) Cidade do endereço de envio do produto.
state: (opcional) Estado do endereço de envio do produto.
country: (opcional) País do endereço de envio do produto. Apenas o valor 'BRA' é aceito.
'''
self.shipping = {}
for arg, value in kwargs.iteritems():
self.shipping[arg] = value
shipping_schema(self.shipping) | python | def set_shipping(self, *args, **kwargs):
''' Define os atributos do frete
Args:
type (int): (opcional) Tipo de frete. Os valores válidos são: 1 para 'Encomenda normal (PAC).',
2 para 'SEDEX' e 3 para 'Tipo de frete não especificado.'
cost (float): (opcional) Valor total do frete. Deve ser maior que 0.00 e menor ou igual a 9999999.00.
street (str): (opcional) Nome da rua do endereço de envio do produto
address_number: (opcional) Número do endereço de envio do produto.
complement: (opcional) Complemento (bloco, apartamento, etc.) do endereço de envio do produto.
district: (opcional) Bairro do endereço de envio do produto.
postal_code: (opcional) CEP do endereço de envio do produto.
city: (opcional) Cidade do endereço de envio do produto.
state: (opcional) Estado do endereço de envio do produto.
country: (opcional) País do endereço de envio do produto. Apenas o valor 'BRA' é aceito.
'''
self.shipping = {}
for arg, value in kwargs.iteritems():
self.shipping[arg] = value
shipping_schema(self.shipping) | [
"def",
"set_shipping",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"shipping",
"=",
"{",
"}",
"for",
"arg",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"shipping",
"[",
"arg",
"]"... | Define os atributos do frete
Args:
type (int): (opcional) Tipo de frete. Os valores válidos são: 1 para 'Encomenda normal (PAC).',
2 para 'SEDEX' e 3 para 'Tipo de frete não especificado.'
cost (float): (opcional) Valor total do frete. Deve ser maior que 0.00 e menor ou igual a 9999999.00.
street (str): (opcional) Nome da rua do endereço de envio do produto
address_number: (opcional) Número do endereço de envio do produto.
complement: (opcional) Complemento (bloco, apartamento, etc.) do endereço de envio do produto.
district: (opcional) Bairro do endereço de envio do produto.
postal_code: (opcional) CEP do endereço de envio do produto.
city: (opcional) Cidade do endereço de envio do produto.
state: (opcional) Estado do endereço de envio do produto.
country: (opcional) País do endereço de envio do produto. Apenas o valor 'BRA' é aceito. | [
"Define",
"os",
"atributos",
"do",
"frete"
] | train | https://github.com/ricardosasilva/pagseguro-python/blob/8e39d1b0585684c460b86073d1fb3f33112b5b3d/pagseguro/api/v2/payment.py#L130-L150 |
ricardosasilva/pagseguro-python | pagseguro/api/v2/payment.py | Payment.request | def request(self):
'''
Faz a requisição de pagamento ao servidor do PagSeguro.
'''
# try:
payment_v2_schema(self)
# except MultipleInvalid as e:
# raise PagSeguroPaymentValidationException(u'Erro na validação dos dados: %s' % e.msg)
params = self._build_params()
# logger.debug(u'Parametros da requisicao ao PagSeguro: %s' % params)
req = requests.post(
self.PAGSEGURO_API_URL,
params=params,
headers={
'Content-Type':
'application/x-www-form-urlencoded; charset=ISO-8859-1'
}
)
if req.status_code == 200:
self.params = params
self.response = self._process_response_xml(req.text)
else:
raise PagSeguroApiException(
u'Erro ao fazer request para a API:' +
' HTTP Status=%s - Response: %s' % (req.status_code, req.text))
return | python | def request(self):
'''
Faz a requisição de pagamento ao servidor do PagSeguro.
'''
# try:
payment_v2_schema(self)
# except MultipleInvalid as e:
# raise PagSeguroPaymentValidationException(u'Erro na validação dos dados: %s' % e.msg)
params = self._build_params()
# logger.debug(u'Parametros da requisicao ao PagSeguro: %s' % params)
req = requests.post(
self.PAGSEGURO_API_URL,
params=params,
headers={
'Content-Type':
'application/x-www-form-urlencoded; charset=ISO-8859-1'
}
)
if req.status_code == 200:
self.params = params
self.response = self._process_response_xml(req.text)
else:
raise PagSeguroApiException(
u'Erro ao fazer request para a API:' +
' HTTP Status=%s - Response: %s' % (req.status_code, req.text))
return | [
"def",
"request",
"(",
"self",
")",
":",
"# try:",
"payment_v2_schema",
"(",
"self",
")",
"# except MultipleInvalid as e:",
"# raise PagSeguroPaymentValidationException(u'Erro na validação dos dados: %s' % e.msg)",
"params",
"=",
"self",
".",
"_build_params... | Faz a requisição de pagamento ao servidor do PagSeguro. | [
"Faz",
"a",
"requisição",
"de",
"pagamento",
"ao",
"servidor",
"do",
"PagSeguro",
"."
] | train | https://github.com/ricardosasilva/pagseguro-python/blob/8e39d1b0585684c460b86073d1fb3f33112b5b3d/pagseguro/api/v2/payment.py#L152-L177 |
ricardosasilva/pagseguro-python | pagseguro/api/v2/payment.py | Payment._build_params | def _build_params(self):
''' método que constrói o dicionario com os parametros que serão usados
na requisição HTTP Post ao PagSeguro
Returns:
Um dicionário com os parametros definidos no objeto Payment.
'''
params = {}
params['email'] = self.email
params['token'] = self.token
params['currency'] = self.currency
# Atributos opcionais
if self.receiver_email:
params['receiver_email'] = self.receiver_email
if self.reference:
params['reference'] = self.reference
if self.extra_amount:
params['extra_amount'] = self.extra_amount
if self.redirect_url:
params['redirect_url'] = self.redirect_url
if self.notification_url:
params['notification_url'] = self.notification_url
if self.max_uses:
params['max_uses'] = self.max_uses
if self.max_age:
params['max_age'] = self.max_age
#TODO: Incluir metadata aqui
# Itens
for index, item in enumerate(self.items, start=1):
params['itemId%d' % index] = item['item_id']
params['itemDescription%d' % index] = item['description']
params['itemAmount%d' % index] = '%.2f' % item['amount']
params['itemQuantity%s' % index] = item['quantity']
if item.get('shipping_cost'):
params['itemShippingCost%d' % index] = item['shipping_cost']
if item.get('weight'):
params['itemWeight%d' % index] = item['weight']
# Sender
if self.client.get('email'):
params['senderEmail'] = self.client.get('email')
if self.client.get('name'):
params['senderName'] = ' '.join(self.client.get('name').split())
if self.client.get('phone_area_code'):
params['senderAreaCode'] = self.client.get('phone_area_code')
if self.client.get('phone_number'):
params['senderPhone'] = self.client.get('phone_number')
if self.client.get('cpf'):
params['senderCPF'] = self.client.get('cpf')
if self.client.get('sender_born_date'):
params['senderBornDate'] = self.client.get('sender_born_date')
# Shipping
if self.shipping.get('type'):
params['shippingType'] = self.shipping.get('type')
if self.shipping.get('cost'):
params['shippingCost'] = '%.2f' % self.shipping.get('cost')
if self.shipping.get('country'):
params['shippingAddressCountry'] = self.shipping.get('country')
if self.shipping.get('state'):
params['shippingAddressState'] = self.shipping.get('state')
if self.shipping.get('city'):
params['shippingAddressCity'] = self.shipping.get('city')
if self.shipping.get('postal_code'):
params['shippingAddressPostalCode'] = self.shipping.get('postal_code')
if self.shipping.get('district'):
params['shippingAddressDistrict'] = self.shipping.get('district')
if self.shipping.get('street'):
params['shippingAddressStreet'] = self.shipping.get('street')
if self.shipping.get('number'):
params['shippingAddressNumber'] = self.shipping.get('number')
if self.shipping.get('complement'):
params['shippingAddressComplement'] = self.shipping.get('complement')
return params | python | def _build_params(self):
''' método que constrói o dicionario com os parametros que serão usados
na requisição HTTP Post ao PagSeguro
Returns:
Um dicionário com os parametros definidos no objeto Payment.
'''
params = {}
params['email'] = self.email
params['token'] = self.token
params['currency'] = self.currency
# Atributos opcionais
if self.receiver_email:
params['receiver_email'] = self.receiver_email
if self.reference:
params['reference'] = self.reference
if self.extra_amount:
params['extra_amount'] = self.extra_amount
if self.redirect_url:
params['redirect_url'] = self.redirect_url
if self.notification_url:
params['notification_url'] = self.notification_url
if self.max_uses:
params['max_uses'] = self.max_uses
if self.max_age:
params['max_age'] = self.max_age
#TODO: Incluir metadata aqui
# Itens
for index, item in enumerate(self.items, start=1):
params['itemId%d' % index] = item['item_id']
params['itemDescription%d' % index] = item['description']
params['itemAmount%d' % index] = '%.2f' % item['amount']
params['itemQuantity%s' % index] = item['quantity']
if item.get('shipping_cost'):
params['itemShippingCost%d' % index] = item['shipping_cost']
if item.get('weight'):
params['itemWeight%d' % index] = item['weight']
# Sender
if self.client.get('email'):
params['senderEmail'] = self.client.get('email')
if self.client.get('name'):
params['senderName'] = ' '.join(self.client.get('name').split())
if self.client.get('phone_area_code'):
params['senderAreaCode'] = self.client.get('phone_area_code')
if self.client.get('phone_number'):
params['senderPhone'] = self.client.get('phone_number')
if self.client.get('cpf'):
params['senderCPF'] = self.client.get('cpf')
if self.client.get('sender_born_date'):
params['senderBornDate'] = self.client.get('sender_born_date')
# Shipping
if self.shipping.get('type'):
params['shippingType'] = self.shipping.get('type')
if self.shipping.get('cost'):
params['shippingCost'] = '%.2f' % self.shipping.get('cost')
if self.shipping.get('country'):
params['shippingAddressCountry'] = self.shipping.get('country')
if self.shipping.get('state'):
params['shippingAddressState'] = self.shipping.get('state')
if self.shipping.get('city'):
params['shippingAddressCity'] = self.shipping.get('city')
if self.shipping.get('postal_code'):
params['shippingAddressPostalCode'] = self.shipping.get('postal_code')
if self.shipping.get('district'):
params['shippingAddressDistrict'] = self.shipping.get('district')
if self.shipping.get('street'):
params['shippingAddressStreet'] = self.shipping.get('street')
if self.shipping.get('number'):
params['shippingAddressNumber'] = self.shipping.get('number')
if self.shipping.get('complement'):
params['shippingAddressComplement'] = self.shipping.get('complement')
return params | [
"def",
"_build_params",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"'email'",
"]",
"=",
"self",
".",
"email",
"params",
"[",
"'token'",
"]",
"=",
"self",
".",
"token",
"params",
"[",
"'currency'",
"]",
"=",
"self",
".",
"currency"... | método que constrói o dicionario com os parametros que serão usados
na requisição HTTP Post ao PagSeguro
Returns:
Um dicionário com os parametros definidos no objeto Payment. | [
"método",
"que",
"constrói",
"o",
"dicionario",
"com",
"os",
"parametros",
"que",
"serão",
"usados",
"na",
"requisição",
"HTTP",
"Post",
"ao",
"PagSeguro",
"Returns",
":",
"Um",
"dicionário",
"com",
"os",
"parametros",
"definidos",
"no",
"objeto",
"Payment",
"... | train | https://github.com/ricardosasilva/pagseguro-python/blob/8e39d1b0585684c460b86073d1fb3f33112b5b3d/pagseguro/api/v2/payment.py#L179-L256 |
ricardosasilva/pagseguro-python | pagseguro/api/v2/payment.py | Payment._process_response_xml | def _process_response_xml(self, response_xml):
'''
Processa o xml de resposta e caso não existam erros retorna um
dicionario com o codigo e data.
:return: dictionary
'''
result = {}
xml = ElementTree.fromstring(response_xml)
if xml.tag == 'errors':
logger.error(
u'Erro no pedido de pagamento ao PagSeguro.' +
' O xml de resposta foi: %s' % response_xml)
errors_message = u'Ocorreu algum problema com os dados do pagamento: '
for error in xml.findall('error'):
error_code = error.find('code').text
error_message = error.find('message').text
errors_message += u'\n (code=%s) %s' % (error_code,
error_message)
raise PagSeguroPaymentException(errors_message)
if xml.tag == 'checkout':
result['code'] = xml.find('code').text
try:
xml_date = xml.find('date').text
result['date'] = dateutil.parser.parse(xml_date)
except:
logger.exception(u'O campo date não foi encontrado ou é invalido')
result['date'] = None
else:
raise PagSeguroPaymentException(
u'Erro ao processar resposta do pagamento: tag "checkout" nao encontrada no xml de resposta')
return result | python | def _process_response_xml(self, response_xml):
'''
Processa o xml de resposta e caso não existam erros retorna um
dicionario com o codigo e data.
:return: dictionary
'''
result = {}
xml = ElementTree.fromstring(response_xml)
if xml.tag == 'errors':
logger.error(
u'Erro no pedido de pagamento ao PagSeguro.' +
' O xml de resposta foi: %s' % response_xml)
errors_message = u'Ocorreu algum problema com os dados do pagamento: '
for error in xml.findall('error'):
error_code = error.find('code').text
error_message = error.find('message').text
errors_message += u'\n (code=%s) %s' % (error_code,
error_message)
raise PagSeguroPaymentException(errors_message)
if xml.tag == 'checkout':
result['code'] = xml.find('code').text
try:
xml_date = xml.find('date').text
result['date'] = dateutil.parser.parse(xml_date)
except:
logger.exception(u'O campo date não foi encontrado ou é invalido')
result['date'] = None
else:
raise PagSeguroPaymentException(
u'Erro ao processar resposta do pagamento: tag "checkout" nao encontrada no xml de resposta')
return result | [
"def",
"_process_response_xml",
"(",
"self",
",",
"response_xml",
")",
":",
"result",
"=",
"{",
"}",
"xml",
"=",
"ElementTree",
".",
"fromstring",
"(",
"response_xml",
")",
"if",
"xml",
".",
"tag",
"==",
"'errors'",
":",
"logger",
".",
"error",
"(",
"u'E... | Processa o xml de resposta e caso não existam erros retorna um
dicionario com o codigo e data.
:return: dictionary | [
"Processa",
"o",
"xml",
"de",
"resposta",
"e",
"caso",
"não",
"existam",
"erros",
"retorna",
"um",
"dicionario",
"com",
"o",
"codigo",
"e",
"data",
"."
] | train | https://github.com/ricardosasilva/pagseguro-python/blob/8e39d1b0585684c460b86073d1fb3f33112b5b3d/pagseguro/api/v2/payment.py#L258-L291 |
vint21h/django-opensearch | opensearch/views.py | opensearch | def opensearch(request):
"""
Return opensearch.xml.
"""
contact_email = settings.CONTACT_EMAIL
short_name = settings.SHORT_NAME
description = settings.DESCRIPTION
favicon_width = settings.FAVICON_WIDTH
favicon_height = settings.FAVICON_HEIGHT
favicon_type = settings.FAVICON_TYPE
favicon_file = settings.FAVICON_FILE
url = "{url}?{querystring}{{searchTerms}}".format(**{
"url": request.build_absolute_uri(reverse(settings.SEARCH_URL)),
"querystring": settings.SEARCH_QUERYSTRING,
})
input_encoding = settings.INPUT_ENCODING.upper()
return render_to_response("opensearch/opensearch.xml", context=locals(), content_type="application/opensearchdescription+xml") | python | def opensearch(request):
"""
Return opensearch.xml.
"""
contact_email = settings.CONTACT_EMAIL
short_name = settings.SHORT_NAME
description = settings.DESCRIPTION
favicon_width = settings.FAVICON_WIDTH
favicon_height = settings.FAVICON_HEIGHT
favicon_type = settings.FAVICON_TYPE
favicon_file = settings.FAVICON_FILE
url = "{url}?{querystring}{{searchTerms}}".format(**{
"url": request.build_absolute_uri(reverse(settings.SEARCH_URL)),
"querystring": settings.SEARCH_QUERYSTRING,
})
input_encoding = settings.INPUT_ENCODING.upper()
return render_to_response("opensearch/opensearch.xml", context=locals(), content_type="application/opensearchdescription+xml") | [
"def",
"opensearch",
"(",
"request",
")",
":",
"contact_email",
"=",
"settings",
".",
"CONTACT_EMAIL",
"short_name",
"=",
"settings",
".",
"SHORT_NAME",
"description",
"=",
"settings",
".",
"DESCRIPTION",
"favicon_width",
"=",
"settings",
".",
"FAVICON_WIDTH",
"fa... | Return opensearch.xml. | [
"Return",
"opensearch",
".",
"xml",
"."
] | train | https://github.com/vint21h/django-opensearch/blob/4da3fa80b36f29e4ce350b3d689cda577b35421d/opensearch/views.py#L23-L41 |
Sanji-IO/sanji | sanji/model_initiator.py | ModelInitiator.db_manager | def db_manager(self):
"""
" Do series of DB operations.
"""
rc_create = self.create_db() # for first create
try:
self.load_db() # load existing/factory
except Exception as e:
_logger.debug("*** %s" % str(e))
try:
self.recover_db(self.backup_json_db_path)
except Exception:
pass
else:
if rc_create is True:
self.db_status = "factory"
else:
self.db_status = "existing"
return True
try:
self.load_db() # load backup
except Exception as b:
_logger.debug("*** %s" % str(b))
self.recover_db(self.factory_json_db_path)
self.load_db() # load factory
self.db_status = "factory"
else:
self.db_status = "backup"
finally:
return True | python | def db_manager(self):
"""
" Do series of DB operations.
"""
rc_create = self.create_db() # for first create
try:
self.load_db() # load existing/factory
except Exception as e:
_logger.debug("*** %s" % str(e))
try:
self.recover_db(self.backup_json_db_path)
except Exception:
pass
else:
if rc_create is True:
self.db_status = "factory"
else:
self.db_status = "existing"
return True
try:
self.load_db() # load backup
except Exception as b:
_logger.debug("*** %s" % str(b))
self.recover_db(self.factory_json_db_path)
self.load_db() # load factory
self.db_status = "factory"
else:
self.db_status = "backup"
finally:
return True | [
"def",
"db_manager",
"(",
"self",
")",
":",
"rc_create",
"=",
"self",
".",
"create_db",
"(",
")",
"# for first create",
"try",
":",
"self",
".",
"load_db",
"(",
")",
"# load existing/factory",
"except",
"Exception",
"as",
"e",
":",
"_logger",
".",
"debug",
... | " Do series of DB operations. | [
"Do",
"series",
"of",
"DB",
"operations",
"."
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model_initiator.py#L47-L77 |
Sanji-IO/sanji | sanji/model_initiator.py | ModelInitiator.create_db | def create_db(self):
"""
" Create a db file for model if there is no db.
" User need to prepare thier own xxx.json.factory.
"""
if self.db_type != "json":
raise RuntimeError("db_type only supports json now")
if os.path.exists(self.json_db_path):
return False
if os.path.exists(self.factory_json_db_path):
with self.db_mutex:
shutil.copy2(
self.factory_json_db_path, self.json_db_path)
return True
_logger.debug(
"*** NO such file: %s" % self.factory_json_db_path)
raise RuntimeError("No *.json.factory file") | python | def create_db(self):
"""
" Create a db file for model if there is no db.
" User need to prepare thier own xxx.json.factory.
"""
if self.db_type != "json":
raise RuntimeError("db_type only supports json now")
if os.path.exists(self.json_db_path):
return False
if os.path.exists(self.factory_json_db_path):
with self.db_mutex:
shutil.copy2(
self.factory_json_db_path, self.json_db_path)
return True
_logger.debug(
"*** NO such file: %s" % self.factory_json_db_path)
raise RuntimeError("No *.json.factory file") | [
"def",
"create_db",
"(",
"self",
")",
":",
"if",
"self",
".",
"db_type",
"!=",
"\"json\"",
":",
"raise",
"RuntimeError",
"(",
"\"db_type only supports json now\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"json_db_path",
")",
":",
"re... | " Create a db file for model if there is no db.
" User need to prepare thier own xxx.json.factory. | [
"Create",
"a",
"db",
"file",
"for",
"model",
"if",
"there",
"is",
"no",
"db",
".",
"User",
"need",
"to",
"prepare",
"thier",
"own",
"xxx",
".",
"json",
".",
"factory",
"."
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model_initiator.py#L79-L98 |
Sanji-IO/sanji | sanji/model_initiator.py | ModelInitiator.recover_db | def recover_db(self, src_file):
"""
" Recover DB from xxxxx.backup.json or xxxxx.json.factory to xxxxx.json
" [src_file]: copy from src_file to xxxxx.json
"""
with self.db_mutex:
try:
shutil.copy2(src_file, self.json_db_path)
except IOError as e:
_logger.debug("*** NO: %s file." % src_file)
raise e | python | def recover_db(self, src_file):
"""
" Recover DB from xxxxx.backup.json or xxxxx.json.factory to xxxxx.json
" [src_file]: copy from src_file to xxxxx.json
"""
with self.db_mutex:
try:
shutil.copy2(src_file, self.json_db_path)
except IOError as e:
_logger.debug("*** NO: %s file." % src_file)
raise e | [
"def",
"recover_db",
"(",
"self",
",",
"src_file",
")",
":",
"with",
"self",
".",
"db_mutex",
":",
"try",
":",
"shutil",
".",
"copy2",
"(",
"src_file",
",",
"self",
".",
"json_db_path",
")",
"except",
"IOError",
"as",
"e",
":",
"_logger",
".",
"debug",... | " Recover DB from xxxxx.backup.json or xxxxx.json.factory to xxxxx.json
" [src_file]: copy from src_file to xxxxx.json | [
"Recover",
"DB",
"from",
"xxxxx",
".",
"backup",
".",
"json",
"or",
"xxxxx",
".",
"json",
".",
"factory",
"to",
"xxxxx",
".",
"json",
"[",
"src_file",
"]",
":",
"copy",
"from",
"src_file",
"to",
"xxxxx",
".",
"json"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model_initiator.py#L100-L110 |
Sanji-IO/sanji | sanji/model_initiator.py | ModelInitiator.backup_db | def backup_db(self):
"""
" Generate a xxxxx.backup.json.
"""
with self.db_mutex:
if os.path.exists(self.json_db_path):
try:
shutil.copy2(self.json_db_path, self.backup_json_db_path)
except (IOError, OSError):
_logger.debug("*** No file to copy.") | python | def backup_db(self):
"""
" Generate a xxxxx.backup.json.
"""
with self.db_mutex:
if os.path.exists(self.json_db_path):
try:
shutil.copy2(self.json_db_path, self.backup_json_db_path)
except (IOError, OSError):
_logger.debug("*** No file to copy.") | [
"def",
"backup_db",
"(",
"self",
")",
":",
"with",
"self",
".",
"db_mutex",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"json_db_path",
")",
":",
"try",
":",
"shutil",
".",
"copy2",
"(",
"self",
".",
"json_db_path",
",",
"self",
... | " Generate a xxxxx.backup.json. | [
"Generate",
"a",
"xxxxx",
".",
"backup",
".",
"json",
"."
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model_initiator.py#L112-L121 |
Sanji-IO/sanji | sanji/model_initiator.py | ModelInitiator.load_db | def load_db(self):
"""
" Load json db as a dictionary.
"""
try:
with open(self.json_db_path) as fp:
self.db = json.load(fp)
except Exception as e:
_logger.debug("*** Open JSON DB error.")
raise e | python | def load_db(self):
"""
" Load json db as a dictionary.
"""
try:
with open(self.json_db_path) as fp:
self.db = json.load(fp)
except Exception as e:
_logger.debug("*** Open JSON DB error.")
raise e | [
"def",
"load_db",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"json_db_path",
")",
"as",
"fp",
":",
"self",
".",
"db",
"=",
"json",
".",
"load",
"(",
"fp",
")",
"except",
"Exception",
"as",
"e",
":",
"_logger",
".",
"debu... | " Load json db as a dictionary. | [
"Load",
"json",
"db",
"as",
"a",
"dictionary",
"."
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model_initiator.py#L123-L132 |
Sanji-IO/sanji | sanji/model_initiator.py | ModelInitiator.save_db | def save_db(self):
"""
" Save json db to file system.
"""
with self.db_mutex:
if not isinstance(self.db, dict) and not isinstance(self.db, list):
return False
try:
with open(self.json_db_path, "w") as fp:
json.dump(self.db, fp, indent=4)
except Exception as e:
# disk full or something.
_logger.debug("*** Write JSON DB to file error.")
raise e
else:
self.sync()
return True | python | def save_db(self):
"""
" Save json db to file system.
"""
with self.db_mutex:
if not isinstance(self.db, dict) and not isinstance(self.db, list):
return False
try:
with open(self.json_db_path, "w") as fp:
json.dump(self.db, fp, indent=4)
except Exception as e:
# disk full or something.
_logger.debug("*** Write JSON DB to file error.")
raise e
else:
self.sync()
return True | [
"def",
"save_db",
"(",
"self",
")",
":",
"with",
"self",
".",
"db_mutex",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"db",
",",
"dict",
")",
"and",
"not",
"isinstance",
"(",
"self",
".",
"db",
",",
"list",
")",
":",
"return",
"False",
"try",... | " Save json db to file system. | [
"Save",
"json",
"db",
"to",
"file",
"system",
"."
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model_initiator.py#L134-L151 |
shmir/PyIxNetwork | ixnetwork/ixn_port.py | IxnPort.reserve | def reserve(self, location=None, force=False, wait_for_up=True, timeout=80):
""" Reserve port and optionally wait for port to come up.
:param location: port location as 'ip/module/port'. If None, the location will be taken from the configuration.
:param force: whether to revoke existing reservation (True) or not (False).
:param wait_for_up: True - wait for port to come up, False - return immediately.
:param timeout: how long (seconds) to wait for port to come up.
"""
if not location or is_local_host(location):
return
hostname, card, port = location.split('/')
chassis = self.root.hw.get_chassis(hostname)
# todo - test if port owned by me.
if force:
chassis.get_card(int(card)).get_port(int(port)).release()
try:
phy_port = chassis.get_card(int(card)).get_port(int(port))
except KeyError as _:
raise TgnError('Physical port {} unreachable'.format(location))
self.set_attributes(commit=True, connectedTo=phy_port.ref)
while self.get_attribute('connectedTo') == '::ixNet::OBJ-null':
time.sleep(1)
if wait_for_up:
self.wait_for_up(timeout) | python | def reserve(self, location=None, force=False, wait_for_up=True, timeout=80):
""" Reserve port and optionally wait for port to come up.
:param location: port location as 'ip/module/port'. If None, the location will be taken from the configuration.
:param force: whether to revoke existing reservation (True) or not (False).
:param wait_for_up: True - wait for port to come up, False - return immediately.
:param timeout: how long (seconds) to wait for port to come up.
"""
if not location or is_local_host(location):
return
hostname, card, port = location.split('/')
chassis = self.root.hw.get_chassis(hostname)
# todo - test if port owned by me.
if force:
chassis.get_card(int(card)).get_port(int(port)).release()
try:
phy_port = chassis.get_card(int(card)).get_port(int(port))
except KeyError as _:
raise TgnError('Physical port {} unreachable'.format(location))
self.set_attributes(commit=True, connectedTo=phy_port.ref)
while self.get_attribute('connectedTo') == '::ixNet::OBJ-null':
time.sleep(1)
if wait_for_up:
self.wait_for_up(timeout) | [
"def",
"reserve",
"(",
"self",
",",
"location",
"=",
"None",
",",
"force",
"=",
"False",
",",
"wait_for_up",
"=",
"True",
",",
"timeout",
"=",
"80",
")",
":",
"if",
"not",
"location",
"or",
"is_local_host",
"(",
"location",
")",
":",
"return",
"hostnam... | Reserve port and optionally wait for port to come up.
:param location: port location as 'ip/module/port'. If None, the location will be taken from the configuration.
:param force: whether to revoke existing reservation (True) or not (False).
:param wait_for_up: True - wait for port to come up, False - return immediately.
:param timeout: how long (seconds) to wait for port to come up. | [
"Reserve",
"port",
"and",
"optionally",
"wait",
"for",
"port",
"to",
"come",
"up",
"."
] | train | https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_port.py#L21-L50 |
shmir/PyIxNetwork | ixnetwork/ixn_port.py | IxnPort.wait_for_up | def wait_for_up(self, timeout=40):
""" Wait until port is up and running, including all parameters (admin state, oper state, license etc.).
:param timeout: max time to wait for port up.
"""
self.wait_for_states(timeout, 'up')
connectionStatus = self.get_attribute('connectionStatus').strip()
if connectionStatus.split(':')[0] != self.get_attribute('assignedTo').split(':')[0]:
raise TgnError('Failed to reach up state, port connection status is {} after {} seconds'.
format(connectionStatus, timeout)) | python | def wait_for_up(self, timeout=40):
""" Wait until port is up and running, including all parameters (admin state, oper state, license etc.).
:param timeout: max time to wait for port up.
"""
self.wait_for_states(timeout, 'up')
connectionStatus = self.get_attribute('connectionStatus').strip()
if connectionStatus.split(':')[0] != self.get_attribute('assignedTo').split(':')[0]:
raise TgnError('Failed to reach up state, port connection status is {} after {} seconds'.
format(connectionStatus, timeout)) | [
"def",
"wait_for_up",
"(",
"self",
",",
"timeout",
"=",
"40",
")",
":",
"self",
".",
"wait_for_states",
"(",
"timeout",
",",
"'up'",
")",
"connectionStatus",
"=",
"self",
".",
"get_attribute",
"(",
"'connectionStatus'",
")",
".",
"strip",
"(",
")",
"if",
... | Wait until port is up and running, including all parameters (admin state, oper state, license etc.).
:param timeout: max time to wait for port up. | [
"Wait",
"until",
"port",
"is",
"up",
"and",
"running",
"including",
"all",
"parameters",
"(",
"admin",
"state",
"oper",
"state",
"license",
"etc",
".",
")",
"."
] | train | https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_port.py#L52-L62 |
shmir/PyIxNetwork | ixnetwork/ixn_port.py | IxnPort.wait_for_states | def wait_for_states(self, timeout=40, *states):
""" Wait until port reaches one of the requested states.
:param timeout: max time to wait for requested port states.
"""
state = self.get_attribute('state')
for _ in range(timeout):
if state in states:
return
time.sleep(1)
state = self.get_attribute('state')
raise TgnError('Failed to reach states {}, port state is {} after {} seconds'.format(states, state, timeout)) | python | def wait_for_states(self, timeout=40, *states):
""" Wait until port reaches one of the requested states.
:param timeout: max time to wait for requested port states.
"""
state = self.get_attribute('state')
for _ in range(timeout):
if state in states:
return
time.sleep(1)
state = self.get_attribute('state')
raise TgnError('Failed to reach states {}, port state is {} after {} seconds'.format(states, state, timeout)) | [
"def",
"wait_for_states",
"(",
"self",
",",
"timeout",
"=",
"40",
",",
"*",
"states",
")",
":",
"state",
"=",
"self",
".",
"get_attribute",
"(",
"'state'",
")",
"for",
"_",
"in",
"range",
"(",
"timeout",
")",
":",
"if",
"state",
"in",
"states",
":",
... | Wait until port reaches one of the requested states.
:param timeout: max time to wait for requested port states. | [
"Wait",
"until",
"port",
"reaches",
"one",
"of",
"the",
"requested",
"states",
"."
] | train | https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_port.py#L64-L76 |
fmalina/bng_latlon | latlon_to_bng.py | WGS84toOSGB36 | def WGS84toOSGB36(lat, lon):
""" Accept latitude and longitude as used in GPS.
Return OSGB grid coordinates: eastings and northings.
Usage:
>>> from latlon_to_bng import WGS84toOSGB36
>>> WGS84toOSGB36(51.4778, -0.0014)
(538890.1053365842, 177320.49650700082)
>>> WGS84toOSGB36(53.50713, -2.71766)
(352500.19520169357, 401400.01483428996)
"""
# First convert to radians
# These are on the wrong ellipsoid currently: GRS80. (Denoted by _1)
lat_1 = lat*pi/180
lon_1 = lon*pi/180
# Want to convert to the Airy 1830 ellipsoid, which has the following:
# The GSR80 semi-major and semi-minor axes used for WGS84(m)
a_1, b_1 = 6378137.000, 6356752.3141
e2_1 = 1 - (b_1*b_1)/(a_1*a_1) # The eccentricity of the GRS80 ellipsoid
nu_1 = a_1/sqrt(1-e2_1*sin(lat_1)**2)
# First convert to cartesian from spherical polar coordinates
H = 0 # Third spherical coord.
x_1 = (nu_1 + H)*cos(lat_1)*cos(lon_1)
y_1 = (nu_1 + H)*cos(lat_1)*sin(lon_1)
z_1 = ((1-e2_1)*nu_1 + H)*sin(lat_1)
# Perform Helmut transform (to go between GRS80 (_1) and Airy 1830 (_2))
s = 20.4894*10**-6 # The scale factor -1
# The translations along x,y,z axes respectively
tx, ty, tz = -446.448, 125.157, -542.060
# The rotations along x,y,z respectively, in seconds
rxs, rys, rzs = -0.1502, -0.2470, -0.8421
# In radians
rx, ry, rz = rxs*pi/(180*3600.), rys*pi/(180*3600.), rzs*pi/(180*3600.)
x_2 = tx + (1+s)*x_1 + (-rz)*y_1 + (ry)*z_1
y_2 = ty + (rz)*x_1 + (1+s)*y_1 + (-rx)*z_1
z_2 = tz + (-ry)*x_1 + (rx)*y_1 + (1+s)*z_1
# Back to spherical polar coordinates from cartesian
# Need some of the characteristics of the new ellipsoid
# The GSR80 semi-major and semi-minor axes used for WGS84(m)
a, b = 6377563.396, 6356256.909
e2 = 1 - (b*b)/(a*a) # The eccentricity of the Airy 1830 ellipsoid
p = sqrt(x_2**2 + y_2**2)
# Lat is obtained by an iterative proceedure:
lat = atan2(z_2, (p*(1-e2))) # Initial value
latold = 2*pi
while abs(lat - latold) > 10**-16:
lat, latold = latold, lat
nu = a/sqrt(1-e2*sin(latold)**2)
lat = atan2(z_2+e2*nu*sin(latold), p)
# Lon and height are then pretty easy
lon = atan2(y_2, x_2)
H = p/cos(lat) - nu
# E, N are the British national grid coordinates - eastings and northings
F0 = 0.9996012717 # scale factor on the central meridian
lat0 = 49*pi/180 # Latitude of true origin (radians)
lon0 = -2*pi/180 # Longtitude of true origin and central meridian (radians)
N0, E0 = -100000, 400000 # Northing & easting of true origin (m)
n = (a-b)/(a+b)
# meridional radius of curvature
rho = a*F0*(1-e2)*(1-e2*sin(lat)**2)**(-1.5)
eta2 = nu*F0/rho-1
M1 = (1 + n + (5/4)*n**2 + (5/4)*n**3) * (lat-lat0)
M2 = (3*n + 3*n**2 + (21/8)*n**3) * sin(lat-lat0) * cos(lat+lat0)
M3 = ((15/8)*n**2 + (15/8)*n**3) * sin(2*(lat-lat0)) * cos(2*(lat+lat0))
M4 = (35/24)*n**3 * sin(3*(lat-lat0)) * cos(3*(lat+lat0))
# meridional arc
M = b * F0 * (M1 - M2 + M3 - M4)
I = M + N0
II = nu*F0*sin(lat)*cos(lat)/2
III = nu*F0*sin(lat)*cos(lat)**3*(5 - tan(lat)**2 + 9*eta2)/24
IIIA = nu*F0*sin(lat)*cos(lat)**5*(61 - 58*tan(lat)**2 + tan(lat)**4)/720
IV = nu*F0*cos(lat)
V = nu*F0*cos(lat)**3*(nu/rho - tan(lat)**2)/6
VI = nu*F0*cos(lat)**5*(5 - 18*tan(lat)**2 + tan(lat)**4 + 14*eta2 - 58*eta2*tan(lat)**2)/120
N = I + II*(lon-lon0)**2 + III*(lon-lon0)**4 + IIIA*(lon-lon0)**6
E = E0 + IV*(lon-lon0) + V*(lon-lon0)**3 + VI*(lon-lon0)**5
# Job's a good'n.
return E, N | python | def WGS84toOSGB36(lat, lon):
""" Accept latitude and longitude as used in GPS.
Return OSGB grid coordinates: eastings and northings.
Usage:
>>> from latlon_to_bng import WGS84toOSGB36
>>> WGS84toOSGB36(51.4778, -0.0014)
(538890.1053365842, 177320.49650700082)
>>> WGS84toOSGB36(53.50713, -2.71766)
(352500.19520169357, 401400.01483428996)
"""
# First convert to radians
# These are on the wrong ellipsoid currently: GRS80. (Denoted by _1)
lat_1 = lat*pi/180
lon_1 = lon*pi/180
# Want to convert to the Airy 1830 ellipsoid, which has the following:
# The GSR80 semi-major and semi-minor axes used for WGS84(m)
a_1, b_1 = 6378137.000, 6356752.3141
e2_1 = 1 - (b_1*b_1)/(a_1*a_1) # The eccentricity of the GRS80 ellipsoid
nu_1 = a_1/sqrt(1-e2_1*sin(lat_1)**2)
# First convert to cartesian from spherical polar coordinates
H = 0 # Third spherical coord.
x_1 = (nu_1 + H)*cos(lat_1)*cos(lon_1)
y_1 = (nu_1 + H)*cos(lat_1)*sin(lon_1)
z_1 = ((1-e2_1)*nu_1 + H)*sin(lat_1)
# Perform Helmut transform (to go between GRS80 (_1) and Airy 1830 (_2))
s = 20.4894*10**-6 # The scale factor -1
# The translations along x,y,z axes respectively
tx, ty, tz = -446.448, 125.157, -542.060
# The rotations along x,y,z respectively, in seconds
rxs, rys, rzs = -0.1502, -0.2470, -0.8421
# In radians
rx, ry, rz = rxs*pi/(180*3600.), rys*pi/(180*3600.), rzs*pi/(180*3600.)
x_2 = tx + (1+s)*x_1 + (-rz)*y_1 + (ry)*z_1
y_2 = ty + (rz)*x_1 + (1+s)*y_1 + (-rx)*z_1
z_2 = tz + (-ry)*x_1 + (rx)*y_1 + (1+s)*z_1
# Back to spherical polar coordinates from cartesian
# Need some of the characteristics of the new ellipsoid
# The GSR80 semi-major and semi-minor axes used for WGS84(m)
a, b = 6377563.396, 6356256.909
e2 = 1 - (b*b)/(a*a) # The eccentricity of the Airy 1830 ellipsoid
p = sqrt(x_2**2 + y_2**2)
# Lat is obtained by an iterative proceedure:
lat = atan2(z_2, (p*(1-e2))) # Initial value
latold = 2*pi
while abs(lat - latold) > 10**-16:
lat, latold = latold, lat
nu = a/sqrt(1-e2*sin(latold)**2)
lat = atan2(z_2+e2*nu*sin(latold), p)
# Lon and height are then pretty easy
lon = atan2(y_2, x_2)
H = p/cos(lat) - nu
# E, N are the British national grid coordinates - eastings and northings
F0 = 0.9996012717 # scale factor on the central meridian
lat0 = 49*pi/180 # Latitude of true origin (radians)
lon0 = -2*pi/180 # Longtitude of true origin and central meridian (radians)
N0, E0 = -100000, 400000 # Northing & easting of true origin (m)
n = (a-b)/(a+b)
# meridional radius of curvature
rho = a*F0*(1-e2)*(1-e2*sin(lat)**2)**(-1.5)
eta2 = nu*F0/rho-1
M1 = (1 + n + (5/4)*n**2 + (5/4)*n**3) * (lat-lat0)
M2 = (3*n + 3*n**2 + (21/8)*n**3) * sin(lat-lat0) * cos(lat+lat0)
M3 = ((15/8)*n**2 + (15/8)*n**3) * sin(2*(lat-lat0)) * cos(2*(lat+lat0))
M4 = (35/24)*n**3 * sin(3*(lat-lat0)) * cos(3*(lat+lat0))
# meridional arc
M = b * F0 * (M1 - M2 + M3 - M4)
I = M + N0
II = nu*F0*sin(lat)*cos(lat)/2
III = nu*F0*sin(lat)*cos(lat)**3*(5 - tan(lat)**2 + 9*eta2)/24
IIIA = nu*F0*sin(lat)*cos(lat)**5*(61 - 58*tan(lat)**2 + tan(lat)**4)/720
IV = nu*F0*cos(lat)
V = nu*F0*cos(lat)**3*(nu/rho - tan(lat)**2)/6
VI = nu*F0*cos(lat)**5*(5 - 18*tan(lat)**2 + tan(lat)**4 + 14*eta2 - 58*eta2*tan(lat)**2)/120
N = I + II*(lon-lon0)**2 + III*(lon-lon0)**4 + IIIA*(lon-lon0)**6
E = E0 + IV*(lon-lon0) + V*(lon-lon0)**3 + VI*(lon-lon0)**5
# Job's a good'n.
return E, N | [
"def",
"WGS84toOSGB36",
"(",
"lat",
",",
"lon",
")",
":",
"# First convert to radians",
"# These are on the wrong ellipsoid currently: GRS80. (Denoted by _1)",
"lat_1",
"=",
"lat",
"*",
"pi",
"/",
"180",
"lon_1",
"=",
"lon",
"*",
"pi",
"/",
"180",
"# Want to convert t... | Accept latitude and longitude as used in GPS.
Return OSGB grid coordinates: eastings and northings.
Usage:
>>> from latlon_to_bng import WGS84toOSGB36
>>> WGS84toOSGB36(51.4778, -0.0014)
(538890.1053365842, 177320.49650700082)
>>> WGS84toOSGB36(53.50713, -2.71766)
(352500.19520169357, 401400.01483428996) | [
"Accept",
"latitude",
"and",
"longitude",
"as",
"used",
"in",
"GPS",
".",
"Return",
"OSGB",
"grid",
"coordinates",
":",
"eastings",
"and",
"northings",
"."
] | train | https://github.com/fmalina/bng_latlon/blob/b0251174b5248e8ade8098a31e754dcd0b157060/latlon_to_bng.py#L9-L99 |
jneight/django-xadmin-extras | xadmin_extras/wizard.py | FormWizardAdminView.get_form | def get_form(self, step=None, data=None, files=None):
"""Instanciate the form for the current step
FormAdminView from xadmin expects form to be at self.form_obj
"""
self.form_obj = super(FormWizardAdminView, self).get_form(
step=step, data=data, files=files)
return self.form_obj | python | def get_form(self, step=None, data=None, files=None):
"""Instanciate the form for the current step
FormAdminView from xadmin expects form to be at self.form_obj
"""
self.form_obj = super(FormWizardAdminView, self).get_form(
step=step, data=data, files=files)
return self.form_obj | [
"def",
"get_form",
"(",
"self",
",",
"step",
"=",
"None",
",",
"data",
"=",
"None",
",",
"files",
"=",
"None",
")",
":",
"self",
".",
"form_obj",
"=",
"super",
"(",
"FormWizardAdminView",
",",
"self",
")",
".",
"get_form",
"(",
"step",
"=",
"step",
... | Instanciate the form for the current step
FormAdminView from xadmin expects form to be at self.form_obj | [
"Instanciate",
"the",
"form",
"for",
"the",
"current",
"step"
] | train | https://github.com/jneight/django-xadmin-extras/blob/a7909a3a4c1620b550202d3f0aa357503cc15a29/xadmin_extras/wizard.py#L49-L57 |
jneight/django-xadmin-extras | xadmin_extras/wizard.py | FormWizardAdminView.render | def render(self, form=None, **kwargs):
"""Returns the ``HttpResponse`` with the context data"""
context = self.get_context(**kwargs)
return self.render_to_response(context) | python | def render(self, form=None, **kwargs):
"""Returns the ``HttpResponse`` with the context data"""
context = self.get_context(**kwargs)
return self.render_to_response(context) | [
"def",
"render",
"(",
"self",
",",
"form",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"self",
".",
"get_context",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"render_to_response",
"(",
"context",
")"
] | Returns the ``HttpResponse`` with the context data | [
"Returns",
"the",
"HttpResponse",
"with",
"the",
"context",
"data"
] | train | https://github.com/jneight/django-xadmin-extras/blob/a7909a3a4c1620b550202d3f0aa357503cc15a29/xadmin_extras/wizard.py#L73-L76 |
jneight/django-xadmin-extras | xadmin_extras/wizard.py | FormWizardAdminView.render_to_response | def render_to_response(self, context):
"""Add django-crispy form helper and draw the template
Returns the ``TemplateResponse`` ready to be displayed
"""
self.setup_forms()
return TemplateResponse(
self.request, self.form_template,
context, current_app=self.admin_site.name) | python | def render_to_response(self, context):
"""Add django-crispy form helper and draw the template
Returns the ``TemplateResponse`` ready to be displayed
"""
self.setup_forms()
return TemplateResponse(
self.request, self.form_template,
context, current_app=self.admin_site.name) | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"setup_forms",
"(",
")",
"return",
"TemplateResponse",
"(",
"self",
".",
"request",
",",
"self",
".",
"form_template",
",",
"context",
",",
"current_app",
"=",
"self",
".",
"a... | Add django-crispy form helper and draw the template
Returns the ``TemplateResponse`` ready to be displayed | [
"Add",
"django",
"-",
"crispy",
"form",
"helper",
"and",
"draw",
"the",
"template"
] | train | https://github.com/jneight/django-xadmin-extras/blob/a7909a3a4c1620b550202d3f0aa357503cc15a29/xadmin_extras/wizard.py#L78-L87 |
jneight/django-xadmin-extras | xadmin_extras/wizard.py | FormWizardAdminView.get_context | def get_context(self, **kwargs):
"""Use this method to built context data for the template
Mix django wizard context data with django-xadmin context
"""
context = self.get_context_data(form=self.form_obj, **kwargs)
context.update(super(FormAdminView, self).get_context())
return context | python | def get_context(self, **kwargs):
"""Use this method to built context data for the template
Mix django wizard context data with django-xadmin context
"""
context = self.get_context_data(form=self.form_obj, **kwargs)
context.update(super(FormAdminView, self).get_context())
return context | [
"def",
"get_context",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"form",
"=",
"self",
".",
"form_obj",
",",
"*",
"*",
"kwargs",
")",
"context",
".",
"update",
"(",
"super",
"(",
"FormAdminView"... | Use this method to built context data for the template
Mix django wizard context data with django-xadmin context | [
"Use",
"this",
"method",
"to",
"built",
"context",
"data",
"for",
"the",
"template"
] | train | https://github.com/jneight/django-xadmin-extras/blob/a7909a3a4c1620b550202d3f0aa357503cc15a29/xadmin_extras/wizard.py#L89-L97 |
karel-brinda/rnftools | rnftools/rnfformat/FqMerger.py | FqMerger.run | def run(self):
"""Run merging.
"""
print("", file=sys.stderr)
print("Going to merge/convert RNF-FASTQ files.", file=sys.stderr)
print("", file=sys.stderr)
print(" mode: ", self.mode, file=sys.stderr)
print(" input files: ", ", ".join(self.input_files_fn), file=sys.stderr)
print(" output files: ", ", ".join(self.output_files_fn), file=sys.stderr)
print("", file=sys.stderr)
while len(self.i_files_weighted) > 0:
file_id = self.rng.randint(0, len(self.i_files_weighted) - 1)
for i in range(READS_IN_GROUP * self._reads_in_tuple):
if self.i_files_weighted[file_id].closed:
del self.i_files_weighted[file_id]
break
ln1 = self.i_files_weighted[file_id].readline()
ln2 = self.i_files_weighted[file_id].readline()
ln3 = self.i_files_weighted[file_id].readline()
ln4 = self.i_files_weighted[file_id].readline()
if ln1 == "" or ln2 == "" or ln3 == "" or ln4 == "":
self.i_files_weighted[file_id].close()
del self.i_files_weighted[file_id]
break
assert ln1[0] == "@", ln1
assert ln3[0] == "+", ln3
self.output.save_read(ln1, ln2, ln3, ln4)
self.output.close() | python | def run(self):
"""Run merging.
"""
print("", file=sys.stderr)
print("Going to merge/convert RNF-FASTQ files.", file=sys.stderr)
print("", file=sys.stderr)
print(" mode: ", self.mode, file=sys.stderr)
print(" input files: ", ", ".join(self.input_files_fn), file=sys.stderr)
print(" output files: ", ", ".join(self.output_files_fn), file=sys.stderr)
print("", file=sys.stderr)
while len(self.i_files_weighted) > 0:
file_id = self.rng.randint(0, len(self.i_files_weighted) - 1)
for i in range(READS_IN_GROUP * self._reads_in_tuple):
if self.i_files_weighted[file_id].closed:
del self.i_files_weighted[file_id]
break
ln1 = self.i_files_weighted[file_id].readline()
ln2 = self.i_files_weighted[file_id].readline()
ln3 = self.i_files_weighted[file_id].readline()
ln4 = self.i_files_weighted[file_id].readline()
if ln1 == "" or ln2 == "" or ln3 == "" or ln4 == "":
self.i_files_weighted[file_id].close()
del self.i_files_weighted[file_id]
break
assert ln1[0] == "@", ln1
assert ln3[0] == "+", ln3
self.output.save_read(ln1, ln2, ln3, ln4)
self.output.close() | [
"def",
"run",
"(",
"self",
")",
":",
"print",
"(",
"\"\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"\"Going to merge/convert RNF-FASTQ files.\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"\"\"",
",",
"file",
"=",
"s... | Run merging. | [
"Run",
"merging",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/rnfformat/FqMerger.py#L88-L119 |
20c/vodka | vodka/config/__init__.py | is_config_container | def is_config_container(v):
"""
checks whether v is of type list,dict or Config
"""
cls = type(v)
return (
issubclass(cls, list) or
issubclass(cls, dict) or
issubclass(cls, Config)
) | python | def is_config_container(v):
"""
checks whether v is of type list,dict or Config
"""
cls = type(v)
return (
issubclass(cls, list) or
issubclass(cls, dict) or
issubclass(cls, Config)
) | [
"def",
"is_config_container",
"(",
"v",
")",
":",
"cls",
"=",
"type",
"(",
"v",
")",
"return",
"(",
"issubclass",
"(",
"cls",
",",
"list",
")",
"or",
"issubclass",
"(",
"cls",
",",
"dict",
")",
"or",
"issubclass",
"(",
"cls",
",",
"Config",
")",
")... | checks whether v is of type list,dict or Config | [
"checks",
"whether",
"v",
"is",
"of",
"type",
"list",
"dict",
"or",
"Config"
] | train | https://github.com/20c/vodka/blob/9615148ac6560298453704bb5246b35b66b3339c/vodka/config/__init__.py#L21-L32 |
20c/vodka | vodka/config/__init__.py | Handler.check | def check(cls, cfg, key_name, path, parent_cfg=None):
"""
Checks that the config values specified in key name is
sane according to config attributes defined as properties
on this class
"""
attr = getattr(cls, key_name, None)
if path != "":
attr_full_name = "%s.%s" % (path, key_name)
else:
attr_full_name = key_name
if not attr:
# attribute specified by key_name is unknown, warn
raise vodka.exceptions.ConfigErrorUnknown(attr_full_name)
if attr.deprecated:
vodka.log.warn("[config deprecated] %s is being deprecated in version %s" % (
attr_full_name,
attr.deprecated
))
# prepare data
for prepare in attr.prepare:
cfg[key_name] = prepare(cfg[key_name])
if hasattr(cls, "prepare_%s" % key_name):
prepare = getattr(cls, "prepare_%s" % key_name)
cfg[key_name] = prepare(cfg[key_name], config=cfg)
value = cfg.get(key_name)
if isinstance(attr.expected_type, types.FunctionType):
# expected type holds a validator function
p, reason = attr.expected_type(value)
if not p:
# validator did not pass
raise vodka.exceptions.ConfigErrorValue(
attr_full_name,
attr,
value,
reason=reason
)
elif attr.expected_type != type(value):
# attribute type mismatch
raise vodka.exceptions.ConfigErrorType(
attr_full_name,
attr
)
if attr.choices and value not in attr.choices:
# attribute value not valid according to
# available choices
raise vodka.exceptions.ConfigErrorValue(
attr_full_name,
attr,
value
)
if hasattr(cls, "validate_%s" % key_name):
# custom validator for this attribute was found
validator = getattr(cls, "validate_%s" % key_name)
valid, reason = validator(value)
if not valid:
# custom validator failed
raise vodka.exceptions.ConfigErrorValue(
attr_full_name,
attr,
value,
reason=reason
)
num_crit = 0
num_warn = 0
if is_config_container(value) and attr.handler:
if type(value) == dict or issubclass(type(value), Config):
keys = list(value.keys())
elif type(value) == list:
keys = list(range(0, len(value)))
else:
return
for k in keys:
if not is_config_container(value[k]):
continue
handler = attr.handler(k, value[k])
if issubclass(handler, Handler):
h = handler
else:
h = getattr(handler, "Configuration", None)
#h = getattr(attr.handler(k, value[k]), "Configuration", None)
if h:
if type(k) == int and type(value[k]) == dict and value[k].get("name"):
_path = "%s.%s" % (
attr_full_name, value[k].get("name"))
else:
_path = "%s.%s" % (attr_full_name, k)
_num_crit, _num_warn = h.validate(value[k], path=_path, nested=attr.nested, parent_cfg=cfg)
h.finalize(
value,
k,
value[k],
attr=attr,
attr_name=key_name,
parent_cfg=cfg
)
num_crit += _num_crit
num_warn += _num_warn
attr.finalize(cfg, key_name, value, num_crit=num_crit)
return (num_crit, num_warn) | python | def check(cls, cfg, key_name, path, parent_cfg=None):
"""
Checks that the config values specified in key name is
sane according to config attributes defined as properties
on this class
"""
attr = getattr(cls, key_name, None)
if path != "":
attr_full_name = "%s.%s" % (path, key_name)
else:
attr_full_name = key_name
if not attr:
# attribute specified by key_name is unknown, warn
raise vodka.exceptions.ConfigErrorUnknown(attr_full_name)
if attr.deprecated:
vodka.log.warn("[config deprecated] %s is being deprecated in version %s" % (
attr_full_name,
attr.deprecated
))
# prepare data
for prepare in attr.prepare:
cfg[key_name] = prepare(cfg[key_name])
if hasattr(cls, "prepare_%s" % key_name):
prepare = getattr(cls, "prepare_%s" % key_name)
cfg[key_name] = prepare(cfg[key_name], config=cfg)
value = cfg.get(key_name)
if isinstance(attr.expected_type, types.FunctionType):
# expected type holds a validator function
p, reason = attr.expected_type(value)
if not p:
# validator did not pass
raise vodka.exceptions.ConfigErrorValue(
attr_full_name,
attr,
value,
reason=reason
)
elif attr.expected_type != type(value):
# attribute type mismatch
raise vodka.exceptions.ConfigErrorType(
attr_full_name,
attr
)
if attr.choices and value not in attr.choices:
# attribute value not valid according to
# available choices
raise vodka.exceptions.ConfigErrorValue(
attr_full_name,
attr,
value
)
if hasattr(cls, "validate_%s" % key_name):
# custom validator for this attribute was found
validator = getattr(cls, "validate_%s" % key_name)
valid, reason = validator(value)
if not valid:
# custom validator failed
raise vodka.exceptions.ConfigErrorValue(
attr_full_name,
attr,
value,
reason=reason
)
num_crit = 0
num_warn = 0
if is_config_container(value) and attr.handler:
if type(value) == dict or issubclass(type(value), Config):
keys = list(value.keys())
elif type(value) == list:
keys = list(range(0, len(value)))
else:
return
for k in keys:
if not is_config_container(value[k]):
continue
handler = attr.handler(k, value[k])
if issubclass(handler, Handler):
h = handler
else:
h = getattr(handler, "Configuration", None)
#h = getattr(attr.handler(k, value[k]), "Configuration", None)
if h:
if type(k) == int and type(value[k]) == dict and value[k].get("name"):
_path = "%s.%s" % (
attr_full_name, value[k].get("name"))
else:
_path = "%s.%s" % (attr_full_name, k)
_num_crit, _num_warn = h.validate(value[k], path=_path, nested=attr.nested, parent_cfg=cfg)
h.finalize(
value,
k,
value[k],
attr=attr,
attr_name=key_name,
parent_cfg=cfg
)
num_crit += _num_crit
num_warn += _num_warn
attr.finalize(cfg, key_name, value, num_crit=num_crit)
return (num_crit, num_warn) | [
"def",
"check",
"(",
"cls",
",",
"cfg",
",",
"key_name",
",",
"path",
",",
"parent_cfg",
"=",
"None",
")",
":",
"attr",
"=",
"getattr",
"(",
"cls",
",",
"key_name",
",",
"None",
")",
"if",
"path",
"!=",
"\"\"",
":",
"attr_full_name",
"=",
"\"%s.%s\""... | Checks that the config values specified in key name is
sane according to config attributes defined as properties
on this class | [
"Checks",
"that",
"the",
"config",
"values",
"specified",
"in",
"key",
"name",
"is",
"sane",
"according",
"to",
"config",
"attributes",
"defined",
"as",
"properties",
"on",
"this",
"class"
] | train | https://github.com/20c/vodka/blob/9615148ac6560298453704bb5246b35b66b3339c/vodka/config/__init__.py#L86-L202 |
20c/vodka | vodka/config/__init__.py | Handler.validate | def validate(cls, cfg, path="", nested=0, parent_cfg=None):
"""
Validates a section of a config dict. Will automatically
validate child sections as well if their attribute pointers
are instantiated with a handler property
"""
# number of critical errors found
num_crit = 0
# number of non-critical errors found
num_warn = 0
# check for missing keys in the config
for name in dir(cls):
if nested > 0:
break
try:
attr = getattr(cls, name)
if isinstance(attr, Attribute):
if attr.default is None and name not in cfg:
# no default value defined, which means its required
# to be set in the config file
if path:
attr_full_name = "%s.%s" % (path, name)
else:
attr_full_name = name
raise vodka.exceptions.ConfigErrorMissing(
attr_full_name, attr)
attr.preload(cfg, name)
except vodka.exceptions.ConfigErrorMissing as inst:
if inst.level == "warn":
vodka.log.warn(inst.explanation)
num_warn += 1
elif inst.level == "critical":
vodka.log.error(inst.explanation)
num_crit += 1
if type(cfg) in [dict, Config]:
keys = list(cfg.keys())
if nested > 0:
for _k, _v in cfg.items():
_num_crit, _num_warn = cls.validate(
_v,
path=("%s.%s" % (path, _k)),
nested=nested-1,
parent_cfg=cfg
)
num_crit += _num_crit
num_warn += _num_warn
return num_crit, num_warn
elif type(cfg) == list:
keys = list(range(0, len(cfg)))
else:
raise ValueError("Cannot validate non-iterable config value")
# validate existing keys in the config
for key in keys:
try:
_num_crit, _num_warn = cls.check(cfg, key, path)
num_crit += _num_crit
num_warn += _num_warn
except (
vodka.exceptions.ConfigErrorUnknown,
vodka.exceptions.ConfigErrorValue,
vodka.exceptions.ConfigErrorType
) as inst:
if inst.level == "warn":
vodka.log.warn(inst.explanation)
num_warn += 1
elif inst.level == "critical":
vodka.log.error(inst.explanation)
num_crit += 1
return num_crit, num_warn | python | def validate(cls, cfg, path="", nested=0, parent_cfg=None):
"""
Validates a section of a config dict. Will automatically
validate child sections as well if their attribute pointers
are instantiated with a handler property
"""
# number of critical errors found
num_crit = 0
# number of non-critical errors found
num_warn = 0
# check for missing keys in the config
for name in dir(cls):
if nested > 0:
break
try:
attr = getattr(cls, name)
if isinstance(attr, Attribute):
if attr.default is None and name not in cfg:
# no default value defined, which means its required
# to be set in the config file
if path:
attr_full_name = "%s.%s" % (path, name)
else:
attr_full_name = name
raise vodka.exceptions.ConfigErrorMissing(
attr_full_name, attr)
attr.preload(cfg, name)
except vodka.exceptions.ConfigErrorMissing as inst:
if inst.level == "warn":
vodka.log.warn(inst.explanation)
num_warn += 1
elif inst.level == "critical":
vodka.log.error(inst.explanation)
num_crit += 1
if type(cfg) in [dict, Config]:
keys = list(cfg.keys())
if nested > 0:
for _k, _v in cfg.items():
_num_crit, _num_warn = cls.validate(
_v,
path=("%s.%s" % (path, _k)),
nested=nested-1,
parent_cfg=cfg
)
num_crit += _num_crit
num_warn += _num_warn
return num_crit, num_warn
elif type(cfg) == list:
keys = list(range(0, len(cfg)))
else:
raise ValueError("Cannot validate non-iterable config value")
# validate existing keys in the config
for key in keys:
try:
_num_crit, _num_warn = cls.check(cfg, key, path)
num_crit += _num_crit
num_warn += _num_warn
except (
vodka.exceptions.ConfigErrorUnknown,
vodka.exceptions.ConfigErrorValue,
vodka.exceptions.ConfigErrorType
) as inst:
if inst.level == "warn":
vodka.log.warn(inst.explanation)
num_warn += 1
elif inst.level == "critical":
vodka.log.error(inst.explanation)
num_crit += 1
return num_crit, num_warn | [
"def",
"validate",
"(",
"cls",
",",
"cfg",
",",
"path",
"=",
"\"\"",
",",
"nested",
"=",
"0",
",",
"parent_cfg",
"=",
"None",
")",
":",
"# number of critical errors found",
"num_crit",
"=",
"0",
"# number of non-critical errors found",
"num_warn",
"=",
"0",
"#... | Validates a section of a config dict. Will automatically
validate child sections as well if their attribute pointers
are instantiated with a handler property | [
"Validates",
"a",
"section",
"of",
"a",
"config",
"dict",
".",
"Will",
"automatically",
"validate",
"child",
"sections",
"as",
"well",
"if",
"their",
"attribute",
"pointers",
"are",
"instantiated",
"with",
"a",
"handler",
"property"
] | train | https://github.com/20c/vodka/blob/9615148ac6560298453704bb5246b35b66b3339c/vodka/config/__init__.py#L214-L293 |
20c/vodka | vodka/config/__init__.py | Handler.attributes | def attributes(cls):
"""
yields tuples for all attributes defined on this handler
tuple yielded:
name (str), attribute (Attribute)
"""
for k in dir(cls):
v = getattr(cls, k)
if isinstance(v, Attribute):
yield k,v | python | def attributes(cls):
"""
yields tuples for all attributes defined on this handler
tuple yielded:
name (str), attribute (Attribute)
"""
for k in dir(cls):
v = getattr(cls, k)
if isinstance(v, Attribute):
yield k,v | [
"def",
"attributes",
"(",
"cls",
")",
":",
"for",
"k",
"in",
"dir",
"(",
"cls",
")",
":",
"v",
"=",
"getattr",
"(",
"cls",
",",
"k",
")",
"if",
"isinstance",
"(",
"v",
",",
"Attribute",
")",
":",
"yield",
"k",
",",
"v"
] | yields tuples for all attributes defined on this handler
tuple yielded:
name (str), attribute (Attribute) | [
"yields",
"tuples",
"for",
"all",
"attributes",
"defined",
"on",
"this",
"handler"
] | train | https://github.com/20c/vodka/blob/9615148ac6560298453704bb5246b35b66b3339c/vodka/config/__init__.py#L307-L318 |
20c/vodka | vodka/config/__init__.py | Config.read | def read(self, config_dir=None, clear=False, config_file=None):
"""
The munge Config's read function only allows to read from
a config directory, but we also want to be able to read
straight from a config file as well
"""
if config_file:
data_file = os.path.basename(config_file)
data_path = os.path.dirname(config_file)
if clear:
self.clear()
config = munge.load_datafile(data_file, data_path, default=None)
if not config:
raise IOError("Config file not found: %s" % config_file)
munge.util.recursive_update(self.data, config)
self._meta_config_dir = data_path
return
else:
return super(Config, self).read(config_dir=config_dir, clear=clear) | python | def read(self, config_dir=None, clear=False, config_file=None):
"""
The munge Config's read function only allows to read from
a config directory, but we also want to be able to read
straight from a config file as well
"""
if config_file:
data_file = os.path.basename(config_file)
data_path = os.path.dirname(config_file)
if clear:
self.clear()
config = munge.load_datafile(data_file, data_path, default=None)
if not config:
raise IOError("Config file not found: %s" % config_file)
munge.util.recursive_update(self.data, config)
self._meta_config_dir = data_path
return
else:
return super(Config, self).read(config_dir=config_dir, clear=clear) | [
"def",
"read",
"(",
"self",
",",
"config_dir",
"=",
"None",
",",
"clear",
"=",
"False",
",",
"config_file",
"=",
"None",
")",
":",
"if",
"config_file",
":",
"data_file",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"config_file",
")",
"data_path",
"="... | The munge Config's read function only allows to read from
a config directory, but we also want to be able to read
straight from a config file as well | [
"The",
"munge",
"Config",
"s",
"read",
"function",
"only",
"allows",
"to",
"read",
"from",
"a",
"config",
"directory",
"but",
"we",
"also",
"want",
"to",
"be",
"able",
"to",
"read",
"straight",
"from",
"a",
"config",
"file",
"as",
"well"
] | train | https://github.com/20c/vodka/blob/9615148ac6560298453704bb5246b35b66b3339c/vodka/config/__init__.py#L408-L431 |
PGower/PyCanvas | pycanvas/apis/favorites.py | FavoritesAPI.remove_group_from_favorites | def remove_group_from_favorites(self, id):
"""
Remove group from favorites.
Remove a group from the current user's favorites.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""the ID or SIS ID of the group to remove"""
path["id"] = id
self.logger.debug("DELETE /api/v1/users/self/favorites/groups/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/self/favorites/groups/{id}".format(**path), data=data, params=params, single_item=True) | python | def remove_group_from_favorites(self, id):
"""
Remove group from favorites.
Remove a group from the current user's favorites.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""the ID or SIS ID of the group to remove"""
path["id"] = id
self.logger.debug("DELETE /api/v1/users/self/favorites/groups/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/self/favorites/groups/{id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"remove_group_from_favorites",
"(",
"self",
",",
"id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - id\r",
"\"\"\"the ID or SIS ID of the group to remove\"\"\"",
"path",
"[",
"\"id\"",
"]",
"=",
"id... | Remove group from favorites.
Remove a group from the current user's favorites. | [
"Remove",
"group",
"from",
"favorites",
".",
"Remove",
"a",
"group",
"from",
"the",
"current",
"user",
"s",
"favorites",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/favorites.py#L104-L119 |
PGower/PyCanvas | pycanvas/apis/favorites.py | FavoritesAPI.reset_course_favorites | def reset_course_favorites(self):
"""
Reset course favorites.
Reset the current user's course favorites to the default
automatically generated list of enrolled courses
"""
path = {}
data = {}
params = {}
self.logger.debug("DELETE /api/v1/users/self/favorites/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/self/favorites/courses".format(**path), data=data, params=params, no_data=True) | python | def reset_course_favorites(self):
"""
Reset course favorites.
Reset the current user's course favorites to the default
automatically generated list of enrolled courses
"""
path = {}
data = {}
params = {}
self.logger.debug("DELETE /api/v1/users/self/favorites/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/self/favorites/courses".format(**path), data=data, params=params, no_data=True) | [
"def",
"reset_course_favorites",
"(",
"self",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"self",
".",
"logger",
".",
"debug",
"(",
"\"DELETE /api/v1/users/self/favorites/courses with query params: {params} and form data: {data}\""... | Reset course favorites.
Reset the current user's course favorites to the default
automatically generated list of enrolled courses | [
"Reset",
"course",
"favorites",
".",
"Reset",
"the",
"current",
"user",
"s",
"course",
"favorites",
"to",
"the",
"default",
"automatically",
"generated",
"list",
"of",
"enrolled",
"courses"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/favorites.py#L121-L133 |
PGower/PyCanvas | pycanvas/apis/search.py | SearchAPI.find_recipients_conversations | def find_recipients_conversations(self, context=None, exclude=None, from_conversation_id=None, permissions=None, search=None, type=None, user_id=None):
"""
Find recipients.
Find valid recipients (users, courses and groups) that the current user
can send messages to. The /api/v1/search/recipients path is the preferred
endpoint, /api/v1/conversations/find_recipients is deprecated.
Pagination is supported.
"""
path = {}
data = {}
params = {}
# OPTIONAL - search
"""Search terms used for matching users/courses/groups (e.g. "bob smith"). If
multiple terms are given (separated via whitespace), only results matching
all terms will be returned."""
if search is not None:
params["search"] = search
# OPTIONAL - context
"""Limit the search to a particular course/group (e.g. "course_3" or "group_4")."""
if context is not None:
params["context"] = context
# OPTIONAL - exclude
"""Array of ids to exclude from the search. These may be user ids or
course/group ids prefixed with "course_" or "group_" respectively,
e.g. exclude[]=1&exclude[]=2&exclude[]=course_3"""
if exclude is not None:
params["exclude"] = exclude
# OPTIONAL - type
"""Limit the search just to users or contexts (groups/courses)."""
if type is not None:
self._validate_enum(type, ["user", "context"])
params["type"] = type
# OPTIONAL - user_id
"""Search for a specific user id. This ignores the other above parameters,
and will never return more than one result."""
if user_id is not None:
params["user_id"] = user_id
# OPTIONAL - from_conversation_id
"""When searching by user_id, only users that could be normally messaged by
this user will be returned. This parameter allows you to specify a
conversation that will be referenced for a shared context -- if both the
current user and the searched user are in the conversation, the user will
be returned. This is used to start new side conversations."""
if from_conversation_id is not None:
params["from_conversation_id"] = from_conversation_id
# OPTIONAL - permissions
"""Array of permission strings to be checked for each matched context (e.g.
"send_messages"). This argument determines which permissions may be
returned in the response; it won't prevent contexts from being returned if
they don't grant the permission(s)."""
if permissions is not None:
params["permissions"] = permissions
self.logger.debug("GET /api/v1/conversations/find_recipients with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/conversations/find_recipients".format(**path), data=data, params=params, no_data=True) | python | def find_recipients_conversations(self, context=None, exclude=None, from_conversation_id=None, permissions=None, search=None, type=None, user_id=None):
"""
Find recipients.
Find valid recipients (users, courses and groups) that the current user
can send messages to. The /api/v1/search/recipients path is the preferred
endpoint, /api/v1/conversations/find_recipients is deprecated.
Pagination is supported.
"""
path = {}
data = {}
params = {}
# OPTIONAL - search
"""Search terms used for matching users/courses/groups (e.g. "bob smith"). If
multiple terms are given (separated via whitespace), only results matching
all terms will be returned."""
if search is not None:
params["search"] = search
# OPTIONAL - context
"""Limit the search to a particular course/group (e.g. "course_3" or "group_4")."""
if context is not None:
params["context"] = context
# OPTIONAL - exclude
"""Array of ids to exclude from the search. These may be user ids or
course/group ids prefixed with "course_" or "group_" respectively,
e.g. exclude[]=1&exclude[]=2&exclude[]=course_3"""
if exclude is not None:
params["exclude"] = exclude
# OPTIONAL - type
"""Limit the search just to users or contexts (groups/courses)."""
if type is not None:
self._validate_enum(type, ["user", "context"])
params["type"] = type
# OPTIONAL - user_id
"""Search for a specific user id. This ignores the other above parameters,
and will never return more than one result."""
if user_id is not None:
params["user_id"] = user_id
# OPTIONAL - from_conversation_id
"""When searching by user_id, only users that could be normally messaged by
this user will be returned. This parameter allows you to specify a
conversation that will be referenced for a shared context -- if both the
current user and the searched user are in the conversation, the user will
be returned. This is used to start new side conversations."""
if from_conversation_id is not None:
params["from_conversation_id"] = from_conversation_id
# OPTIONAL - permissions
"""Array of permission strings to be checked for each matched context (e.g.
"send_messages"). This argument determines which permissions may be
returned in the response; it won't prevent contexts from being returned if
they don't grant the permission(s)."""
if permissions is not None:
params["permissions"] = permissions
self.logger.debug("GET /api/v1/conversations/find_recipients with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/conversations/find_recipients".format(**path), data=data, params=params, no_data=True) | [
"def",
"find_recipients_conversations",
"(",
"self",
",",
"context",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"from_conversation_id",
"=",
"None",
",",
"permissions",
"=",
"None",
",",
"search",
"=",
"None",
",",
"type",
"=",
"None",
",",
"user_id",
... | Find recipients.
Find valid recipients (users, courses and groups) that the current user
can send messages to. The /api/v1/search/recipients path is the preferred
endpoint, /api/v1/conversations/find_recipients is deprecated.
Pagination is supported. | [
"Find",
"recipients",
".",
"Find",
"valid",
"recipients",
"(",
"users",
"courses",
"and",
"groups",
")",
"that",
"the",
"current",
"user",
"can",
"send",
"messages",
"to",
".",
"The",
"/",
"api",
"/",
"v1",
"/",
"search",
"/",
"recipients",
"path",
"is",... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/search.py#L19-L82 |
PGower/PyCanvas | pycanvas/apis/search.py | SearchAPI.list_all_courses | def list_all_courses(self, open_enrollment_only=None, public_only=None, search=None):
"""
List all courses.
List all courses visible in the public index
"""
path = {}
data = {}
params = {}
# OPTIONAL - search
"""Search terms used for matching users/courses/groups (e.g. "bob smith"). If
multiple terms are given (separated via whitespace), only results matching
all terms will be returned."""
if search is not None:
params["search"] = search
# OPTIONAL - public_only
"""Only return courses with public content. Defaults to false."""
if public_only is not None:
params["public_only"] = public_only
# OPTIONAL - open_enrollment_only
"""Only return courses that allow self enrollment. Defaults to false."""
if open_enrollment_only is not None:
params["open_enrollment_only"] = open_enrollment_only
self.logger.debug("GET /api/v1/search/all_courses with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/search/all_courses".format(**path), data=data, params=params, no_data=True) | python | def list_all_courses(self, open_enrollment_only=None, public_only=None, search=None):
"""
List all courses.
List all courses visible in the public index
"""
path = {}
data = {}
params = {}
# OPTIONAL - search
"""Search terms used for matching users/courses/groups (e.g. "bob smith"). If
multiple terms are given (separated via whitespace), only results matching
all terms will be returned."""
if search is not None:
params["search"] = search
# OPTIONAL - public_only
"""Only return courses with public content. Defaults to false."""
if public_only is not None:
params["public_only"] = public_only
# OPTIONAL - open_enrollment_only
"""Only return courses that allow self enrollment. Defaults to false."""
if open_enrollment_only is not None:
params["open_enrollment_only"] = open_enrollment_only
self.logger.debug("GET /api/v1/search/all_courses with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/search/all_courses".format(**path), data=data, params=params, no_data=True) | [
"def",
"list_all_courses",
"(",
"self",
",",
"open_enrollment_only",
"=",
"None",
",",
"public_only",
"=",
"None",
",",
"search",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# OPTIONAL - search\r",
"\"\"... | List all courses.
List all courses visible in the public index | [
"List",
"all",
"courses",
".",
"List",
"all",
"courses",
"visible",
"in",
"the",
"public",
"index"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/search.py#L149-L177 |
PGower/PyCanvas | pycanvas/apis/communication_channels.py | CommunicationChannelsAPI.create_communication_channel | def create_communication_channel(self, user_id, communication_channel_type, communication_channel_address, communication_channel_token=None, skip_confirmation=None):
"""
Create a communication channel.
Creates a new communication channel for the specified user.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - communication_channel[address]
"""An email address or SMS number. Not required for "push" type channels."""
data["communication_channel[address]"] = communication_channel_address
# REQUIRED - communication_channel[type]
"""The type of communication channel.
In order to enable push notification support, the server must be
properly configured (via sns.yml) to communicate with Amazon
Simple Notification Services, and the developer key used to create
the access token from this request must have an SNS ARN configured on
it."""
self._validate_enum(communication_channel_type, ["email", "sms", "push"])
data["communication_channel[type]"] = communication_channel_type
# OPTIONAL - communication_channel[token]
"""A registration id, device token, or equivalent token given to an app when
registering with a push notification provider. Only valid for "push" type channels."""
if communication_channel_token is not None:
data["communication_channel[token]"] = communication_channel_token
# OPTIONAL - skip_confirmation
"""Only valid for site admins and account admins making requests; If true, the channel is
automatically validated and no confirmation email or SMS is sent.
Otherwise, the user must respond to a confirmation message to confirm the
channel."""
if skip_confirmation is not None:
data["skip_confirmation"] = skip_confirmation
self.logger.debug("POST /api/v1/users/{user_id}/communication_channels with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/users/{user_id}/communication_channels".format(**path), data=data, params=params, single_item=True) | python | def create_communication_channel(self, user_id, communication_channel_type, communication_channel_address, communication_channel_token=None, skip_confirmation=None):
"""
Create a communication channel.
Creates a new communication channel for the specified user.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - communication_channel[address]
"""An email address or SMS number. Not required for "push" type channels."""
data["communication_channel[address]"] = communication_channel_address
# REQUIRED - communication_channel[type]
"""The type of communication channel.
In order to enable push notification support, the server must be
properly configured (via sns.yml) to communicate with Amazon
Simple Notification Services, and the developer key used to create
the access token from this request must have an SNS ARN configured on
it."""
self._validate_enum(communication_channel_type, ["email", "sms", "push"])
data["communication_channel[type]"] = communication_channel_type
# OPTIONAL - communication_channel[token]
"""A registration id, device token, or equivalent token given to an app when
registering with a push notification provider. Only valid for "push" type channels."""
if communication_channel_token is not None:
data["communication_channel[token]"] = communication_channel_token
# OPTIONAL - skip_confirmation
"""Only valid for site admins and account admins making requests; If true, the channel is
automatically validated and no confirmation email or SMS is sent.
Otherwise, the user must respond to a confirmation message to confirm the
channel."""
if skip_confirmation is not None:
data["skip_confirmation"] = skip_confirmation
self.logger.debug("POST /api/v1/users/{user_id}/communication_channels with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/users/{user_id}/communication_channels".format(**path), data=data, params=params, single_item=True) | [
"def",
"create_communication_channel",
"(",
"self",
",",
"user_id",
",",
"communication_channel_type",
",",
"communication_channel_address",
",",
"communication_channel_token",
"=",
"None",
",",
"skip_confirmation",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data"... | Create a communication channel.
Creates a new communication channel for the specified user. | [
"Create",
"a",
"communication",
"channel",
".",
"Creates",
"a",
"new",
"communication",
"channel",
"for",
"the",
"specified",
"user",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/communication_channels.py#L37-L81 |
PGower/PyCanvas | pycanvas/apis/communication_channels.py | CommunicationChannelsAPI.delete_communication_channel_id | def delete_communication_channel_id(self, id, user_id):
"""
Delete a communication channel.
Delete an existing communication channel.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
self.logger.debug("DELETE /api/v1/users/{user_id}/communication_channels/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/{user_id}/communication_channels/{id}".format(**path), data=data, params=params, single_item=True) | python | def delete_communication_channel_id(self, id, user_id):
"""
Delete a communication channel.
Delete an existing communication channel.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
self.logger.debug("DELETE /api/v1/users/{user_id}/communication_channels/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/{user_id}/communication_channels/{id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"delete_communication_channel_id",
"(",
"self",
",",
"id",
",",
"user_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"user_id\"",
"]",
"=",
"user_... | Delete a communication channel.
Delete an existing communication channel. | [
"Delete",
"a",
"communication",
"channel",
".",
"Delete",
"an",
"existing",
"communication",
"channel",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/communication_channels.py#L83-L102 |
bioasp/caspo | caspo/core/literal.py | Literal.from_str | def from_str(cls, string):
"""
Creates a literal from a string
Parameters
----------
string : str
If the string starts with '!', it's interpreted as a negated variable
Returns
-------
caspo.core.literal.Literal
Created object instance
"""
if string[0] == '!':
signature = -1
variable = string[1:]
else:
signature = 1
variable = string
return cls(variable, signature) | python | def from_str(cls, string):
"""
Creates a literal from a string
Parameters
----------
string : str
If the string starts with '!', it's interpreted as a negated variable
Returns
-------
caspo.core.literal.Literal
Created object instance
"""
if string[0] == '!':
signature = -1
variable = string[1:]
else:
signature = 1
variable = string
return cls(variable, signature) | [
"def",
"from_str",
"(",
"cls",
",",
"string",
")",
":",
"if",
"string",
"[",
"0",
"]",
"==",
"'!'",
":",
"signature",
"=",
"-",
"1",
"variable",
"=",
"string",
"[",
"1",
":",
"]",
"else",
":",
"signature",
"=",
"1",
"variable",
"=",
"string",
"re... | Creates a literal from a string
Parameters
----------
string : str
If the string starts with '!', it's interpreted as a negated variable
Returns
-------
caspo.core.literal.Literal
Created object instance | [
"Creates",
"a",
"literal",
"from",
"a",
"string"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/literal.py#L33-L54 |
bionikspoon/cache_requests | cache_requests/utils.py | normalize_signature | def normalize_signature(func):
"""Decorator. Combine args and kwargs. Unpack single item tuples."""
@wraps(func)
def wrapper(*args, **kwargs):
if kwargs:
args = args, kwargs
if len(args) is 1:
args = args[0]
return func(args)
return wrapper | python | def normalize_signature(func):
"""Decorator. Combine args and kwargs. Unpack single item tuples."""
@wraps(func)
def wrapper(*args, **kwargs):
if kwargs:
args = args, kwargs
if len(args) is 1:
args = args[0]
return func(args)
return wrapper | [
"def",
"normalize_signature",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"args",
"=",
"args",
",",
"kwargs",
"if",
"len",
"(",
"args",
")",
"i... | Decorator. Combine args and kwargs. Unpack single item tuples. | [
"Decorator",
".",
"Combine",
"args",
"and",
"kwargs",
".",
"Unpack",
"single",
"item",
"tuples",
"."
] | train | https://github.com/bionikspoon/cache_requests/blob/d75f6f944bc5a72fef5d7811e4973e124d9921dd/cache_requests/utils.py#L99-L112 |
mrstephenneal/mysql-toolkit | mysql/toolkit/commands/prepare.py | filter_commands | def filter_commands(commands, invalid_query_starts=('DROP', 'UNLOCK', 'LOCK')):
"""
Remove particular queries from a list of SQL commands.
:param commands: List of SQL commands
:param invalid_query_starts: Type of SQL command to remove
:return: Filtered list of SQL commands
"""
commands_with_drops = len(commands)
filtered_commands = [c for c in commands if not c.startswith(invalid_query_starts)]
if commands_with_drops - len(filtered_commands) > 0:
print("\t" + str(invalid_query_starts) + " commands removed", commands_with_drops - len(filtered_commands))
return filtered_commands | python | def filter_commands(commands, invalid_query_starts=('DROP', 'UNLOCK', 'LOCK')):
"""
Remove particular queries from a list of SQL commands.
:param commands: List of SQL commands
:param invalid_query_starts: Type of SQL command to remove
:return: Filtered list of SQL commands
"""
commands_with_drops = len(commands)
filtered_commands = [c for c in commands if not c.startswith(invalid_query_starts)]
if commands_with_drops - len(filtered_commands) > 0:
print("\t" + str(invalid_query_starts) + " commands removed", commands_with_drops - len(filtered_commands))
return filtered_commands | [
"def",
"filter_commands",
"(",
"commands",
",",
"invalid_query_starts",
"=",
"(",
"'DROP'",
",",
"'UNLOCK'",
",",
"'LOCK'",
")",
")",
":",
"commands_with_drops",
"=",
"len",
"(",
"commands",
")",
"filtered_commands",
"=",
"[",
"c",
"for",
"c",
"in",
"command... | Remove particular queries from a list of SQL commands.
:param commands: List of SQL commands
:param invalid_query_starts: Type of SQL command to remove
:return: Filtered list of SQL commands | [
"Remove",
"particular",
"queries",
"from",
"a",
"list",
"of",
"SQL",
"commands",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/commands/prepare.py#L7-L19 |
mrstephenneal/mysql-toolkit | mysql/toolkit/commands/prepare.py | prepare_sql | def prepare_sql(sql, add_semicolon=True, invalid_starts=('--', '/*', '*/', ';')):
"""Wrapper method for PrepareSQL class."""
return PrepareSQL(sql, add_semicolon, invalid_starts).prepared | python | def prepare_sql(sql, add_semicolon=True, invalid_starts=('--', '/*', '*/', ';')):
"""Wrapper method for PrepareSQL class."""
return PrepareSQL(sql, add_semicolon, invalid_starts).prepared | [
"def",
"prepare_sql",
"(",
"sql",
",",
"add_semicolon",
"=",
"True",
",",
"invalid_starts",
"=",
"(",
"'--'",
",",
"'/*'",
",",
"'*/'",
",",
"';'",
")",
")",
":",
"return",
"PrepareSQL",
"(",
"sql",
",",
"add_semicolon",
",",
"invalid_starts",
")",
".",
... | Wrapper method for PrepareSQL class. | [
"Wrapper",
"method",
"for",
"PrepareSQL",
"class",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/commands/prepare.py#L131-L133 |
mrstephenneal/mysql-toolkit | mysql/toolkit/commands/prepare.py | PrepareSQL._split_sql | def _split_sql(self, sql):
"""
Generate hunks of SQL that are between the bookends.
note: beginning & end of string are returned as None
:return: tuple of beginning bookend, closing bookend, and contents
"""
bookends = ("\n", ";", "--", "/*", "*/")
last_bookend_found = None
start = 0
while start <= len(sql):
results = self._get_next_occurrence(sql, start, bookends)
if results is None:
yield (last_bookend_found, None, sql[start:])
start = len(sql) + 1
else:
(end, bookend) = results
yield (last_bookend_found, bookend, sql[start:end])
start = end + len(bookend)
last_bookend_found = bookend | python | def _split_sql(self, sql):
"""
Generate hunks of SQL that are between the bookends.
note: beginning & end of string are returned as None
:return: tuple of beginning bookend, closing bookend, and contents
"""
bookends = ("\n", ";", "--", "/*", "*/")
last_bookend_found = None
start = 0
while start <= len(sql):
results = self._get_next_occurrence(sql, start, bookends)
if results is None:
yield (last_bookend_found, None, sql[start:])
start = len(sql) + 1
else:
(end, bookend) = results
yield (last_bookend_found, bookend, sql[start:end])
start = end + len(bookend)
last_bookend_found = bookend | [
"def",
"_split_sql",
"(",
"self",
",",
"sql",
")",
":",
"bookends",
"=",
"(",
"\"\\n\"",
",",
"\";\"",
",",
"\"--\"",
",",
"\"/*\"",
",",
"\"*/\"",
")",
"last_bookend_found",
"=",
"None",
"start",
"=",
"0",
"while",
"start",
"<=",
"len",
"(",
"sql",
... | Generate hunks of SQL that are between the bookends.
note: beginning & end of string are returned as None
:return: tuple of beginning bookend, closing bookend, and contents | [
"Generate",
"hunks",
"of",
"SQL",
"that",
"are",
"between",
"the",
"bookends",
".",
"note",
":",
"beginning",
"&",
"end",
"of",
"string",
"are",
"returned",
"as",
"None"
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/commands/prepare.py#L89-L109 |
mrstephenneal/mysql-toolkit | mysql/toolkit/commands/prepare.py | PrepareSQL._get_next_occurrence | def _get_next_occurrence(haystack, offset, needles):
"""
Find next occurence of one of the needles in the haystack
:return: tuple of (index, needle found)
or: None if no needle was found"""
# make map of first char to full needle (only works if all needles
# have different first characters)
firstcharmap = dict([(n[0], n) for n in needles])
firstchars = firstcharmap.keys()
while offset < len(haystack):
if haystack[offset] in firstchars:
possible_needle = firstcharmap[haystack[offset]]
if haystack[offset:offset + len(possible_needle)] == possible_needle:
return offset, possible_needle
offset += 1
return None | python | def _get_next_occurrence(haystack, offset, needles):
"""
Find next occurence of one of the needles in the haystack
:return: tuple of (index, needle found)
or: None if no needle was found"""
# make map of first char to full needle (only works if all needles
# have different first characters)
firstcharmap = dict([(n[0], n) for n in needles])
firstchars = firstcharmap.keys()
while offset < len(haystack):
if haystack[offset] in firstchars:
possible_needle = firstcharmap[haystack[offset]]
if haystack[offset:offset + len(possible_needle)] == possible_needle:
return offset, possible_needle
offset += 1
return None | [
"def",
"_get_next_occurrence",
"(",
"haystack",
",",
"offset",
",",
"needles",
")",
":",
"# make map of first char to full needle (only works if all needles",
"# have different first characters)",
"firstcharmap",
"=",
"dict",
"(",
"[",
"(",
"n",
"[",
"0",
"]",
",",
"n",... | Find next occurence of one of the needles in the haystack
:return: tuple of (index, needle found)
or: None if no needle was found | [
"Find",
"next",
"occurence",
"of",
"one",
"of",
"the",
"needles",
"in",
"the",
"haystack"
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/commands/prepare.py#L112-L128 |
PGower/PyCanvas | pycanvas/apis/content_exports.py | ContentExportsAPI.export_content_courses | def export_content_courses(self, course_id, export_type, skip_notifications=None):
"""
Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export completes, use the {api:ContentExportsApiController#show Show content export} endpoint
to retrieve a download URL for the exported content.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - export_type
""""common_cartridge":: Export the contents of the course in the Common Cartridge (.imscc) format
"qti":: Export quizzes from a course in the QTI format
"zip":: Export files from a course, group, or user in a zip file"""
self._validate_enum(export_type, ["common_cartridge", "qti", "zip"])
data["export_type"] = export_type
# OPTIONAL - skip_notifications
"""Don't send the notifications about the export to the user. Default: false"""
if skip_notifications is not None:
data["skip_notifications"] = skip_notifications
self.logger.debug("POST /api/v1/courses/{course_id}/content_exports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/content_exports".format(**path), data=data, params=params, single_item=True) | python | def export_content_courses(self, course_id, export_type, skip_notifications=None):
"""
Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export completes, use the {api:ContentExportsApiController#show Show content export} endpoint
to retrieve a download URL for the exported content.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - export_type
""""common_cartridge":: Export the contents of the course in the Common Cartridge (.imscc) format
"qti":: Export quizzes from a course in the QTI format
"zip":: Export files from a course, group, or user in a zip file"""
self._validate_enum(export_type, ["common_cartridge", "qti", "zip"])
data["export_type"] = export_type
# OPTIONAL - skip_notifications
"""Don't send the notifications about the export to the user. Default: false"""
if skip_notifications is not None:
data["skip_notifications"] = skip_notifications
self.logger.debug("POST /api/v1/courses/{course_id}/content_exports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/content_exports".format(**path), data=data, params=params, single_item=True) | [
"def",
"export_content_courses",
"(",
"self",
",",
"course_id",
",",
"export_type",
",",
"skip_notifications",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"p... | Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export completes, use the {api:ContentExportsApiController#show Show content export} endpoint
to retrieve a download URL for the exported content. | [
"Export",
"content",
".",
"Begin",
"a",
"content",
"export",
"job",
"for",
"a",
"course",
"group",
"or",
"user",
".",
"You",
"can",
"use",
"the",
"{",
"api",
":",
"ProgressController#show",
"Progress",
"API",
"}",
"to",
"track",
"the",
"progress",
"of",
... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/content_exports.py#L136-L170 |
PGower/PyCanvas | pycanvas/apis/content_exports.py | ContentExportsAPI.export_content_groups | def export_content_groups(self, group_id, export_type, skip_notifications=None):
"""
Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export completes, use the {api:ContentExportsApiController#show Show content export} endpoint
to retrieve a download URL for the exported content.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - export_type
""""common_cartridge":: Export the contents of the course in the Common Cartridge (.imscc) format
"qti":: Export quizzes from a course in the QTI format
"zip":: Export files from a course, group, or user in a zip file"""
self._validate_enum(export_type, ["common_cartridge", "qti", "zip"])
data["export_type"] = export_type
# OPTIONAL - skip_notifications
"""Don't send the notifications about the export to the user. Default: false"""
if skip_notifications is not None:
data["skip_notifications"] = skip_notifications
self.logger.debug("POST /api/v1/groups/{group_id}/content_exports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups/{group_id}/content_exports".format(**path), data=data, params=params, single_item=True) | python | def export_content_groups(self, group_id, export_type, skip_notifications=None):
"""
Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export completes, use the {api:ContentExportsApiController#show Show content export} endpoint
to retrieve a download URL for the exported content.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - export_type
""""common_cartridge":: Export the contents of the course in the Common Cartridge (.imscc) format
"qti":: Export quizzes from a course in the QTI format
"zip":: Export files from a course, group, or user in a zip file"""
self._validate_enum(export_type, ["common_cartridge", "qti", "zip"])
data["export_type"] = export_type
# OPTIONAL - skip_notifications
"""Don't send the notifications about the export to the user. Default: false"""
if skip_notifications is not None:
data["skip_notifications"] = skip_notifications
self.logger.debug("POST /api/v1/groups/{group_id}/content_exports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups/{group_id}/content_exports".format(**path), data=data, params=params, single_item=True) | [
"def",
"export_content_groups",
"(",
"self",
",",
"group_id",
",",
"export_type",
",",
"skip_notifications",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path... | Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export completes, use the {api:ContentExportsApiController#show Show content export} endpoint
to retrieve a download URL for the exported content. | [
"Export",
"content",
".",
"Begin",
"a",
"content",
"export",
"job",
"for",
"a",
"course",
"group",
"or",
"user",
".",
"You",
"can",
"use",
"the",
"{",
"api",
":",
"ProgressController#show",
"Progress",
"API",
"}",
"to",
"track",
"the",
"progress",
"of",
... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/content_exports.py#L172-L206 |
PGower/PyCanvas | pycanvas/apis/content_exports.py | ContentExportsAPI.export_content_users | def export_content_users(self, user_id, export_type, skip_notifications=None):
"""
Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export completes, use the {api:ContentExportsApiController#show Show content export} endpoint
to retrieve a download URL for the exported content.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - export_type
""""common_cartridge":: Export the contents of the course in the Common Cartridge (.imscc) format
"qti":: Export quizzes from a course in the QTI format
"zip":: Export files from a course, group, or user in a zip file"""
self._validate_enum(export_type, ["common_cartridge", "qti", "zip"])
data["export_type"] = export_type
# OPTIONAL - skip_notifications
"""Don't send the notifications about the export to the user. Default: false"""
if skip_notifications is not None:
data["skip_notifications"] = skip_notifications
self.logger.debug("POST /api/v1/users/{user_id}/content_exports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/users/{user_id}/content_exports".format(**path), data=data, params=params, single_item=True) | python | def export_content_users(self, user_id, export_type, skip_notifications=None):
"""
Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export completes, use the {api:ContentExportsApiController#show Show content export} endpoint
to retrieve a download URL for the exported content.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - export_type
""""common_cartridge":: Export the contents of the course in the Common Cartridge (.imscc) format
"qti":: Export quizzes from a course in the QTI format
"zip":: Export files from a course, group, or user in a zip file"""
self._validate_enum(export_type, ["common_cartridge", "qti", "zip"])
data["export_type"] = export_type
# OPTIONAL - skip_notifications
"""Don't send the notifications about the export to the user. Default: false"""
if skip_notifications is not None:
data["skip_notifications"] = skip_notifications
self.logger.debug("POST /api/v1/users/{user_id}/content_exports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/users/{user_id}/content_exports".format(**path), data=data, params=params, single_item=True) | [
"def",
"export_content_users",
"(",
"self",
",",
"user_id",
",",
"export_type",
",",
"skip_notifications",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",
"path",
... | Export content.
Begin a content export job for a course, group, or user.
You can use the {api:ProgressController#show Progress API} to track the
progress of the export. The migration's progress is linked to with the
_progress_url_ value.
When the export completes, use the {api:ContentExportsApiController#show Show content export} endpoint
to retrieve a download URL for the exported content. | [
"Export",
"content",
".",
"Begin",
"a",
"content",
"export",
"job",
"for",
"a",
"course",
"group",
"or",
"user",
".",
"You",
"can",
"use",
"the",
"{",
"api",
":",
"ProgressController#show",
"Progress",
"API",
"}",
"to",
"track",
"the",
"progress",
"of",
... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/content_exports.py#L208-L242 |
michaeljoseph/remarkable | remarkable/cli.py | ask | def ask(question, no_input=False):
"""Display a Y/n question prompt, and return a boolean"""
if no_input:
return True
else:
input_ = input('%s [Y/n] ' % question)
input_ = input_.strip().lower()
if input_ in ('y', 'yes', ''):
return True
if input_ in ('n', 'no'):
return False
print('Invalid selection') | python | def ask(question, no_input=False):
"""Display a Y/n question prompt, and return a boolean"""
if no_input:
return True
else:
input_ = input('%s [Y/n] ' % question)
input_ = input_.strip().lower()
if input_ in ('y', 'yes', ''):
return True
if input_ in ('n', 'no'):
return False
print('Invalid selection') | [
"def",
"ask",
"(",
"question",
",",
"no_input",
"=",
"False",
")",
":",
"if",
"no_input",
":",
"return",
"True",
"else",
":",
"input_",
"=",
"input",
"(",
"'%s [Y/n] '",
"%",
"question",
")",
"input_",
"=",
"input_",
".",
"strip",
"(",
")",
".",
"low... | Display a Y/n question prompt, and return a boolean | [
"Display",
"a",
"Y",
"/",
"n",
"question",
"prompt",
"and",
"return",
"a",
"boolean"
] | train | https://github.com/michaeljoseph/remarkable/blob/321f8f7d58fe2ad0c48233980cedda18c5abad55/remarkable/cli.py#L35-L46 |
michaeljoseph/remarkable | remarkable/cli.py | render_template | def render_template(template_name, context):
"""Render a jinja template"""
return Environment(
loader=PackageLoader('remarkable')
).get_template(template_name).render(context) | python | def render_template(template_name, context):
"""Render a jinja template"""
return Environment(
loader=PackageLoader('remarkable')
).get_template(template_name).render(context) | [
"def",
"render_template",
"(",
"template_name",
",",
"context",
")",
":",
"return",
"Environment",
"(",
"loader",
"=",
"PackageLoader",
"(",
"'remarkable'",
")",
")",
".",
"get_template",
"(",
"template_name",
")",
".",
"render",
"(",
"context",
")"
] | Render a jinja template | [
"Render",
"a",
"jinja",
"template"
] | train | https://github.com/michaeljoseph/remarkable/blob/321f8f7d58fe2ad0c48233980cedda18c5abad55/remarkable/cli.py#L49-L53 |
michaeljoseph/remarkable | remarkable/cli.py | render_template_directory | def render_template_directory(deck, arguments):
"""Render a template directory"""
output_directory = dir_name_from_title(deck.title)
if os.path.exists(output_directory):
if sys.stdout.isatty():
if ask(
'%s already exists, shall I delete it?' % output_directory,
arguments.get('--noinput')
):
shutil.rmtree(output_directory)
else:
shutil.rmtree(output_directory)
# copy support files to output directory
template_directory_path = (
'%s/templates/%s' %
(remarkable.__path__[0], deck.presentation_type)
)
shutil.copytree(
template_directory_path,
output_directory,
)
# copy resources
if os.path.exists('resources'):
log.info('Copying resources')
shutil.copytree('resources', '%s/resources' % output_directory)
else:
log.info('No resources to copy')
# render template
template_filename = '%s/index.html' % deck.presentation_type
html = render_template(template_filename, deck.json)
# write index to output directory
index_filename = '%s/index.html' % output_directory
write_file(index_filename, html)
return output_directory | python | def render_template_directory(deck, arguments):
"""Render a template directory"""
output_directory = dir_name_from_title(deck.title)
if os.path.exists(output_directory):
if sys.stdout.isatty():
if ask(
'%s already exists, shall I delete it?' % output_directory,
arguments.get('--noinput')
):
shutil.rmtree(output_directory)
else:
shutil.rmtree(output_directory)
# copy support files to output directory
template_directory_path = (
'%s/templates/%s' %
(remarkable.__path__[0], deck.presentation_type)
)
shutil.copytree(
template_directory_path,
output_directory,
)
# copy resources
if os.path.exists('resources'):
log.info('Copying resources')
shutil.copytree('resources', '%s/resources' % output_directory)
else:
log.info('No resources to copy')
# render template
template_filename = '%s/index.html' % deck.presentation_type
html = render_template(template_filename, deck.json)
# write index to output directory
index_filename = '%s/index.html' % output_directory
write_file(index_filename, html)
return output_directory | [
"def",
"render_template_directory",
"(",
"deck",
",",
"arguments",
")",
":",
"output_directory",
"=",
"dir_name_from_title",
"(",
"deck",
".",
"title",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"output_directory",
")",
":",
"if",
"sys",
".",
"stdout"... | Render a template directory | [
"Render",
"a",
"template",
"directory"
] | train | https://github.com/michaeljoseph/remarkable/blob/321f8f7d58fe2ad0c48233980cedda18c5abad55/remarkable/cli.py#L56-L95 |
s0lst1c3/grey_harvest | grey_harvest.py | main | def main():
''' set things up '''
configs = setup(argparse.ArgumentParser())
harvester = GreyHarvester(
test_domain=configs['test_domain'],
test_sleeptime=TEST_SLEEPTIME,
https_only=configs['https_only'],
allowed_countries=configs['allowed_countries'],
denied_countries=configs['denied_countries'],
ports=configs['ports'],
max_timeout=configs['max_timeout']
)
''' harvest free and working proxies from teh interwebz '''
count = 0
for proxy in harvester.run():
if count >= configs['num_proxies']:
break
print(proxy)
count += 1 | python | def main():
''' set things up '''
configs = setup(argparse.ArgumentParser())
harvester = GreyHarvester(
test_domain=configs['test_domain'],
test_sleeptime=TEST_SLEEPTIME,
https_only=configs['https_only'],
allowed_countries=configs['allowed_countries'],
denied_countries=configs['denied_countries'],
ports=configs['ports'],
max_timeout=configs['max_timeout']
)
''' harvest free and working proxies from teh interwebz '''
count = 0
for proxy in harvester.run():
if count >= configs['num_proxies']:
break
print(proxy)
count += 1 | [
"def",
"main",
"(",
")",
":",
"configs",
"=",
"setup",
"(",
"argparse",
".",
"ArgumentParser",
"(",
")",
")",
"harvester",
"=",
"GreyHarvester",
"(",
"test_domain",
"=",
"configs",
"[",
"'test_domain'",
"]",
",",
"test_sleeptime",
"=",
"TEST_SLEEPTIME",
",",... | set things up | [
"set",
"things",
"up"
] | train | https://github.com/s0lst1c3/grey_harvest/blob/811e5787ce7e613bc489b8e5e475eaa8790f4d66/grey_harvest.py#L264-L284 |
s0lst1c3/grey_harvest | grey_harvest.py | GreyHarvester._extract_proxies | def _extract_proxies(self, ajax_endpoint):
''' request the xml object '''
proxy_xml = requests.get(ajax_endpoint)
print(proxy_xml.content)
root = etree.XML(proxy_xml.content)
quote = root.xpath('quote')[0]
''' extract the raw text from the body of the quote tag '''
raw_text = quote.text
''' eliminate the stuff we don't need '''
proxy_data = raw_text.split('You will definitely love it! Give it a try!</td></tr>')[1]
''' get rid of the </table> at the end of proxy_data '''
proxy_data = proxy_data[:-len('</table>')]
''' split proxy_data into rows '''
table_rows = proxy_data.split('<tr>')
''' convert each row into a Proxy object '''
for row in table_rows:
''' get rid of the </tr> at the end of each row '''
row = row[:-len('</tr>')]
''' split each row into a list of items '''
items = row.split('<td>')
''' sometimes we get weird lists containing only an empty string '''
if len(items) != 7:
continue
''' we'll use this to remove the </td> from the end of each item '''
tdlen = len('</td>')
''' create proxy dict '''
proxy = Proxy(
ip=items[1][:-tdlen],
port=int(items[2][:-tdlen]),
https=bool(items[3][:-tdlen]),
latency=int(items[4][:-tdlen]),
last_checked=items[5][:-tdlen],
country=items[6][:-tdlen],
)
yield proxy | python | def _extract_proxies(self, ajax_endpoint):
''' request the xml object '''
proxy_xml = requests.get(ajax_endpoint)
print(proxy_xml.content)
root = etree.XML(proxy_xml.content)
quote = root.xpath('quote')[0]
''' extract the raw text from the body of the quote tag '''
raw_text = quote.text
''' eliminate the stuff we don't need '''
proxy_data = raw_text.split('You will definitely love it! Give it a try!</td></tr>')[1]
''' get rid of the </table> at the end of proxy_data '''
proxy_data = proxy_data[:-len('</table>')]
''' split proxy_data into rows '''
table_rows = proxy_data.split('<tr>')
''' convert each row into a Proxy object '''
for row in table_rows:
''' get rid of the </tr> at the end of each row '''
row = row[:-len('</tr>')]
''' split each row into a list of items '''
items = row.split('<td>')
''' sometimes we get weird lists containing only an empty string '''
if len(items) != 7:
continue
''' we'll use this to remove the </td> from the end of each item '''
tdlen = len('</td>')
''' create proxy dict '''
proxy = Proxy(
ip=items[1][:-tdlen],
port=int(items[2][:-tdlen]),
https=bool(items[3][:-tdlen]),
latency=int(items[4][:-tdlen]),
last_checked=items[5][:-tdlen],
country=items[6][:-tdlen],
)
yield proxy | [
"def",
"_extract_proxies",
"(",
"self",
",",
"ajax_endpoint",
")",
":",
"proxy_xml",
"=",
"requests",
".",
"get",
"(",
"ajax_endpoint",
")",
"print",
"(",
"proxy_xml",
".",
"content",
")",
"root",
"=",
"etree",
".",
"XML",
"(",
"proxy_xml",
".",
"content",... | request the xml object | [
"request",
"the",
"xml",
"object"
] | train | https://github.com/s0lst1c3/grey_harvest/blob/811e5787ce7e613bc489b8e5e475eaa8790f4d66/grey_harvest.py#L111-L156 |
s0lst1c3/grey_harvest | grey_harvest.py | GreyHarvester._passes_filter | def _passes_filter(self, proxy):
''' avoid redudant and space consuming calls to 'self' '''
''' validate proxy based on provided filters '''
if self.allowed_countries is not None and proxy['country'] not in self.allowed_countries:
return False
if self.denied_countries is not None and proxy['country'] in self.denied_countries:
return False
if self.https_only and proxy['https'] == False:
return False
if not self.all_ports and str(proxy.port) not in self.ports:
return False
return True | python | def _passes_filter(self, proxy):
''' avoid redudant and space consuming calls to 'self' '''
''' validate proxy based on provided filters '''
if self.allowed_countries is not None and proxy['country'] not in self.allowed_countries:
return False
if self.denied_countries is not None and proxy['country'] in self.denied_countries:
return False
if self.https_only and proxy['https'] == False:
return False
if not self.all_ports and str(proxy.port) not in self.ports:
return False
return True | [
"def",
"_passes_filter",
"(",
"self",
",",
"proxy",
")",
":",
"''' validate proxy based on provided filters '''",
"if",
"self",
".",
"allowed_countries",
"is",
"not",
"None",
"and",
"proxy",
"[",
"'country'",
"]",
"not",
"in",
"self",
".",
"allowed_countries",
":"... | avoid redudant and space consuming calls to 'self' | [
"avoid",
"redudant",
"and",
"space",
"consuming",
"calls",
"to",
"self"
] | train | https://github.com/s0lst1c3/grey_harvest/blob/811e5787ce7e613bc489b8e5e475eaa8790f4d66/grey_harvest.py#L158-L174 |
s0lst1c3/grey_harvest | grey_harvest.py | GreyHarvester._extract_ajax_endpoints | def _extract_ajax_endpoints(self):
''' make a GET request to freeproxylists.com/elite.html '''
url = '/'.join([DOC_ROOT, ELITE_PAGE])
response = requests.get(url)
''' extract the raw HTML doc from the response '''
raw_html = response.text
''' convert raw html into BeautifulSoup object '''
soup = BeautifulSoup(raw_html, 'lxml')
for url in soup.select('table tr td table tr td a'):
if 'elite #' in url.text:
yield '%s/load_elite_d%s' % (DOC_ROOT, url['href'].lstrip('elite/')) | python | def _extract_ajax_endpoints(self):
''' make a GET request to freeproxylists.com/elite.html '''
url = '/'.join([DOC_ROOT, ELITE_PAGE])
response = requests.get(url)
''' extract the raw HTML doc from the response '''
raw_html = response.text
''' convert raw html into BeautifulSoup object '''
soup = BeautifulSoup(raw_html, 'lxml')
for url in soup.select('table tr td table tr td a'):
if 'elite #' in url.text:
yield '%s/load_elite_d%s' % (DOC_ROOT, url['href'].lstrip('elite/')) | [
"def",
"_extract_ajax_endpoints",
"(",
"self",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"DOC_ROOT",
",",
"ELITE_PAGE",
"]",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"''' extract the raw HTML doc from the response '''",
"raw_html"... | make a GET request to freeproxylists.com/elite.html | [
"make",
"a",
"GET",
"request",
"to",
"freeproxylists",
".",
"com",
"/",
"elite",
".",
"html"
] | train | https://github.com/s0lst1c3/grey_harvest/blob/811e5787ce7e613bc489b8e5e475eaa8790f4d66/grey_harvest.py#L176-L190 |
bioasp/caspo | caspo/core/mapping.py | MappingList.iteritems | def iteritems(self):
"""
Iterates over all mappings
Yields
------
(int,Mapping)
The next pair (index, mapping)
"""
for m in self.mappings:
yield self.indexes[m.clause][m.target], m | python | def iteritems(self):
"""
Iterates over all mappings
Yields
------
(int,Mapping)
The next pair (index, mapping)
"""
for m in self.mappings:
yield self.indexes[m.clause][m.target], m | [
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"m",
"in",
"self",
".",
"mappings",
":",
"yield",
"self",
".",
"indexes",
"[",
"m",
".",
"clause",
"]",
"[",
"m",
".",
"target",
"]",
",",
"m"
] | Iterates over all mappings
Yields
------
(int,Mapping)
The next pair (index, mapping) | [
"Iterates",
"over",
"all",
"mappings"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/mapping.py#L100-L111 |
bioasp/caspo | caspo/core/mapping.py | Mapping.from_str | def from_str(cls, string):
"""
Creates a mapping from a string
Parameters
----------
string : str
String of the form `target<-clause` where `clause` is a valid string for :class:`caspo.core.clause.Clause`
Returns
-------
caspo.core.mapping.Mapping
Created object instance
"""
if "<-" not in string:
raise ValueError("Cannot parse the given string to a mapping")
target, clause_str = string.split('<-')
return cls(Clause.from_str(clause_str), target) | python | def from_str(cls, string):
"""
Creates a mapping from a string
Parameters
----------
string : str
String of the form `target<-clause` where `clause` is a valid string for :class:`caspo.core.clause.Clause`
Returns
-------
caspo.core.mapping.Mapping
Created object instance
"""
if "<-" not in string:
raise ValueError("Cannot parse the given string to a mapping")
target, clause_str = string.split('<-')
return cls(Clause.from_str(clause_str), target) | [
"def",
"from_str",
"(",
"cls",
",",
"string",
")",
":",
"if",
"\"<-\"",
"not",
"in",
"string",
":",
"raise",
"ValueError",
"(",
"\"Cannot parse the given string to a mapping\"",
")",
"target",
",",
"clause_str",
"=",
"string",
".",
"split",
"(",
"'<-'",
")",
... | Creates a mapping from a string
Parameters
----------
string : str
String of the form `target<-clause` where `clause` is a valid string for :class:`caspo.core.clause.Clause`
Returns
-------
caspo.core.mapping.Mapping
Created object instance | [
"Creates",
"a",
"mapping",
"from",
"a",
"string"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/mapping.py#L125-L144 |
PGower/PyCanvas | pycanvas/apis/logins.py | LoginsAPI.list_user_logins_users | def list_user_logins_users(self, user_id):
"""
List user logins.
Given a user ID, return that user's logins for the given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
self.logger.debug("GET /api/v1/users/{user_id}/logins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/users/{user_id}/logins".format(**path), data=data, params=params, all_pages=True) | python | def list_user_logins_users(self, user_id):
"""
List user logins.
Given a user ID, return that user's logins for the given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
self.logger.debug("GET /api/v1/users/{user_id}/logins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/users/{user_id}/logins".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_user_logins_users",
"(",
"self",
",",
"user_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"user_id\"",
"]",
"=",
"user_id",
"self",
".",
... | List user logins.
Given a user ID, return that user's logins for the given account. | [
"List",
"user",
"logins",
".",
"Given",
"a",
"user",
"ID",
"return",
"that",
"user",
"s",
"logins",
"for",
"the",
"given",
"account",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/logins.py#L35-L50 |
PGower/PyCanvas | pycanvas/apis/logins.py | LoginsAPI.create_user_login | def create_user_login(self, user_id, account_id, login_unique_id, login_authentication_provider_id=None, login_integration_id=None, login_password=None, login_sis_user_id=None):
"""
Create a user login.
Create a new login for an existing user in the given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - user[id]
"""The ID of the user to create the login for."""
data["user[id]"] = user_id
# REQUIRED - login[unique_id]
"""The unique ID for the new login."""
data["login[unique_id]"] = login_unique_id
# OPTIONAL - login[password]
"""The new login's password."""
if login_password is not None:
data["login[password]"] = login_password
# OPTIONAL - login[sis_user_id]
"""SIS ID for the login. To set this parameter, the caller must be able to
manage SIS permissions on the account."""
if login_sis_user_id is not None:
data["login[sis_user_id]"] = login_sis_user_id
# OPTIONAL - login[integration_id]
"""Integration ID for the login. To set this parameter, the caller must be able to
manage SIS permissions on the account. The Integration ID is a secondary
identifier useful for more complex SIS integrations."""
if login_integration_id is not None:
data["login[integration_id]"] = login_integration_id
# OPTIONAL - login[authentication_provider_id]
"""The authentication provider this login is associated with. Logins
associated with a specific provider can only be used with that provider.
Legacy providers (LDAP, CAS, SAML) will search for logins associated with
them, or unassociated logins. New providers will only search for logins
explicitly associated with them. This can be the integer ID of the
provider, or the type of the provider (in which case, it will find the
first matching provider)."""
if login_authentication_provider_id is not None:
data["login[authentication_provider_id]"] = login_authentication_provider_id
self.logger.debug("POST /api/v1/accounts/{account_id}/logins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/logins".format(**path), data=data, params=params, no_data=True) | python | def create_user_login(self, user_id, account_id, login_unique_id, login_authentication_provider_id=None, login_integration_id=None, login_password=None, login_sis_user_id=None):
"""
Create a user login.
Create a new login for an existing user in the given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - user[id]
"""The ID of the user to create the login for."""
data["user[id]"] = user_id
# REQUIRED - login[unique_id]
"""The unique ID for the new login."""
data["login[unique_id]"] = login_unique_id
# OPTIONAL - login[password]
"""The new login's password."""
if login_password is not None:
data["login[password]"] = login_password
# OPTIONAL - login[sis_user_id]
"""SIS ID for the login. To set this parameter, the caller must be able to
manage SIS permissions on the account."""
if login_sis_user_id is not None:
data["login[sis_user_id]"] = login_sis_user_id
# OPTIONAL - login[integration_id]
"""Integration ID for the login. To set this parameter, the caller must be able to
manage SIS permissions on the account. The Integration ID is a secondary
identifier useful for more complex SIS integrations."""
if login_integration_id is not None:
data["login[integration_id]"] = login_integration_id
# OPTIONAL - login[authentication_provider_id]
"""The authentication provider this login is associated with. Logins
associated with a specific provider can only be used with that provider.
Legacy providers (LDAP, CAS, SAML) will search for logins associated with
them, or unassociated logins. New providers will only search for logins
explicitly associated with them. This can be the integer ID of the
provider, or the type of the provider (in which case, it will find the
first matching provider)."""
if login_authentication_provider_id is not None:
data["login[authentication_provider_id]"] = login_authentication_provider_id
self.logger.debug("POST /api/v1/accounts/{account_id}/logins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/logins".format(**path), data=data, params=params, no_data=True) | [
"def",
"create_user_login",
"(",
"self",
",",
"user_id",
",",
"account_id",
",",
"login_unique_id",
",",
"login_authentication_provider_id",
"=",
"None",
",",
"login_integration_id",
"=",
"None",
",",
"login_password",
"=",
"None",
",",
"login_sis_user_id",
"=",
"No... | Create a user login.
Create a new login for an existing user in the given account. | [
"Create",
"a",
"user",
"login",
".",
"Create",
"a",
"new",
"login",
"for",
"an",
"existing",
"user",
"in",
"the",
"given",
"account",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/logins.py#L52-L104 |
PGower/PyCanvas | pycanvas/apis/logins.py | LoginsAPI.edit_user_login | def edit_user_login(self, id, account_id, login_integration_id=None, login_password=None, login_sis_user_id=None, login_unique_id=None):
"""
Edit a user login.
Update an existing login for a user in the given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - login[unique_id]
"""The new unique ID for the login."""
if login_unique_id is not None:
data["login[unique_id]"] = login_unique_id
# OPTIONAL - login[password]
"""The new password for the login. Can only be set by an admin user if admins
are allowed to change passwords for the account."""
if login_password is not None:
data["login[password]"] = login_password
# OPTIONAL - login[sis_user_id]
"""SIS ID for the login. To set this parameter, the caller must be able to
manage SIS permissions on the account."""
if login_sis_user_id is not None:
data["login[sis_user_id]"] = login_sis_user_id
# OPTIONAL - login[integration_id]
"""Integration ID for the login. To set this parameter, the caller must be able to
manage SIS permissions on the account. The Integration ID is a secondary
identifier useful for more complex SIS integrations."""
if login_integration_id is not None:
data["login[integration_id]"] = login_integration_id
self.logger.debug("PUT /api/v1/accounts/{account_id}/logins/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/accounts/{account_id}/logins/{id}".format(**path), data=data, params=params, no_data=True) | python | def edit_user_login(self, id, account_id, login_integration_id=None, login_password=None, login_sis_user_id=None, login_unique_id=None):
"""
Edit a user login.
Update an existing login for a user in the given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - login[unique_id]
"""The new unique ID for the login."""
if login_unique_id is not None:
data["login[unique_id]"] = login_unique_id
# OPTIONAL - login[password]
"""The new password for the login. Can only be set by an admin user if admins
are allowed to change passwords for the account."""
if login_password is not None:
data["login[password]"] = login_password
# OPTIONAL - login[sis_user_id]
"""SIS ID for the login. To set this parameter, the caller must be able to
manage SIS permissions on the account."""
if login_sis_user_id is not None:
data["login[sis_user_id]"] = login_sis_user_id
# OPTIONAL - login[integration_id]
"""Integration ID for the login. To set this parameter, the caller must be able to
manage SIS permissions on the account. The Integration ID is a secondary
identifier useful for more complex SIS integrations."""
if login_integration_id is not None:
data["login[integration_id]"] = login_integration_id
self.logger.debug("PUT /api/v1/accounts/{account_id}/logins/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/accounts/{account_id}/logins/{id}".format(**path), data=data, params=params, no_data=True) | [
"def",
"edit_user_login",
"(",
"self",
",",
"id",
",",
"account_id",
",",
"login_integration_id",
"=",
"None",
",",
"login_password",
"=",
"None",
",",
"login_sis_user_id",
"=",
"None",
",",
"login_unique_id",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
... | Edit a user login.
Update an existing login for a user in the given account. | [
"Edit",
"a",
"user",
"login",
".",
"Update",
"an",
"existing",
"login",
"for",
"a",
"user",
"in",
"the",
"given",
"account",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/logins.py#L106-L149 |
PGower/PyCanvas | pycanvas/apis/logins.py | LoginsAPI.delete_user_login | def delete_user_login(self, id, user_id):
"""
Delete a user login.
Delete an existing login.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
self.logger.debug("DELETE /api/v1/users/{user_id}/logins/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/{user_id}/logins/{id}".format(**path), data=data, params=params, no_data=True) | python | def delete_user_login(self, id, user_id):
"""
Delete a user login.
Delete an existing login.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
self.logger.debug("DELETE /api/v1/users/{user_id}/logins/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/{user_id}/logins/{id}".format(**path), data=data, params=params, no_data=True) | [
"def",
"delete_user_login",
"(",
"self",
",",
"id",
",",
"user_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"user_id\"",
"]",
"=",
"user_id",
"# REQU... | Delete a user login.
Delete an existing login. | [
"Delete",
"a",
"user",
"login",
".",
"Delete",
"an",
"existing",
"login",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/logins.py#L151-L170 |
PGower/PyCanvas | pycanvas/apis/quiz_questions.py | QuizQuestionsAPI.list_questions_in_quiz_or_submission | def list_questions_in_quiz_or_submission(self, quiz_id, course_id, quiz_submission_attempt=None, quiz_submission_id=None):
"""
List questions in a quiz or a submission.
Returns the list of QuizQuestions in this quiz.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# OPTIONAL - quiz_submission_id
"""If specified, the endpoint will return the questions that were presented
for that submission. This is useful if the quiz has been modified after
the submission was created and the latest quiz version's set of questions
does not match the submission's.
NOTE: you must specify quiz_submission_attempt as well if you specify this
parameter."""
if quiz_submission_id is not None:
params["quiz_submission_id"] = quiz_submission_id
# OPTIONAL - quiz_submission_attempt
"""The attempt of the submission you want the questions for."""
if quiz_submission_attempt is not None:
params["quiz_submission_attempt"] = quiz_submission_attempt
self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/questions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/questions".format(**path), data=data, params=params, all_pages=True) | python | def list_questions_in_quiz_or_submission(self, quiz_id, course_id, quiz_submission_attempt=None, quiz_submission_id=None):
"""
List questions in a quiz or a submission.
Returns the list of QuizQuestions in this quiz.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# OPTIONAL - quiz_submission_id
"""If specified, the endpoint will return the questions that were presented
for that submission. This is useful if the quiz has been modified after
the submission was created and the latest quiz version's set of questions
does not match the submission's.
NOTE: you must specify quiz_submission_attempt as well if you specify this
parameter."""
if quiz_submission_id is not None:
params["quiz_submission_id"] = quiz_submission_id
# OPTIONAL - quiz_submission_attempt
"""The attempt of the submission you want the questions for."""
if quiz_submission_attempt is not None:
params["quiz_submission_attempt"] = quiz_submission_attempt
self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/questions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/questions".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_questions_in_quiz_or_submission",
"(",
"self",
",",
"quiz_id",
",",
"course_id",
",",
"quiz_submission_attempt",
"=",
"None",
",",
"quiz_submission_id",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}"... | List questions in a quiz or a submission.
Returns the list of QuizQuestions in this quiz. | [
"List",
"questions",
"in",
"a",
"quiz",
"or",
"a",
"submission",
".",
"Returns",
"the",
"list",
"of",
"QuizQuestions",
"in",
"this",
"quiz",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quiz_questions.py#L19-L53 |
PGower/PyCanvas | pycanvas/apis/quiz_questions.py | QuizQuestionsAPI.create_single_quiz_question | def create_single_quiz_question(self, quiz_id, course_id, question_answers=None, question_correct_comments=None, question_incorrect_comments=None, question_neutral_comments=None, question_points_possible=None, question_position=None, question_question_name=None, question_question_text=None, question_question_type=None, question_quiz_group_id=None, question_text_after_answers=None):
"""
Create a single quiz question.
Create a new quiz question for this quiz
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# OPTIONAL - question[question_name]
"""The name of the question."""
if question_question_name is not None:
data["question[question_name]"] = question_question_name
# OPTIONAL - question[question_text]
"""The text of the question."""
if question_question_text is not None:
data["question[question_text]"] = question_question_text
# OPTIONAL - question[quiz_group_id]
"""The id of the quiz group to assign the question to."""
if question_quiz_group_id is not None:
data["question[quiz_group_id]"] = question_quiz_group_id
# OPTIONAL - question[question_type]
"""The type of question. Multiple optional fields depend upon the type of question to be used."""
if question_question_type is not None:
self._validate_enum(question_question_type, ["calculated_question", "essay_question", "file_upload_question", "fill_in_multiple_blanks_question", "matching_question", "multiple_answers_question", "multiple_choice_question", "multiple_dropdowns_question", "numerical_question", "short_answer_question", "text_only_question", "true_false_question"])
data["question[question_type]"] = question_question_type
# OPTIONAL - question[position]
"""The order in which the question will be displayed in the quiz in relation to other questions."""
if question_position is not None:
data["question[position]"] = question_position
# OPTIONAL - question[points_possible]
"""The maximum amount of points received for answering this question correctly."""
if question_points_possible is not None:
data["question[points_possible]"] = question_points_possible
# OPTIONAL - question[correct_comments]
"""The comment to display if the student answers the question correctly."""
if question_correct_comments is not None:
data["question[correct_comments]"] = question_correct_comments
# OPTIONAL - question[incorrect_comments]
"""The comment to display if the student answers incorrectly."""
if question_incorrect_comments is not None:
data["question[incorrect_comments]"] = question_incorrect_comments
# OPTIONAL - question[neutral_comments]
"""The comment to display regardless of how the student answered."""
if question_neutral_comments is not None:
data["question[neutral_comments]"] = question_neutral_comments
# OPTIONAL - question[text_after_answers]
"""no description"""
if question_text_after_answers is not None:
data["question[text_after_answers]"] = question_text_after_answers
# OPTIONAL - question[answers]
"""no description"""
if question_answers is not None:
data["question[answers]"] = question_answers
self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/questions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/questions".format(**path), data=data, params=params, single_item=True) | python | def create_single_quiz_question(self, quiz_id, course_id, question_answers=None, question_correct_comments=None, question_incorrect_comments=None, question_neutral_comments=None, question_points_possible=None, question_position=None, question_question_name=None, question_question_text=None, question_question_type=None, question_quiz_group_id=None, question_text_after_answers=None):
"""
Create a single quiz question.
Create a new quiz question for this quiz
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - quiz_id
"""ID"""
path["quiz_id"] = quiz_id
# OPTIONAL - question[question_name]
"""The name of the question."""
if question_question_name is not None:
data["question[question_name]"] = question_question_name
# OPTIONAL - question[question_text]
"""The text of the question."""
if question_question_text is not None:
data["question[question_text]"] = question_question_text
# OPTIONAL - question[quiz_group_id]
"""The id of the quiz group to assign the question to."""
if question_quiz_group_id is not None:
data["question[quiz_group_id]"] = question_quiz_group_id
# OPTIONAL - question[question_type]
"""The type of question. Multiple optional fields depend upon the type of question to be used."""
if question_question_type is not None:
self._validate_enum(question_question_type, ["calculated_question", "essay_question", "file_upload_question", "fill_in_multiple_blanks_question", "matching_question", "multiple_answers_question", "multiple_choice_question", "multiple_dropdowns_question", "numerical_question", "short_answer_question", "text_only_question", "true_false_question"])
data["question[question_type]"] = question_question_type
# OPTIONAL - question[position]
"""The order in which the question will be displayed in the quiz in relation to other questions."""
if question_position is not None:
data["question[position]"] = question_position
# OPTIONAL - question[points_possible]
"""The maximum amount of points received for answering this question correctly."""
if question_points_possible is not None:
data["question[points_possible]"] = question_points_possible
# OPTIONAL - question[correct_comments]
"""The comment to display if the student answers the question correctly."""
if question_correct_comments is not None:
data["question[correct_comments]"] = question_correct_comments
# OPTIONAL - question[incorrect_comments]
"""The comment to display if the student answers incorrectly."""
if question_incorrect_comments is not None:
data["question[incorrect_comments]"] = question_incorrect_comments
# OPTIONAL - question[neutral_comments]
"""The comment to display regardless of how the student answered."""
if question_neutral_comments is not None:
data["question[neutral_comments]"] = question_neutral_comments
# OPTIONAL - question[text_after_answers]
"""no description"""
if question_text_after_answers is not None:
data["question[text_after_answers]"] = question_text_after_answers
# OPTIONAL - question[answers]
"""no description"""
if question_answers is not None:
data["question[answers]"] = question_answers
self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/questions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/questions".format(**path), data=data, params=params, single_item=True) | [
"def",
"create_single_quiz_question",
"(",
"self",
",",
"quiz_id",
",",
"course_id",
",",
"question_answers",
"=",
"None",
",",
"question_correct_comments",
"=",
"None",
",",
"question_incorrect_comments",
"=",
"None",
",",
"question_neutral_comments",
"=",
"None",
",... | Create a single quiz question.
Create a new quiz question for this quiz | [
"Create",
"a",
"single",
"quiz",
"question",
".",
"Create",
"a",
"new",
"quiz",
"question",
"for",
"this",
"quiz"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quiz_questions.py#L80-L155 |
TurboGears/backlash | backlash/utils.py | escape | def escape(s, quote=False):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
:param quote: set to true to also escape double quotes.
"""
if s is None:
return ''
if hasattr(s, '__html__'):
return s.__html__()
if not isinstance(s, (text_type, binary_type)):
s = text_type(s)
if isinstance(s, binary_type):
try:
s.decode('ascii')
except:
s = s.decode('utf-8', 'replace')
s = s.replace('&', '&').replace('<', '<').replace('>', '>')
if quote:
s = s.replace('"', """)
return s | python | def escape(s, quote=False):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
:param quote: set to true to also escape double quotes.
"""
if s is None:
return ''
if hasattr(s, '__html__'):
return s.__html__()
if not isinstance(s, (text_type, binary_type)):
s = text_type(s)
if isinstance(s, binary_type):
try:
s.decode('ascii')
except:
s = s.decode('utf-8', 'replace')
s = s.replace('&', '&').replace('<', '<').replace('>', '>')
if quote:
s = s.replace('"', """)
return s | [
"def",
"escape",
"(",
"s",
",",
"quote",
"=",
"False",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"''",
"if",
"hasattr",
"(",
"s",
",",
"'__html__'",
")",
":",
"return",
"s",
".",
"__html__",
"(",
")",
"if",
"not",
"isinstance",
"(",
"s",
... | Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
:param quote: set to true to also escape double quotes. | [
"Replace",
"special",
"characters",
"&",
"<",
"and",
">",
"to",
"HTML",
"-",
"safe",
"sequences",
".",
"If",
"the",
"optional",
"flag",
"quote",
"is",
"True",
"the",
"quotation",
"mark",
"character",
"is",
"also",
"translated",
"."
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/utils.py#L8-L32 |
arcturial/clickatell-python | clickatell/http/__init__.py | Http.request | def request(self, action, data={}, headers={}, method='GET'):
"""
Append the user authentication details to every incoming request
"""
data = self.merge(data, {'user': self.username, 'password': self.password, 'api_id': self.apiId})
return Transport.request(self, action, data, headers, method) | python | def request(self, action, data={}, headers={}, method='GET'):
"""
Append the user authentication details to every incoming request
"""
data = self.merge(data, {'user': self.username, 'password': self.password, 'api_id': self.apiId})
return Transport.request(self, action, data, headers, method) | [
"def",
"request",
"(",
"self",
",",
"action",
",",
"data",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
",",
"method",
"=",
"'GET'",
")",
":",
"data",
"=",
"self",
".",
"merge",
"(",
"data",
",",
"{",
"'user'",
":",
"self",
".",
"username",
",... | Append the user authentication details to every incoming request | [
"Append",
"the",
"user",
"authentication",
"details",
"to",
"every",
"incoming",
"request"
] | train | https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/http/__init__.py#L24-L29 |
arcturial/clickatell-python | clickatell/http/__init__.py | Http.sendMessage | def sendMessage(self, to, message, extra={}):
"""
If the 'to' parameter is a single entry, we will parse it into a list.
We will merge default values into the request data and the extra parameters
provided by the user.
"""
to = to if isinstance(to, list) else [to]
to = [str(i) for i in to]
data = {'to': ','.join(to), 'text': message}
data = self.merge(data, {'callback': 7, 'mo': 1}, extra)
try:
content = self.parseLegacy(self.request('http/sendmsg', data));
except ClickatellError as e:
# The error that gets catched here will only be raised if the request was for
# one number only. We can safely assume we are only dealing with a single response
# here.
content = {'error': e.message, 'errorCode': e.code, 'To': to[0]}
# Force all responses to behave like a list, for consistency
content = content if isinstance(content, list) else [content]
result = []
# Sending messages will also result in a "stable" response. The reason
# for this is that we can't actually know if the request failed or not...a message
# that could not be delivered is different from a failed request...so errors are returned
# per message. In the case of global failures (like authentication) all messages will contain
# the specific error as part of the response body.
for index, entry in enumerate(content):
entry = self.merge({'ID': False, 'To': to[index], 'error': False, 'errorCode': False}, entry)
result.append({
'id': entry['ID'],
'destination': entry['To'],
'error': entry['error'],
'errorCode': entry['errorCode']
});
return result | python | def sendMessage(self, to, message, extra={}):
"""
If the 'to' parameter is a single entry, we will parse it into a list.
We will merge default values into the request data and the extra parameters
provided by the user.
"""
to = to if isinstance(to, list) else [to]
to = [str(i) for i in to]
data = {'to': ','.join(to), 'text': message}
data = self.merge(data, {'callback': 7, 'mo': 1}, extra)
try:
content = self.parseLegacy(self.request('http/sendmsg', data));
except ClickatellError as e:
# The error that gets catched here will only be raised if the request was for
# one number only. We can safely assume we are only dealing with a single response
# here.
content = {'error': e.message, 'errorCode': e.code, 'To': to[0]}
# Force all responses to behave like a list, for consistency
content = content if isinstance(content, list) else [content]
result = []
# Sending messages will also result in a "stable" response. The reason
# for this is that we can't actually know if the request failed or not...a message
# that could not be delivered is different from a failed request...so errors are returned
# per message. In the case of global failures (like authentication) all messages will contain
# the specific error as part of the response body.
for index, entry in enumerate(content):
entry = self.merge({'ID': False, 'To': to[index], 'error': False, 'errorCode': False}, entry)
result.append({
'id': entry['ID'],
'destination': entry['To'],
'error': entry['error'],
'errorCode': entry['errorCode']
});
return result | [
"def",
"sendMessage",
"(",
"self",
",",
"to",
",",
"message",
",",
"extra",
"=",
"{",
"}",
")",
":",
"to",
"=",
"to",
"if",
"isinstance",
"(",
"to",
",",
"list",
")",
"else",
"[",
"to",
"]",
"to",
"=",
"[",
"str",
"(",
"i",
")",
"for",
"i",
... | If the 'to' parameter is a single entry, we will parse it into a list.
We will merge default values into the request data and the extra parameters
provided by the user. | [
"If",
"the",
"to",
"parameter",
"is",
"a",
"single",
"entry",
"we",
"will",
"parse",
"it",
"into",
"a",
"list",
".",
"We",
"will",
"merge",
"default",
"values",
"into",
"the",
"request",
"data",
"and",
"the",
"extra",
"parameters",
"provided",
"by",
"the... | train | https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/http/__init__.py#L31-L69 |
arcturial/clickatell-python | clickatell/http/__init__.py | Http.stopMessage | def stopMessage(self, apiMsgId):
"""
See parent method for documentation
"""
content = self.parseLegacy(self.request('http/delmsg', {'apimsgid': apiMsgId}))
return {
'id': content['ID'],
'status': content['Status'],
'description': self.getStatus(content['Status'])
} | python | def stopMessage(self, apiMsgId):
"""
See parent method for documentation
"""
content = self.parseLegacy(self.request('http/delmsg', {'apimsgid': apiMsgId}))
return {
'id': content['ID'],
'status': content['Status'],
'description': self.getStatus(content['Status'])
} | [
"def",
"stopMessage",
"(",
"self",
",",
"apiMsgId",
")",
":",
"content",
"=",
"self",
".",
"parseLegacy",
"(",
"self",
".",
"request",
"(",
"'http/delmsg'",
",",
"{",
"'apimsgid'",
":",
"apiMsgId",
"}",
")",
")",
"return",
"{",
"'id'",
":",
"content",
... | See parent method for documentation | [
"See",
"parent",
"method",
"for",
"documentation"
] | train | https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/http/__init__.py#L78-L88 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.