repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_excel
def to_excel(self, filename, recommended_only=False, include_io=True): """ Return an Excel file for each model and dataset. Parameters ---------- filename : str or ExcelWriter object Either the file name (string) or an ExcelWriter object. recommended_only : b...
python
def to_excel(self, filename, recommended_only=False, include_io=True): """ Return an Excel file for each model and dataset. Parameters ---------- filename : str or ExcelWriter object Either the file name (string) or an ExcelWriter object. recommended_only : b...
[ "def", "to_excel", "(", "self", ",", "filename", ",", "recommended_only", "=", "False", ",", "include_io", "=", "True", ")", ":", "df", "=", "self", ".", "to_df", "(", "recommended_only", ",", "include_io", ")", "if", "isinstance", "(", "filename", ",", ...
Return an Excel file for each model and dataset. Parameters ---------- filename : str or ExcelWriter object Either the file name (string) or an ExcelWriter object. recommended_only : bool, optional If True, only recommended models for each session are included. I...
[ "Return", "an", "Excel", "file", "for", "each", "model", "and", "dataset", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L140-L164
train
Returns an Excel file for each model and dataset.
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_docx
def to_docx( self, filename=None, input_dataset=True, summary_table=True, recommendation_details=True, recommended_model=True, all_models=False, ): """ Write batch sessions to a Word file. Parameters ---------- filename...
python
def to_docx( self, filename=None, input_dataset=True, summary_table=True, recommendation_details=True, recommended_model=True, all_models=False, ): """ Write batch sessions to a Word file. Parameters ---------- filename...
[ "def", "to_docx", "(", "self", ",", "filename", "=", "None", ",", "input_dataset", "=", "True", ",", "summary_table", "=", "True", ",", "recommendation_details", "=", "True", ",", "recommended_model", "=", "True", ",", "all_models", "=", "False", ",", ")", ...
Write batch sessions to a Word file. Parameters ---------- filename : str or None If provided, the file is saved to this location, otherwise this method returns a docx.Document input_dataset : bool Include input dataset data table summary_tabl...
[ "Write", "batch", "sessions", "to", "a", "Word", "file", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L166-L215
train
Writes batch sessions to a Word file.
shapiromatron/bmds
bmds/batch.py
SessionBatch.save_plots
def save_plots(self, directory, format="png", recommended_only=False): """ Save images of dose-response curve-fits for each model. Parameters ---------- directory : str Directory where the PNG files will be saved. format : str, optional Image outp...
python
def save_plots(self, directory, format="png", recommended_only=False): """ Save images of dose-response curve-fits for each model. Parameters ---------- directory : str Directory where the PNG files will be saved. format : str, optional Image outp...
[ "def", "save_plots", "(", "self", ",", "directory", ",", "format", "=", "\"png\"", ",", "recommended_only", "=", "False", ")", ":", "for", "i", ",", "session", "in", "enumerate", "(", "self", ")", ":", "session", ".", "save_plots", "(", "directory", ",",...
Save images of dose-response curve-fits for each model. Parameters ---------- directory : str Directory where the PNG files will be saved. format : str, optional Image output format. Valid options include: png, pdf, svg, ps, eps recommended_only : bool, o...
[ "Save", "images", "of", "dose", "-", "response", "curve", "-", "fits", "for", "each", "model", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L217-L240
train
Save images of dose - response curve - fits for each session.
tjcsl/cslbot
cslbot/commands/zipcode.py
cmd
def cmd(send, msg, args): """Gets the location of a ZIP code Syntax: {command} (zipcode) Powered by STANDS4, www.stands4.com """ uid = args['config']['api']['stands4uid'] token = args['config']['api']['stands4token'] parser = arguments.ArgParser(args['config']) parser.add_argument('zipco...
python
def cmd(send, msg, args): """Gets the location of a ZIP code Syntax: {command} (zipcode) Powered by STANDS4, www.stands4.com """ uid = args['config']['api']['stands4uid'] token = args['config']['api']['stands4token'] parser = arguments.ArgParser(args['config']) parser.add_argument('zipco...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "uid", "=", "args", "[", "'config'", "]", "[", "'api'", "]", "[", "'stands4uid'", "]", "token", "=", "args", "[", "'config'", "]", "[", "'api'", "]", "[", "'stands4token'", "]", "parser"...
Gets the location of a ZIP code Syntax: {command} (zipcode) Powered by STANDS4, www.stands4.com
[ "Gets", "the", "location", "of", "a", "ZIP", "code", "Syntax", ":", "{", "command", "}", "(", "zipcode", ")", "Powered", "by", "STANDS4", "www", ".", "stands4", ".", "com" ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/zipcode.py#L27-L46
train
Gets the location of a ZIP code
adamziel/python_translate
python_translate/glue.py
TransationLoader.load_messages
def load_messages(self, directory, catalogue): """ Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError ...
python
def load_messages(self, directory, catalogue): """ Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError ...
[ "def", "load_messages", "(", "self", ",", "directory", ",", "catalogue", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "raise", "ValueError", "(", "\"{0} is not a directory\"", ".", "format", "(", "directory", ")", ")"...
Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError
[ "Loads", "translation", "found", "in", "a", "directory", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/glue.py#L37-L61
train
Loads all the messages in a directory.
adamziel/python_translate
python_translate/glue.py
TranslationWriter.disable_backup
def disable_backup(self): """ Disables dumper backup. """ for dumper in list(self.dumpers.values()): dumper.set_backup(False)
python
def disable_backup(self): """ Disables dumper backup. """ for dumper in list(self.dumpers.values()): dumper.set_backup(False)
[ "def", "disable_backup", "(", "self", ")", ":", "for", "dumper", "in", "list", "(", "self", ".", "dumpers", ".", "values", "(", ")", ")", ":", "dumper", ".", "set_backup", "(", "False", ")" ]
Disables dumper backup.
[ "Disables", "dumper", "backup", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/glue.py#L85-L90
train
Disables backup.
adamziel/python_translate
python_translate/glue.py
TranslationWriter.write_translations
def write_translations(self, catalogue, format, options={}): """ Writes translation from the catalogue according to the selected format. @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @type format: string @param format: The format to u...
python
def write_translations(self, catalogue, format, options={}): """ Writes translation from the catalogue according to the selected format. @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @type format: string @param format: The format to u...
[ "def", "write_translations", "(", "self", ",", "catalogue", ",", "format", ",", "options", "=", "{", "}", ")", ":", "if", "format", "not", "in", "self", ".", "dumpers", ":", "raise", "ValueError", "(", "'There is no dumper associated with format \"{0}\"'", ".", ...
Writes translation from the catalogue according to the selected format. @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @type format: string @param format: The format to use to dump the messages @type options: array @param options: Opt...
[ "Writes", "translation", "from", "the", "catalogue", "according", "to", "the", "selected", "format", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/glue.py#L100-L123
train
Writes the translations from the given message catalogue according to the given format.
acutesoftware/virtual-AI-simulator
scripts/recipe_finder.py
main
def main(): """ script to find a list of recipes for a group of people with specific likes and dislikes. Output of script best ingred = ['Tea', 'Tofu', 'Cheese', 'Cucumber', 'Salad', 'Chocolate'] worst ingred = ['Fish', 'Lamb', 'Pie', 'Asparagus', 'Chicken', 'Turnips'] ...
python
def main(): """ script to find a list of recipes for a group of people with specific likes and dislikes. Output of script best ingred = ['Tea', 'Tofu', 'Cheese', 'Cucumber', 'Salad', 'Chocolate'] worst ingred = ['Fish', 'Lamb', 'Pie', 'Asparagus', 'Chicken', 'Turnips'] ...
[ "def", "main", "(", ")", ":", "s", "=", "rawdata", ".", "content", ".", "DataFiles", "(", ")", "all_ingredients", "=", "list", "(", "s", ".", "get_collist_by_name", "(", "data_files", "[", "1", "]", "[", "'file'", "]", ",", "data_files", "[", "1", "]...
script to find a list of recipes for a group of people with specific likes and dislikes. Output of script best ingred = ['Tea', 'Tofu', 'Cheese', 'Cucumber', 'Salad', 'Chocolate'] worst ingred = ['Fish', 'Lamb', 'Pie', 'Asparagus', 'Chicken', 'Turnips'] Use this = Tofu ...
[ "script", "to", "find", "a", "list", "of", "recipes", "for", "a", "group", "of", "people", "with", "specific", "likes", "and", "dislikes", ".", "Output", "of", "script" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/scripts/recipe_finder.py#L32-L55
train
This script is used to find a list of recipes for a group of people with specific likes and dislikes.
tjcsl/cslbot
cslbot/commands/define.py
cmd
def cmd(send, msg, args): """Gets the definition of a word Syntax: {command} (word) Powered by STANDS4, www.stands4.com """ uid = args['config']['api']['stands4uid'] token = args['config']['api']['stands4token'] parser = arguments.ArgParser(args['config']) parser.add_argument('--entry', ...
python
def cmd(send, msg, args): """Gets the definition of a word Syntax: {command} (word) Powered by STANDS4, www.stands4.com """ uid = args['config']['api']['stands4uid'] token = args['config']['api']['stands4token'] parser = arguments.ArgParser(args['config']) parser.add_argument('--entry', ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "uid", "=", "args", "[", "'config'", "]", "[", "'api'", "]", "[", "'stands4uid'", "]", "token", "=", "args", "[", "'config'", "]", "[", "'api'", "]", "[", "'stands4token'", "]", "parser"...
Gets the definition of a word Syntax: {command} (word) Powered by STANDS4, www.stands4.com
[ "Gets", "the", "definition", "of", "a", "word", "Syntax", ":", "{", "command", "}", "(", "word", ")", "Powered", "by", "STANDS4", "www", ".", "stands4", ".", "com" ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/define.py#L27-L55
train
Gets the definition of a word
Aplopio/django_rip
rip/crud/crud_resource.py
CrudResource._setup_configuration
def _setup_configuration(self): """ All steps are accepted as classes. Instantiate them with the right configuration and set them in a local property. """ self.configuration = dict( schema_cls=self.schema_cls, allowed_actions=self.allowed_actions, ...
python
def _setup_configuration(self): """ All steps are accepted as classes. Instantiate them with the right configuration and set them in a local property. """ self.configuration = dict( schema_cls=self.schema_cls, allowed_actions=self.allowed_actions, ...
[ "def", "_setup_configuration", "(", "self", ")", ":", "self", ".", "configuration", "=", "dict", "(", "schema_cls", "=", "self", ".", "schema_cls", ",", "allowed_actions", "=", "self", ".", "allowed_actions", ",", "filter_by_fields", "=", "self", ".", "filter_...
All steps are accepted as classes. Instantiate them with the right configuration and set them in a local property.
[ "All", "steps", "are", "accepted", "as", "classes", ".", "Instantiate", "them", "with", "the", "right", "configuration", "and", "set", "them", "in", "a", "local", "property", "." ]
6b03962ccb778c1a95950a3803e5170c7a2392df
https://github.com/Aplopio/django_rip/blob/6b03962ccb778c1a95950a3803e5170c7a2392df/rip/crud/crud_resource.py#L81-L125
train
Setup the configuration for the current locale.
Aplopio/django_rip
rip/crud/crud_resource.py
CrudResource.read_detail
def read_detail(self, request): """ Implements the Read Detail (read an object) maps to GET /api/objects/:id/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.read_detail_pipeline( configuration=...
python
def read_detail(self, request): """ Implements the Read Detail (read an object) maps to GET /api/objects/:id/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.read_detail_pipeline( configuration=...
[ "def", "read_detail", "(", "self", ",", "request", ")", ":", "pipeline", "=", "crud_pipeline_factory", ".", "read_detail_pipeline", "(", "configuration", "=", "self", ".", "configuration", ")", "return", "pipeline", "(", "request", "=", "request", ")" ]
Implements the Read Detail (read an object) maps to GET /api/objects/:id/ in rest semantics :param request: rip.Request :return: rip.Response
[ "Implements", "the", "Read", "Detail", "(", "read", "an", "object", ")" ]
6b03962ccb778c1a95950a3803e5170c7a2392df
https://github.com/Aplopio/django_rip/blob/6b03962ccb778c1a95950a3803e5170c7a2392df/rip/crud/crud_resource.py#L153-L163
train
Implements the Read Detail ( read an object
Aplopio/django_rip
rip/crud/crud_resource.py
CrudResource.update_detail
def update_detail(self, request): """ Implements the Update Detail (partially update an object) maps to PATCH /api/object/:id/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.update_detail_pipeline( ...
python
def update_detail(self, request): """ Implements the Update Detail (partially update an object) maps to PATCH /api/object/:id/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.update_detail_pipeline( ...
[ "def", "update_detail", "(", "self", ",", "request", ")", ":", "pipeline", "=", "crud_pipeline_factory", ".", "update_detail_pipeline", "(", "configuration", "=", "self", ".", "configuration", ")", "return", "pipeline", "(", "request", "=", "request", ")" ]
Implements the Update Detail (partially update an object) maps to PATCH /api/object/:id/ in rest semantics :param request: rip.Request :return: rip.Response
[ "Implements", "the", "Update", "Detail", "(", "partially", "update", "an", "object", ")" ]
6b03962ccb778c1a95950a3803e5170c7a2392df
https://github.com/Aplopio/django_rip/blob/6b03962ccb778c1a95950a3803e5170c7a2392df/rip/crud/crud_resource.py#L166-L176
train
Implements the Update Detail API.
Aplopio/django_rip
rip/crud/crud_resource.py
CrudResource.read_list
def read_list(self, request): """ Implements the List read (get a list of objects) maps to GET /api/objects/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.read_list_pipeline( configuration=sel...
python
def read_list(self, request): """ Implements the List read (get a list of objects) maps to GET /api/objects/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.read_list_pipeline( configuration=sel...
[ "def", "read_list", "(", "self", ",", "request", ")", ":", "pipeline", "=", "crud_pipeline_factory", ".", "read_list_pipeline", "(", "configuration", "=", "self", ".", "configuration", ")", "return", "pipeline", "(", "request", "=", "request", ")" ]
Implements the List read (get a list of objects) maps to GET /api/objects/ in rest semantics :param request: rip.Request :return: rip.Response
[ "Implements", "the", "List", "read", "(", "get", "a", "list", "of", "objects", ")" ]
6b03962ccb778c1a95950a3803e5170c7a2392df
https://github.com/Aplopio/django_rip/blob/6b03962ccb778c1a95950a3803e5170c7a2392df/rip/crud/crud_resource.py#L179-L189
train
Implements the List read
Aplopio/django_rip
rip/crud/crud_resource.py
CrudResource.create_detail
def create_detail(self, request): """ Implements the Create Detail (create an object) maps to POST /api/objects/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.create_detail_pipeline( configura...
python
def create_detail(self, request): """ Implements the Create Detail (create an object) maps to POST /api/objects/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.create_detail_pipeline( configura...
[ "def", "create_detail", "(", "self", ",", "request", ")", ":", "pipeline", "=", "crud_pipeline_factory", ".", "create_detail_pipeline", "(", "configuration", "=", "self", ".", "configuration", ")", "return", "pipeline", "(", "request", "=", "request", ")" ]
Implements the Create Detail (create an object) maps to POST /api/objects/ in rest semantics :param request: rip.Request :return: rip.Response
[ "Implements", "the", "Create", "Detail", "(", "create", "an", "object", ")" ]
6b03962ccb778c1a95950a3803e5170c7a2392df
https://github.com/Aplopio/django_rip/blob/6b03962ccb778c1a95950a3803e5170c7a2392df/rip/crud/crud_resource.py#L192-L202
train
Implements the Create Detail API.
Aplopio/django_rip
rip/crud/crud_resource.py
CrudResource.delete_detail
def delete_detail(self, request): """ Implements the Delete Detail (delete an object) maps to DELETE /api/object_name/:id/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.delete_detail_pipeline( ...
python
def delete_detail(self, request): """ Implements the Delete Detail (delete an object) maps to DELETE /api/object_name/:id/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.delete_detail_pipeline( ...
[ "def", "delete_detail", "(", "self", ",", "request", ")", ":", "pipeline", "=", "crud_pipeline_factory", ".", "delete_detail_pipeline", "(", "configuration", "=", "self", ".", "configuration", ")", "return", "pipeline", "(", "request", "=", "request", ")" ]
Implements the Delete Detail (delete an object) maps to DELETE /api/object_name/:id/ in rest semantics :param request: rip.Request :return: rip.Response
[ "Implements", "the", "Delete", "Detail", "(", "delete", "an", "object", ")" ]
6b03962ccb778c1a95950a3803e5170c7a2392df
https://github.com/Aplopio/django_rip/blob/6b03962ccb778c1a95950a3803e5170c7a2392df/rip/crud/crud_resource.py#L205-L215
train
This method is used to delete an object from the resource store. It is used to delete an object from the resource store.
Aplopio/django_rip
rip/crud/crud_resource.py
CrudResource.get_aggregates
def get_aggregates(self, request): """ Implements the Get aggregates (total number of objects filtered) maps to PATCH /api/object_name/get_aggregates/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.get_agg...
python
def get_aggregates(self, request): """ Implements the Get aggregates (total number of objects filtered) maps to PATCH /api/object_name/get_aggregates/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.get_agg...
[ "def", "get_aggregates", "(", "self", ",", "request", ")", ":", "pipeline", "=", "crud_pipeline_factory", ".", "get_aggregates_pipeline", "(", "configuration", "=", "self", ".", "configuration", ")", "return", "pipeline", "(", "request", "=", "request", ")" ]
Implements the Get aggregates (total number of objects filtered) maps to PATCH /api/object_name/get_aggregates/ in rest semantics :param request: rip.Request :return: rip.Response
[ "Implements", "the", "Get", "aggregates", "(", "total", "number", "of", "objects", "filtered", ")" ]
6b03962ccb778c1a95950a3803e5170c7a2392df
https://github.com/Aplopio/django_rip/blob/6b03962ccb778c1a95950a3803e5170c7a2392df/rip/crud/crud_resource.py#L218-L229
train
Implements the Get aggregates endpoint.
Aplopio/django_rip
rip/crud/crud_resource.py
CrudResource.create_or_update_detail
def create_or_update_detail(self, request): """ Implements Create/Update an object completely given an id maps to PUT /api/object/:id in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.create_or_update_detail_pipe...
python
def create_or_update_detail(self, request): """ Implements Create/Update an object completely given an id maps to PUT /api/object/:id in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.create_or_update_detail_pipe...
[ "def", "create_or_update_detail", "(", "self", ",", "request", ")", ":", "pipeline", "=", "crud_pipeline_factory", ".", "create_or_update_detail_pipeline", "(", "configuration", "=", "self", ".", "configuration", ")", "return", "pipeline", "(", "request", "=", "requ...
Implements Create/Update an object completely given an id maps to PUT /api/object/:id in rest semantics :param request: rip.Request :return: rip.Response
[ "Implements", "Create", "/", "Update", "an", "object", "completely", "given", "an", "id" ]
6b03962ccb778c1a95950a3803e5170c7a2392df
https://github.com/Aplopio/django_rip/blob/6b03962ccb778c1a95950a3803e5170c7a2392df/rip/crud/crud_resource.py#L232-L244
train
Implements Create or Update an object completely given an id maps to PUT / api / object/:id in rest semantics MF does not implement Create or Update
Xion/taipan
taipan/algorithms.py
batch
def batch(iterable, n, fillvalue=None): """Batches the elements of given iterable. Resulting iterable will yield tuples containing at most ``n`` elements (might be less if ``fillvalue`` isn't specified). :param n: Number of items in every batch :param fillvalue: Value to fill the last batch with. ...
python
def batch(iterable, n, fillvalue=None): """Batches the elements of given iterable. Resulting iterable will yield tuples containing at most ``n`` elements (might be less if ``fillvalue`` isn't specified). :param n: Number of items in every batch :param fillvalue: Value to fill the last batch with. ...
[ "def", "batch", "(", "iterable", ",", "n", ",", "fillvalue", "=", "None", ")", ":", "ensure_iterable", "(", "iterable", ")", "if", "not", "isinstance", "(", "n", ",", "Integral", ")", ":", "raise", "TypeError", "(", "\"invalid number of elements in a batch\"",...
Batches the elements of given iterable. Resulting iterable will yield tuples containing at most ``n`` elements (might be less if ``fillvalue`` isn't specified). :param n: Number of items in every batch :param fillvalue: Value to fill the last batch with. If None, last batch might...
[ "Batches", "the", "elements", "of", "given", "iterable", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L24-L58
train
Returns an iterable of n batches of the given iterable.
Xion/taipan
taipan/algorithms.py
cycle
def cycle(iterable, n=None): """Cycle through given iterable specific (or infinite) number of times. :param n: Number of cycles. If None, result cycles through ``iterable`` indefinitely. :return: Iterable that cycles through given one .. note:: This is an extended version of nc...
python
def cycle(iterable, n=None): """Cycle through given iterable specific (or infinite) number of times. :param n: Number of cycles. If None, result cycles through ``iterable`` indefinitely. :return: Iterable that cycles through given one .. note:: This is an extended version of nc...
[ "def", "cycle", "(", "iterable", ",", "n", "=", "None", ")", ":", "ensure_iterable", "(", "iterable", ")", "if", "n", "is", "None", ":", "return", "cycle_", "(", "iterable", ")", "else", ":", "if", "not", "isinstance", "(", "n", ",", "Integral", ")",...
Cycle through given iterable specific (or infinite) number of times. :param n: Number of cycles. If None, result cycles through ``iterable`` indefinitely. :return: Iterable that cycles through given one .. note:: This is an extended version of ncycles() recipe from the :mod...
[ "Cycle", "through", "given", "iterable", "specific", "(", "or", "infinite", ")", "number", "of", "times", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L61-L85
train
Cycle through given iterable n times.
Xion/taipan
taipan/algorithms.py
intertwine
def intertwine(*iterables): """Constructs an iterable which intertwines given iterables. The resulting iterable will return an item from first sequence, then from second, etc. until the last one - and then another item from first, then from second, etc. - up until all iterables are exhausted. """ ...
python
def intertwine(*iterables): """Constructs an iterable which intertwines given iterables. The resulting iterable will return an item from first sequence, then from second, etc. until the last one - and then another item from first, then from second, etc. - up until all iterables are exhausted. """ ...
[ "def", "intertwine", "(", "*", "iterables", ")", ":", "iterables", "=", "tuple", "(", "imap", "(", "ensure_iterable", ",", "iterables", ")", ")", "empty", "=", "object", "(", ")", "return", "(", "item", "for", "iterable", "in", "izip_longest", "(", "*", ...
Constructs an iterable which intertwines given iterables. The resulting iterable will return an item from first sequence, then from second, etc. until the last one - and then another item from first, then from second, etc. - up until all iterables are exhausted.
[ "Constructs", "an", "iterable", "which", "intertwines", "given", "iterables", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L88-L100
train
Constructs an iterable which intertwines given iterables.
Xion/taipan
taipan/algorithms.py
iterate
def iterate(iterator, n=None): """Efficiently advances the iterator N times; by default goes to its end. The actual loop is done "in C" and hence it is faster than equivalent 'for'. :param n: How much the iterator should be advanced. If None, it will be advanced until the end. """ en...
python
def iterate(iterator, n=None): """Efficiently advances the iterator N times; by default goes to its end. The actual loop is done "in C" and hence it is faster than equivalent 'for'. :param n: How much the iterator should be advanced. If None, it will be advanced until the end. """ en...
[ "def", "iterate", "(", "iterator", ",", "n", "=", "None", ")", ":", "ensure_iterable", "(", "iterator", ")", "if", "n", "is", "None", ":", "deque", "(", "iterator", ",", "maxlen", "=", "0", ")", "else", ":", "next", "(", "islice", "(", "iterator", ...
Efficiently advances the iterator N times; by default goes to its end. The actual loop is done "in C" and hence it is faster than equivalent 'for'. :param n: How much the iterator should be advanced. If None, it will be advanced until the end.
[ "Efficiently", "advances", "the", "iterator", "N", "times", ";", "by", "default", "goes", "to", "its", "end", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L103-L115
train
Efficiently advances the iterator N times ; by default goes to its end.
Xion/taipan
taipan/algorithms.py
unique
def unique(iterable, key=None): """Removes duplicates from given iterable, using given key as criterion. :param key: Key function which returns a hashable, uniquely identifying an object. :return: Iterable with duplicates removed """ ensure_iterable(iterable) key = hash if key ...
python
def unique(iterable, key=None): """Removes duplicates from given iterable, using given key as criterion. :param key: Key function which returns a hashable, uniquely identifying an object. :return: Iterable with duplicates removed """ ensure_iterable(iterable) key = hash if key ...
[ "def", "unique", "(", "iterable", ",", "key", "=", "None", ")", ":", "ensure_iterable", "(", "iterable", ")", "key", "=", "hash", "if", "key", "is", "None", "else", "ensure_callable", "(", "key", ")", "def", "generator", "(", ")", ":", "seen", "=", "...
Removes duplicates from given iterable, using given key as criterion. :param key: Key function which returns a hashable, uniquely identifying an object. :return: Iterable with duplicates removed
[ "Removes", "duplicates", "from", "given", "iterable", "using", "given", "key", "as", "criterion", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L130-L149
train
Removes duplicates from given iterable using given key as criterion.
Xion/taipan
taipan/algorithms.py
breadth_first
def breadth_first(start, expand): """Performs a breadth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the BFS order ...
python
def breadth_first(start, expand): """Performs a breadth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the BFS order ...
[ "def", "breadth_first", "(", "start", ",", "expand", ")", ":", "ensure_callable", "(", "expand", ")", "def", "generator", "(", ")", ":", "queue", "=", "deque", "(", "[", "start", "]", ")", "while", "queue", ":", "node", "=", "queue", ".", "popleft", ...
Performs a breadth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the BFS order Example:: tree = json.loads(som...
[ "Performs", "a", "breadth", "-", "first", "search", "of", "a", "graph", "-", "like", "structure", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L154-L178
train
Perform a breadth - first search of a graph - like structure.
Xion/taipan
taipan/algorithms.py
depth_first
def depth_first(start, descend): """Performs a depth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the DFS order Ex...
python
def depth_first(start, descend): """Performs a depth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the DFS order Ex...
[ "def", "depth_first", "(", "start", ",", "descend", ")", ":", "ensure_callable", "(", "descend", ")", "def", "generator", "(", ")", ":", "stack", "=", "[", "start", "]", "while", "stack", ":", "node", "=", "stack", ".", "pop", "(", ")", "yield", "nod...
Performs a depth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the DFS order Example:: for node in depth_first...
[ "Performs", "a", "depth", "-", "first", "search", "of", "a", "graph", "-", "like", "structure", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L181-L204
train
Performs a depth - first search of a graph - like structure.
Xion/taipan
taipan/algorithms.py
topological_order
def topological_order(nodes, incoming): """Performs topological sort of a DAG-like structure (directed acyclic graph). :param nodes: Collection of nodes :param incoming: Function taking node as an argument and returning iterable of nodes with edges pointing _towards_ given one ...
python
def topological_order(nodes, incoming): """Performs topological sort of a DAG-like structure (directed acyclic graph). :param nodes: Collection of nodes :param incoming: Function taking node as an argument and returning iterable of nodes with edges pointing _towards_ given one ...
[ "def", "topological_order", "(", "nodes", ",", "incoming", ")", ":", "ensure_iterable", "(", "nodes", ")", "ensure_countable", "(", "nodes", ")", "ensure_callable", "(", "incoming", ")", "# data structure for tracking node's visit state", "NOT_VISITED", ",", "VISITING",...
Performs topological sort of a DAG-like structure (directed acyclic graph). :param nodes: Collection of nodes :param incoming: Function taking node as an argument and returning iterable of nodes with edges pointing _towards_ given one :return: Iterable of nodes in the topological ...
[ "Performs", "topological", "sort", "of", "a", "DAG", "-", "like", "structure", "(", "directed", "acyclic", "graph", ")", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L207-L267
train
Returns an iterable of nodes in the topological order of a DAG - like structure.
maximkulkin/hypothesis-regex
hypothesis_regex.py
regex
def regex(regex): """Return strategy that generates strings that match given regex. Regex can be either a string or compiled regex (through `re.compile()`). You can use regex flags (such as `re.IGNORECASE`, `re.DOTALL` or `re.UNICODE`) to control generation. Flags can be passed either in compiled rege...
python
def regex(regex): """Return strategy that generates strings that match given regex. Regex can be either a string or compiled regex (through `re.compile()`). You can use regex flags (such as `re.IGNORECASE`, `re.DOTALL` or `re.UNICODE`) to control generation. Flags can be passed either in compiled rege...
[ "def", "regex", "(", "regex", ")", ":", "if", "not", "hasattr", "(", "regex", ",", "'pattern'", ")", ":", "regex", "=", "re", ".", "compile", "(", "regex", ")", "pattern", "=", "regex", ".", "pattern", "flags", "=", "regex", ".", "flags", "codes", ...
Return strategy that generates strings that match given regex. Regex can be either a string or compiled regex (through `re.compile()`). You can use regex flags (such as `re.IGNORECASE`, `re.DOTALL` or `re.UNICODE`) to control generation. Flags can be passed either in compiled regex (specify flags in c...
[ "Return", "strategy", "that", "generates", "strings", "that", "match", "given", "regex", "." ]
dd139e97f5ef555dc61e9636bbe96558a5c7801f
https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L144-L167
train
Return strategy that generates strings that match given regex.
maximkulkin/hypothesis-regex
hypothesis_regex.py
_strategy
def _strategy(codes, context): """ Convert SRE regex parse tree to strategy that generates strings matching that regex represented by that parse tree. `codes` is either a list of SRE regex elements representations or a particular element representation. Each element is a tuple of element code (as s...
python
def _strategy(codes, context): """ Convert SRE regex parse tree to strategy that generates strings matching that regex represented by that parse tree. `codes` is either a list of SRE regex elements representations or a particular element representation. Each element is a tuple of element code (as s...
[ "def", "_strategy", "(", "codes", ",", "context", ")", ":", "if", "not", "isinstance", "(", "codes", ",", "tuple", ")", ":", "# List of codes", "strategies", "=", "[", "]", "i", "=", "0", "while", "i", "<", "len", "(", "codes", ")", ":", "if", "cod...
Convert SRE regex parse tree to strategy that generates strings matching that regex represented by that parse tree. `codes` is either a list of SRE regex elements representations or a particular element representation. Each element is a tuple of element code (as string) and parameters. E.g. regex 'ab[0...
[ "Convert", "SRE", "regex", "parse", "tree", "to", "strategy", "that", "generates", "strings", "matching", "that", "regex", "represented", "by", "that", "parse", "tree", "." ]
dd139e97f5ef555dc61e9636bbe96558a5c7801f
https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L170-L329
train
Convert SRE regex parse tree to strategy that generates strings matching that regex represented by that parse tree.
maximkulkin/hypothesis-regex
hypothesis_regex.py
CharactersBuilder.strategy
def strategy(self): 'Returns resulting strategy that generates configured char set' max_codepoint = None if self._unicode else 127 strategies = [] if self._negate: if self._categories or self._whitelist_chars: strategies.append( hs.charact...
python
def strategy(self): 'Returns resulting strategy that generates configured char set' max_codepoint = None if self._unicode else 127 strategies = [] if self._negate: if self._categories or self._whitelist_chars: strategies.append( hs.charact...
[ "def", "strategy", "(", "self", ")", ":", "max_codepoint", "=", "None", "if", "self", ".", "_unicode", "else", "127", "strategies", "=", "[", "]", "if", "self", ".", "_negate", ":", "if", "self", ".", "_categories", "or", "self", ".", "_whitelist_chars",...
Returns resulting strategy that generates configured char set
[ "Returns", "resulting", "strategy", "that", "generates", "configured", "char", "set" ]
dd139e97f5ef555dc61e9636bbe96558a5c7801f
https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L63-L99
train
Returns resulting strategy that generates configured char set
maximkulkin/hypothesis-regex
hypothesis_regex.py
CharactersBuilder.add_category
def add_category(self, category): ''' Add unicode category to set Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc. See `unicodedata.category()` ''' if category == sre.CATEGORY_DIGIT: self._categories |= UNICODE_DIGIT_CATEGORIES elif category...
python
def add_category(self, category): ''' Add unicode category to set Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc. See `unicodedata.category()` ''' if category == sre.CATEGORY_DIGIT: self._categories |= UNICODE_DIGIT_CATEGORIES elif category...
[ "def", "add_category", "(", "self", ",", "category", ")", ":", "if", "category", "==", "sre", ".", "CATEGORY_DIGIT", ":", "self", ".", "_categories", "|=", "UNICODE_DIGIT_CATEGORIES", "elif", "category", "==", "sre", ".", "CATEGORY_NOT_DIGIT", ":", "self", "."...
Add unicode category to set Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc. See `unicodedata.category()`
[ "Add", "unicode", "category", "to", "set" ]
dd139e97f5ef555dc61e9636bbe96558a5c7801f
https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L101-L131
train
Add unicode category to set of unicode categories.
maximkulkin/hypothesis-regex
hypothesis_regex.py
CharactersBuilder.add_chars
def add_chars(self, chars): 'Add given chars to char set' for c in chars: if self._ignorecase: self._whitelist_chars.add(c.lower()) self._whitelist_chars.add(c.upper()) else: self._whitelist_chars.add(c)
python
def add_chars(self, chars): 'Add given chars to char set' for c in chars: if self._ignorecase: self._whitelist_chars.add(c.lower()) self._whitelist_chars.add(c.upper()) else: self._whitelist_chars.add(c)
[ "def", "add_chars", "(", "self", ",", "chars", ")", ":", "for", "c", "in", "chars", ":", "if", "self", ".", "_ignorecase", ":", "self", ".", "_whitelist_chars", ".", "add", "(", "c", ".", "lower", "(", ")", ")", "self", ".", "_whitelist_chars", ".", ...
Add given chars to char set
[ "Add", "given", "chars", "to", "char", "set" ]
dd139e97f5ef555dc61e9636bbe96558a5c7801f
https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L133-L140
train
Add given chars to char set
intuition-io/insights
insights/plugins/mobile.py
push_to_android
def push_to_android(api_key, device_id, payload, push_type): ''' Push android notification through www.pushbullet.com ''' payload['type'] = push_type payload['device_id'] = device_id return requests.post('https://api.pushbullet.com/api/pushes', data=payload, ...
python
def push_to_android(api_key, device_id, payload, push_type): ''' Push android notification through www.pushbullet.com ''' payload['type'] = push_type payload['device_id'] = device_id return requests.post('https://api.pushbullet.com/api/pushes', data=payload, ...
[ "def", "push_to_android", "(", "api_key", ",", "device_id", ",", "payload", ",", "push_type", ")", ":", "payload", "[", "'type'", "]", "=", "push_type", "payload", "[", "'device_id'", "]", "=", "device_id", "return", "requests", ".", "post", "(", "'https://a...
Push android notification through www.pushbullet.com
[ "Push", "android", "notification", "through", "www", ".", "pushbullet", ".", "com" ]
a4eae53a1886164db96751d2b0964aa2acb7c2d7
https://github.com/intuition-io/insights/blob/a4eae53a1886164db96751d2b0964aa2acb7c2d7/insights/plugins/mobile.py#L22-L28
train
Push to Android
intuition-io/insights
insights/plugins/mobile.py
AndroidPush._device_lookup
def _device_lookup(self, device_name): ''' Request informations about <name> device ''' device_found = {} response = requests.get(self._api_url + 'devices', auth=(self._api_key, '')) if response.ok: for device in response.json()['devices']: ...
python
def _device_lookup(self, device_name): ''' Request informations about <name> device ''' device_found = {} response = requests.get(self._api_url + 'devices', auth=(self._api_key, '')) if response.ok: for device in response.json()['devices']: ...
[ "def", "_device_lookup", "(", "self", ",", "device_name", ")", ":", "device_found", "=", "{", "}", "response", "=", "requests", ".", "get", "(", "self", ".", "_api_url", "+", "'devices'", ",", "auth", "=", "(", "self", ".", "_api_key", ",", "''", ")", ...
Request informations about <name> device
[ "Request", "informations", "about", "<name", ">", "device" ]
a4eae53a1886164db96751d2b0964aa2acb7c2d7
https://github.com/intuition-io/insights/blob/a4eae53a1886164db96751d2b0964aa2acb7c2d7/insights/plugins/mobile.py#L51-L61
train
Request informations about a device
intuition-io/insights
insights/plugins/mobile.py
AndroidPush._watchdog
def _watchdog(self): ''' Notifications are stopped if * The last one was too close * We reach a rated limit ''' too_early = (time.time() - self._last_time < self._min_interval) too_much = (self._count >= self._rate_limit) return (False if (too_early or too_much) else ...
python
def _watchdog(self): ''' Notifications are stopped if * The last one was too close * We reach a rated limit ''' too_early = (time.time() - self._last_time < self._min_interval) too_much = (self._count >= self._rate_limit) return (False if (too_early or too_much) else ...
[ "def", "_watchdog", "(", "self", ")", ":", "too_early", "=", "(", "time", ".", "time", "(", ")", "-", "self", ".", "_last_time", "<", "self", ".", "_min_interval", ")", "too_much", "=", "(", "self", ".", "_count", ">=", "self", ".", "_rate_limit", ")...
Notifications are stopped if * The last one was too close * We reach a rated limit
[ "Notifications", "are", "stopped", "if", "*", "The", "last", "one", "was", "too", "close", "*", "We", "reach", "a", "rated", "limit" ]
a4eae53a1886164db96751d2b0964aa2acb7c2d7
https://github.com/intuition-io/insights/blob/a4eae53a1886164db96751d2b0964aa2acb7c2d7/insights/plugins/mobile.py#L89-L95
train
Check if we should stop the timer and return a boolean indicating if we should stop the timer.
jeffh/describe
describe/spec/utils.py
str_traceback
def str_traceback(error, tb): """Returns a string representation of the traceback. """ if not isinstance(tb, types.TracebackType): return tb return ''.join(traceback.format_exception(error.__class__, error, tb))
python
def str_traceback(error, tb): """Returns a string representation of the traceback. """ if not isinstance(tb, types.TracebackType): return tb return ''.join(traceback.format_exception(error.__class__, error, tb))
[ "def", "str_traceback", "(", "error", ",", "tb", ")", ":", "if", "not", "isinstance", "(", "tb", ",", "types", ".", "TracebackType", ")", ":", "return", "tb", "return", "''", ".", "join", "(", "traceback", ".", "format_exception", "(", "error", ".", "_...
Returns a string representation of the traceback.
[ "Returns", "a", "string", "representation", "of", "the", "traceback", "." ]
6a33ffecc3340b57e60bc8a7095521882ff9a156
https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/utils.py#L9-L15
train
Returns a string representation of the traceback.
jeffh/describe
describe/spec/utils.py
filter_traceback
def filter_traceback(error, tb, ignore_pkg=CURRENT_PACKAGE): """Filtered out all parent stacktraces starting with the given stacktrace that has a given variable name in its globals. """ if not isinstance(tb, types.TracebackType): return tb def in_namespace(n): return n and (n.starts...
python
def filter_traceback(error, tb, ignore_pkg=CURRENT_PACKAGE): """Filtered out all parent stacktraces starting with the given stacktrace that has a given variable name in its globals. """ if not isinstance(tb, types.TracebackType): return tb def in_namespace(n): return n and (n.starts...
[ "def", "filter_traceback", "(", "error", ",", "tb", ",", "ignore_pkg", "=", "CURRENT_PACKAGE", ")", ":", "if", "not", "isinstance", "(", "tb", ",", "types", ".", "TracebackType", ")", ":", "return", "tb", "def", "in_namespace", "(", "n", ")", ":", "retur...
Filtered out all parent stacktraces starting with the given stacktrace that has a given variable name in its globals.
[ "Filtered", "out", "all", "parent", "stacktraces", "starting", "with", "the", "given", "stacktrace", "that", "has", "a", "given", "variable", "name", "in", "its", "globals", "." ]
6a33ffecc3340b57e60bc8a7095521882ff9a156
https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/utils.py#L17-L35
train
Filter out all parent stacktraces starting with the given stacktrace that has a given variable name in its globals.
jeffh/describe
describe/spec/utils.py
get_true_function
def get_true_function(obj): "Returns the actual function and a boolean indicated if this is a method or not." if not callable(obj): raise TypeError("%r is not callable." % (obj,)) ismethod = inspect.ismethod(obj) if inspect.isfunction(obj) or ismethod: return obj, ismethod if hasattr...
python
def get_true_function(obj): "Returns the actual function and a boolean indicated if this is a method or not." if not callable(obj): raise TypeError("%r is not callable." % (obj,)) ismethod = inspect.ismethod(obj) if inspect.isfunction(obj) or ismethod: return obj, ismethod if hasattr...
[ "def", "get_true_function", "(", "obj", ")", ":", "if", "not", "callable", "(", "obj", ")", ":", "raise", "TypeError", "(", "\"%r is not callable.\"", "%", "(", "obj", ",", ")", ")", "ismethod", "=", "inspect", ".", "ismethod", "(", "obj", ")", "if", "...
Returns the actual function and a boolean indicated if this is a method or not.
[ "Returns", "the", "actual", "function", "and", "a", "boolean", "indicated", "if", "this", "is", "a", "method", "or", "not", "." ]
6a33ffecc3340b57e60bc8a7095521882ff9a156
https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/utils.py#L151-L166
train
Returns the actual function and a boolean indicated if this is a method or not.
adamziel/python_translate
python_translate/loaders.py
FileMixin.assert_valid_path
def assert_valid_path(self, path): """ Ensures that the path represents an existing file @type path: str @param path: path to check """ if not isinstance(path, str): raise NotFoundResourceException( "Resource passed to load() method must be a...
python
def assert_valid_path(self, path): """ Ensures that the path represents an existing file @type path: str @param path: path to check """ if not isinstance(path, str): raise NotFoundResourceException( "Resource passed to load() method must be a...
[ "def", "assert_valid_path", "(", "self", ",", "path", ")", ":", "if", "not", "isinstance", "(", "path", ",", "str", ")", ":", "raise", "NotFoundResourceException", "(", "\"Resource passed to load() method must be a file path\"", ")", "if", "not", "os", ".", "path"...
Ensures that the path represents an existing file @type path: str @param path: path to check
[ "Ensures", "that", "the", "path", "represents", "an", "existing", "file" ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L63-L77
train
Ensures that the path represents an existing file and that the file exists.
adamziel/python_translate
python_translate/loaders.py
FileMixin.read_file
def read_file(self, path): """ Reads a file into memory and returns it's contents @type path: str @param path: path to load """ self.assert_valid_path(path) with open(path, 'rb') as file: contents = file.read().decode('UTF-8') return conten...
python
def read_file(self, path): """ Reads a file into memory and returns it's contents @type path: str @param path: path to load """ self.assert_valid_path(path) with open(path, 'rb') as file: contents = file.read().decode('UTF-8') return conten...
[ "def", "read_file", "(", "self", ",", "path", ")", ":", "self", ".", "assert_valid_path", "(", "path", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "file", ":", "contents", "=", "file", ".", "read", "(", ")", ".", "decode", "(", "'UTF-...
Reads a file into memory and returns it's contents @type path: str @param path: path to load
[ "Reads", "a", "file", "into", "memory", "and", "returns", "it", "s", "contents" ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L79-L92
train
Reads a file into memory and returns it s contents
adamziel/python_translate
python_translate/loaders.py
FileMixin.rethrow
def rethrow(self, msg, _type=InvalidResourceException): """ Raises an exception with custom type and modified error message. Raised exception is based on current exc_info() and carries it's traceback @type msg: str @param msg: New error message @type _type: type ...
python
def rethrow(self, msg, _type=InvalidResourceException): """ Raises an exception with custom type and modified error message. Raised exception is based on current exc_info() and carries it's traceback @type msg: str @param msg: New error message @type _type: type ...
[ "def", "rethrow", "(", "self", ",", "msg", ",", "_type", "=", "InvalidResourceException", ")", ":", "exc_type", ",", "exc_value", ",", "exc_traceback", "=", "sys", ".", "exc_info", "(", ")", "msg", "=", "msg", "+", "\"\\nOriginal message: {0} {1}\"", ".", "f...
Raises an exception with custom type and modified error message. Raised exception is based on current exc_info() and carries it's traceback @type msg: str @param msg: New error message @type _type: type @param _type: Reraised exception type @raises: Exception
[ "Raises", "an", "exception", "with", "custom", "type", "and", "modified", "error", "message", ".", "Raised", "exception", "is", "based", "on", "current", "exc_info", "()", "and", "carries", "it", "s", "traceback" ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L94-L110
train
Raises an exception with custom type and modified error message.
adamziel/python_translate
python_translate/loaders.py
DictLoader.flatten
def flatten(self, messages, parent_key=''): """ Flattens an nested array of translations. The scheme used is: 'key' => array('key2' => array('key3' => 'value')) Becomes: 'key.key2.key3' => 'value' This function takes an array by reference and will modify it ...
python
def flatten(self, messages, parent_key=''): """ Flattens an nested array of translations. The scheme used is: 'key' => array('key2' => array('key3' => 'value')) Becomes: 'key.key2.key3' => 'value' This function takes an array by reference and will modify it ...
[ "def", "flatten", "(", "self", ",", "messages", ",", "parent_key", "=", "''", ")", ":", "items", "=", "[", "]", "sep", "=", "'.'", "for", "k", ",", "v", "in", "list", "(", "messages", ".", "items", "(", ")", ")", ":", "new_key", "=", "\"{0}{1}{2}...
Flattens an nested array of translations. The scheme used is: 'key' => array('key2' => array('key3' => 'value')) Becomes: 'key.key2.key3' => 'value' This function takes an array by reference and will modify it @type messages: dict @param messages: The dict ...
[ "Flattens", "an", "nested", "array", "of", "translations", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L127-L152
train
Flattens an nested array of translations.
adamziel/python_translate
python_translate/loaders.py
PoFileLoader.parse
def parse(self, resource): """ Loads given resource into a dict using polib @type resource: str @param resource: resource @rtype: list """ try: import polib except ImportError as e: self.rethrow( "You need to insta...
python
def parse(self, resource): """ Loads given resource into a dict using polib @type resource: str @param resource: resource @rtype: list """ try: import polib except ImportError as e: self.rethrow( "You need to insta...
[ "def", "parse", "(", "self", ",", "resource", ")", ":", "try", ":", "import", "polib", "except", "ImportError", "as", "e", ":", "self", ".", "rethrow", "(", "\"You need to install polib to use PoFileLoader or MoFileLoader\"", ",", "ImportError", ")", "self", ".", ...
Loads given resource into a dict using polib @type resource: str @param resource: resource @rtype: list
[ "Loads", "given", "resource", "into", "a", "dict", "using", "polib" ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L219-L250
train
Parses given resource into a dict using polib
adamziel/python_translate
python_translate/loaders.py
PoFileLoader._load_contents
def _load_contents(self, polib, resource): """ Parses portable object (PO) format using polib @type resource: str @param resource: resource @rtype: list """ try: return polib.pofile(resource) except (ValueError, AttributeError) as e: ...
python
def _load_contents(self, polib, resource): """ Parses portable object (PO) format using polib @type resource: str @param resource: resource @rtype: list """ try: return polib.pofile(resource) except (ValueError, AttributeError) as e: ...
[ "def", "_load_contents", "(", "self", ",", "polib", ",", "resource", ")", ":", "try", ":", "return", "polib", ".", "pofile", "(", "resource", ")", "except", "(", "ValueError", ",", "AttributeError", ")", "as", "e", ":", "self", ".", "rethrow", "(", "\"...
Parses portable object (PO) format using polib @type resource: str @param resource: resource @rtype: list
[ "Parses", "portable", "object", "(", "PO", ")", "format", "using", "polib" ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L252-L266
train
Parses portable object using polib. pofile and returns list of tuples
adamziel/python_translate
python_translate/loaders.py
MoFileLoader._load_contents
def _load_contents(self, polib, resource): """ Parses machine object (MO) format using polib @type resource: str @param resource: resource @rtype: list """ import struct try: return polib.mofile(resource) except (ValueError, Attribute...
python
def _load_contents(self, polib, resource): """ Parses machine object (MO) format using polib @type resource: str @param resource: resource @rtype: list """ import struct try: return polib.mofile(resource) except (ValueError, Attribute...
[ "def", "_load_contents", "(", "self", ",", "polib", ",", "resource", ")", ":", "import", "struct", "try", ":", "return", "polib", ".", "mofile", "(", "resource", ")", "except", "(", "ValueError", ",", "AttributeError", ",", "struct", ".", "error", ")", "...
Parses machine object (MO) format using polib @type resource: str @param resource: resource @rtype: list
[ "Parses", "machine", "object", "(", "MO", ")", "format", "using", "polib" ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L271-L286
train
Load the contents of a resource from the given polib file.
ktdreyer/txkoji
txkoji/task.py
Task.arch
def arch(self): """ Return an architecture for this task. :returns: an arch string (eg "noarch", or "ppc64le"), or None this task has no architecture associated with it. """ if self.method in ('buildArch', 'createdistrepo', 'livecd'): return self.pa...
python
def arch(self): """ Return an architecture for this task. :returns: an arch string (eg "noarch", or "ppc64le"), or None this task has no architecture associated with it. """ if self.method in ('buildArch', 'createdistrepo', 'livecd'): return self.pa...
[ "def", "arch", "(", "self", ")", ":", "if", "self", ".", "method", "in", "(", "'buildArch'", ",", "'createdistrepo'", ",", "'livecd'", ")", ":", "return", "self", ".", "params", "[", "2", "]", "if", "self", ".", "method", "in", "(", "'createrepo'", "...
Return an architecture for this task. :returns: an arch string (eg "noarch", or "ppc64le"), or None this task has no architecture associated with it.
[ "Return", "an", "architecture", "for", "this", "task", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L28-L42
train
Returns an architecture string for this task.
ktdreyer/txkoji
txkoji/task.py
Task.arches
def arches(self): """ Return a list of architectures for this task. :returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list is empty if this task has no arches associated with it. """ if self.method == 'image': return self.params[2] ...
python
def arches(self): """ Return a list of architectures for this task. :returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list is empty if this task has no arches associated with it. """ if self.method == 'image': return self.params[2] ...
[ "def", "arches", "(", "self", ")", ":", "if", "self", ".", "method", "==", "'image'", ":", "return", "self", ".", "params", "[", "2", "]", "if", "self", ".", "arch", ":", "return", "[", "self", ".", "arch", "]", "return", "[", "]" ]
Return a list of architectures for this task. :returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list is empty if this task has no arches associated with it.
[ "Return", "a", "list", "of", "architectures", "for", "this", "task", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L45-L56
train
Returns a list of architectures for this task.
ktdreyer/txkoji
txkoji/task.py
Task.duration
def duration(self): """ Return a timedelta for this task. Measure the time between this task's start and end time, or "now" if the task has not yet finished. :returns: timedelta object, or None if the task has not even started. """ if not self.started: ...
python
def duration(self): """ Return a timedelta for this task. Measure the time between this task's start and end time, or "now" if the task has not yet finished. :returns: timedelta object, or None if the task has not even started. """ if not self.started: ...
[ "def", "duration", "(", "self", ")", ":", "if", "not", "self", ".", "started", ":", "return", "None", "start", "=", "self", ".", "started", "end", "=", "self", ".", "completed", "if", "not", "end", ":", "end", "=", "datetime", ".", "utcnow", "(", "...
Return a timedelta for this task. Measure the time between this task's start and end time, or "now" if the task has not yet finished. :returns: timedelta object, or None if the task has not even started.
[ "Return", "a", "timedelta", "for", "this", "task", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L127-L142
train
Return a timedelta object for this task.
ktdreyer/txkoji
txkoji/task.py
Task.estimate_completion
def estimate_completion(self): """ Estimate completion time for a task. :returns: deferred that when fired returns a datetime object for the estimated, or the actual datetime, or None if we could not estimate a time for this task method. """ i...
python
def estimate_completion(self): """ Estimate completion time for a task. :returns: deferred that when fired returns a datetime object for the estimated, or the actual datetime, or None if we could not estimate a time for this task method. """ i...
[ "def", "estimate_completion", "(", "self", ")", ":", "if", "self", ".", "completion_ts", ":", "# Task is already complete. Return the exact completion time:", "defer", ".", "returnValue", "(", "self", ".", "completed", ")", "# Get the timestamps from the descendent task that'...
Estimate completion time for a task. :returns: deferred that when fired returns a datetime object for the estimated, or the actual datetime, or None if we could not estimate a time for this task method.
[ "Estimate", "completion", "time", "for", "a", "task", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L145-L167
train
Estimate completion time for a task.
ktdreyer/txkoji
txkoji/task.py
Task.estimate_duration
def estimate_duration(self): """ Estimate duration (timedelta) for this task. Estimate the average length of time we expect between this task's start and end times. :returns: deferred that when fired returns a timedelta object for the estimated timedelta, or t...
python
def estimate_duration(self): """ Estimate duration (timedelta) for this task. Estimate the average length of time we expect between this task's start and end times. :returns: deferred that when fired returns a timedelta object for the estimated timedelta, or t...
[ "def", "estimate_duration", "(", "self", ")", ":", "if", "self", ".", "completion_ts", ":", "# Task is already complete. Return the exact duration timedelta.", "return", "defer", ".", "succeed", "(", "self", ".", "duration", ")", "if", "not", "self", ".", "package",...
Estimate duration (timedelta) for this task. Estimate the average length of time we expect between this task's start and end times. :returns: deferred that when fired returns a timedelta object for the estimated timedelta, or the actual timedelta, or None if we ...
[ "Estimate", "duration", "(", "timedelta", ")", "for", "this", "task", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L169-L194
train
Estimate the duration of this task.
ktdreyer/txkoji
txkoji/task.py
Task._estimate_free
def _estimate_free(self): """ Estimate completion time for a free task. :returns: deferred that when fired returns a datetime object for the estimated, or the actual datetime, or None if we could not estimate a time for this task method. """ #...
python
def _estimate_free(self): """ Estimate completion time for a free task. :returns: deferred that when fired returns a datetime object for the estimated, or the actual datetime, or None if we could not estimate a time for this task method. """ #...
[ "def", "_estimate_free", "(", "self", ")", ":", "# Query the information we need for this task's channel and package.", "capacity_deferred", "=", "self", ".", "channel", ".", "total_capacity", "(", ")", "open_tasks_deferred", "=", "self", ".", "channel", ".", "tasks", "...
Estimate completion time for a free task. :returns: deferred that when fired returns a datetime object for the estimated, or the actual datetime, or None if we could not estimate a time for this task method.
[ "Estimate", "completion", "time", "for", "a", "free", "task", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L197-L228
train
Estimate completion time for a free task.
ktdreyer/txkoji
txkoji/task.py
Task.estimate_descendents
def estimate_descendents(self): """ Estimate from the descendent (child) tasks. :returns: deferred that when fired returns a datetime object for the estimated, or actual datetime, or None if there is no support for this task method. Currently the only support...
python
def estimate_descendents(self): """ Estimate from the descendent (child) tasks. :returns: deferred that when fired returns a datetime object for the estimated, or actual datetime, or None if there is no support for this task method. Currently the only support...
[ "def", "estimate_descendents", "(", "self", ")", ":", "child_method", "=", "None", "if", "self", ".", "method", "==", "'build'", ":", "child_method", "=", "'buildArch'", "if", "self", ".", "method", "==", "'image'", ":", "child_method", "=", "'createImage'", ...
Estimate from the descendent (child) tasks. :returns: deferred that when fired returns a datetime object for the estimated, or actual datetime, or None if there is no support for this task method. Currently the only supported methods here are "build" and "i...
[ "Estimate", "from", "the", "descendent", "(", "child", ")", "tasks", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L231-L271
train
Estimate the completion time for the child tasks.
ktdreyer/txkoji
txkoji/task.py
Task.descendents
def descendents(self, method=None, state=None): """ Find descendant tasks, optionally filtered by method and/or state. :param method: (optional) filter for tasks, eg. "buildArch". :param state: (optional) filter for tasks, eg. task_states.OPEN. :returns: deferred that when fired...
python
def descendents(self, method=None, state=None): """ Find descendant tasks, optionally filtered by method and/or state. :param method: (optional) filter for tasks, eg. "buildArch". :param state: (optional) filter for tasks, eg. task_states.OPEN. :returns: deferred that when fired...
[ "def", "descendents", "(", "self", ",", "method", "=", "None", ",", "state", "=", "None", ")", ":", "subtasks", "=", "yield", "self", ".", "connection", ".", "getTaskDescendents", "(", "self", ".", "id", ")", "if", "method", ":", "subtasks", "=", "[", ...
Find descendant tasks, optionally filtered by method and/or state. :param method: (optional) filter for tasks, eg. "buildArch". :param state: (optional) filter for tasks, eg. task_states.OPEN. :returns: deferred that when fired returns a list of Tasks.
[ "Find", "descendant", "tasks", "optionally", "filtered", "by", "method", "and", "/", "or", "state", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L274-L287
train
Find descendant tasks optionally filtered by method and state.
ktdreyer/txkoji
txkoji/task.py
Task.package
def package(self): """ Find a package name from a build task's parameters. :returns: name of the package this build task is building. :raises: ValueError if we could not parse this tasks's request params. """ if self.method == 'buildNotification': return self...
python
def package(self): """ Find a package name from a build task's parameters. :returns: name of the package this build task is building. :raises: ValueError if we could not parse this tasks's request params. """ if self.method == 'buildNotification': return self...
[ "def", "package", "(", "self", ")", ":", "if", "self", ".", "method", "==", "'buildNotification'", ":", "return", "self", ".", "params", "[", "1", "]", "[", "'name'", "]", "if", "self", ".", "method", "in", "(", "'createImage'", ",", "'image'", ",", ...
Find a package name from a build task's parameters. :returns: name of the package this build task is building. :raises: ValueError if we could not parse this tasks's request params.
[ "Find", "a", "package", "name", "from", "a", "build", "task", "s", "parameters", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L290-L325
train
Find a package name from a build task s parameters.
ktdreyer/txkoji
txkoji/task.py
Task.params
def params(self): """ Return a list of parameters in this task's request. If self.request is already a list, simply return it. If self.request is a raw XML-RPC string, parse it and return the params. """ if isinstance(self.request, list): return unmu...
python
def params(self): """ Return a list of parameters in this task's request. If self.request is already a list, simply return it. If self.request is a raw XML-RPC string, parse it and return the params. """ if isinstance(self.request, list): return unmu...
[ "def", "params", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "request", ",", "list", ")", ":", "return", "unmunchify", "(", "self", ".", "request", ")", "(", "params", ",", "_", ")", "=", "xmlrpc", ".", "loads", "(", "self", ".", ...
Return a list of parameters in this task's request. If self.request is already a list, simply return it. If self.request is a raw XML-RPC string, parse it and return the params.
[ "Return", "a", "list", "of", "parameters", "in", "this", "task", "s", "request", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L328-L340
train
Return a list of parameters in this task s request.
ktdreyer/txkoji
txkoji/task.py
Task.tag
def tag(self): """ Return the tag's name (or id number) for this task. :returns: An int (tag id) or string (tag name, eg "foo-build"). This seems to depend on the task method. For example, buildArch, tagBuild, and tagNotification tasks always return ...
python
def tag(self): """ Return the tag's name (or id number) for this task. :returns: An int (tag id) or string (tag name, eg "foo-build"). This seems to depend on the task method. For example, buildArch, tagBuild, and tagNotification tasks always return ...
[ "def", "tag", "(", "self", ")", ":", "if", "self", ".", "method", "==", "'buildArch'", ":", "# Note: buildArch tag will be an int here.", "return", "self", ".", "params", "[", "1", "]", "if", "self", ".", "method", "in", "(", "'createdistrepo'", ",", "'distR...
Return the tag's name (or id number) for this task. :returns: An int (tag id) or string (tag name, eg "foo-build"). This seems to depend on the task method. For example, buildArch, tagBuild, and tagNotification tasks always return a tag ID here. ...
[ "Return", "the", "tag", "s", "name", "(", "or", "id", "number", ")", "for", "this", "task", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L351-L371
train
Returns the tag name or id number for this task.
ktdreyer/txkoji
txkoji/task.py
Task.url
def url(self): """ Return a kojiweb URL for this resource. :returns: ``str``, kojiweb URL like "http://cbs.centos.org/koji/taskinfo?taskID=381617" """ endpoint = 'taskinfo?taskID=%d' % self.id return posixpath.join(self.connection.weburl, endpoint)
python
def url(self): """ Return a kojiweb URL for this resource. :returns: ``str``, kojiweb URL like "http://cbs.centos.org/koji/taskinfo?taskID=381617" """ endpoint = 'taskinfo?taskID=%d' % self.id return posixpath.join(self.connection.weburl, endpoint)
[ "def", "url", "(", "self", ")", ":", "endpoint", "=", "'taskinfo?taskID=%d'", "%", "self", ".", "id", "return", "posixpath", ".", "join", "(", "self", ".", "connection", ".", "weburl", ",", "endpoint", ")" ]
Return a kojiweb URL for this resource. :returns: ``str``, kojiweb URL like "http://cbs.centos.org/koji/taskinfo?taskID=381617"
[ "Return", "a", "kojiweb", "URL", "for", "this", "resource", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L390-L398
train
Return a kojiweb URL for this resource.
tjcsl/cslbot
cslbot/commands/pull.py
cmd
def cmd(send, _, args): """Pull changes. Syntax: {command} <branch> """ try: if exists(join(args['handler'].confdir, '.git')): send(do_pull(srcdir=args['handler'].confdir)) else: send(do_pull(repo=args['config']['api']['githubrepo'])) except subprocess.Calle...
python
def cmd(send, _, args): """Pull changes. Syntax: {command} <branch> """ try: if exists(join(args['handler'].confdir, '.git')): send(do_pull(srcdir=args['handler'].confdir)) else: send(do_pull(repo=args['config']['api']['githubrepo'])) except subprocess.Calle...
[ "def", "cmd", "(", "send", ",", "_", ",", "args", ")", ":", "try", ":", "if", "exists", "(", "join", "(", "args", "[", "'handler'", "]", ".", "confdir", ",", "'.git'", ")", ")", ":", "send", "(", "do_pull", "(", "srcdir", "=", "args", "[", "'ha...
Pull changes. Syntax: {command} <branch>
[ "Pull", "changes", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/pull.py#L27-L41
train
Pull changes. Syntax: command
tjcsl/cslbot
cslbot/helpers/babble.py
build_markov
def build_markov(cursor, cmdchar, ctrlchan, speaker=None, initial_run=False, debug=False): """Builds a markov dictionary.""" if initial_run: cursor.query(Babble_last).delete() lastrow = cursor.query(Babble_last).first() if not lastrow: lastrow = Babble_last(last=0) cursor.add(las...
python
def build_markov(cursor, cmdchar, ctrlchan, speaker=None, initial_run=False, debug=False): """Builds a markov dictionary.""" if initial_run: cursor.query(Babble_last).delete() lastrow = cursor.query(Babble_last).first() if not lastrow: lastrow = Babble_last(last=0) cursor.add(las...
[ "def", "build_markov", "(", "cursor", ",", "cmdchar", ",", "ctrlchan", ",", "speaker", "=", "None", ",", "initial_run", "=", "False", ",", "debug", "=", "False", ")", ":", "if", "initial_run", ":", "cursor", ".", "query", "(", "Babble_last", ")", ".", ...
Builds a markov dictionary.
[ "Builds", "a", "markov", "dictionary", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/babble.py#L153-L206
train
Builds a markov dictionary.
reichlab/pymmwr
pymmwr.py
_start_date_of_year
def _start_date_of_year(year: int) -> datetime.date: """ Return start date of the year using MMWR week rules """ jan_one = datetime.date(year, 1, 1) diff = 7 * (jan_one.isoweekday() > 3) - jan_one.isoweekday() return jan_one + datetime.timedelta(days=diff)
python
def _start_date_of_year(year: int) -> datetime.date: """ Return start date of the year using MMWR week rules """ jan_one = datetime.date(year, 1, 1) diff = 7 * (jan_one.isoweekday() > 3) - jan_one.isoweekday() return jan_one + datetime.timedelta(days=diff)
[ "def", "_start_date_of_year", "(", "year", ":", "int", ")", "->", "datetime", ".", "date", ":", "jan_one", "=", "datetime", ".", "date", "(", "year", ",", "1", ",", "1", ")", "diff", "=", "7", "*", "(", "jan_one", ".", "isoweekday", "(", ")", ">", ...
Return start date of the year using MMWR week rules
[ "Return", "start", "date", "of", "the", "year", "using", "MMWR", "week", "rules" ]
98216bd5081998ca63db89003c4ef397fe905755
https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L40-L48
train
Return start date of the year using MMWR week rules
reichlab/pymmwr
pymmwr.py
epiweek_to_date
def epiweek_to_date(ew: Epiweek) -> datetime.date: """ Return date from epiweek (starts at Sunday) """ day_one = _start_date_of_year(ew.year) diff = 7 * (ew.week - 1) + (ew.day - 1) return day_one + datetime.timedelta(days=diff)
python
def epiweek_to_date(ew: Epiweek) -> datetime.date: """ Return date from epiweek (starts at Sunday) """ day_one = _start_date_of_year(ew.year) diff = 7 * (ew.week - 1) + (ew.day - 1) return day_one + datetime.timedelta(days=diff)
[ "def", "epiweek_to_date", "(", "ew", ":", "Epiweek", ")", "->", "datetime", ".", "date", ":", "day_one", "=", "_start_date_of_year", "(", "ew", ".", "year", ")", "diff", "=", "7", "*", "(", "ew", ".", "week", "-", "1", ")", "+", "(", "ew", ".", "...
Return date from epiweek (starts at Sunday)
[ "Return", "date", "from", "epiweek", "(", "starts", "at", "Sunday", ")" ]
98216bd5081998ca63db89003c4ef397fe905755
https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L51-L59
train
Return date from epiweek
reichlab/pymmwr
pymmwr.py
date_to_epiweek
def date_to_epiweek(date=datetime.date.today()) -> Epiweek: """ Convert python date to Epiweek """ year = date.year start_dates = list(map(_start_date_of_year, [year - 1, year, year + 1])) start_date = start_dates[1] if start_dates[1] > date: start_date = start_dates[0] elif da...
python
def date_to_epiweek(date=datetime.date.today()) -> Epiweek: """ Convert python date to Epiweek """ year = date.year start_dates = list(map(_start_date_of_year, [year - 1, year, year + 1])) start_date = start_dates[1] if start_dates[1] > date: start_date = start_dates[0] elif da...
[ "def", "date_to_epiweek", "(", "date", "=", "datetime", ".", "date", ".", "today", "(", ")", ")", "->", "Epiweek", ":", "year", "=", "date", ".", "year", "start_dates", "=", "list", "(", "map", "(", "_start_date_of_year", ",", "[", "year", "-", "1", ...
Convert python date to Epiweek
[ "Convert", "python", "date", "to", "Epiweek" ]
98216bd5081998ca63db89003c4ef397fe905755
https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L62-L80
train
Convert python date to Epiweek
reichlab/pymmwr
pymmwr.py
epiweeks_in_year
def epiweeks_in_year(year: int) -> int: """ Return number of epiweeks in a year """ if date_to_epiweek(epiweek_to_date(Epiweek(year, 53))).year == year: return 53 else: return 52
python
def epiweeks_in_year(year: int) -> int: """ Return number of epiweeks in a year """ if date_to_epiweek(epiweek_to_date(Epiweek(year, 53))).year == year: return 53 else: return 52
[ "def", "epiweeks_in_year", "(", "year", ":", "int", ")", "->", "int", ":", "if", "date_to_epiweek", "(", "epiweek_to_date", "(", "Epiweek", "(", "year", ",", "53", ")", ")", ")", ".", "year", "==", "year", ":", "return", "53", "else", ":", "return", ...
Return number of epiweeks in a year
[ "Return", "number", "of", "epiweeks", "in", "a", "year" ]
98216bd5081998ca63db89003c4ef397fe905755
https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L83-L91
train
Return number of epiweeks in a year
tylerbutler/engineer
engineer/commands/core.py
_ArgparseMixin.parser
def parser(self): """Returns the appropriate parser to use for adding arguments to your command.""" if self._command_parser is None: parents = [] if self.need_verbose: parents.append(_verbose_parser) if self.need_settings: parents.appen...
python
def parser(self): """Returns the appropriate parser to use for adding arguments to your command.""" if self._command_parser is None: parents = [] if self.need_verbose: parents.append(_verbose_parser) if self.need_settings: parents.appen...
[ "def", "parser", "(", "self", ")", ":", "if", "self", ".", "_command_parser", "is", "None", ":", "parents", "=", "[", "]", "if", "self", ".", "need_verbose", ":", "parents", ".", "append", "(", "_verbose_parser", ")", "if", "self", ".", "need_settings", ...
Returns the appropriate parser to use for adding arguments to your command.
[ "Returns", "the", "appropriate", "parser", "to", "use", "for", "adding", "arguments", "to", "your", "command", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/commands/core.py#L165-L178
train
Returns the appropriate parser to use for adding arguments to your command.
JoeVirtual/KonFoo
konfoo/categories.py
Category.get_name
def get_name(cls, value): """ Returns the `name` of the `Category` member with the matching *value* or a empty string if no member match. Example: >>> class Format(Category): ... hour = 'hh' ... minute = 'mm' ... second = 'ss' >>> Format.get_...
python
def get_name(cls, value): """ Returns the `name` of the `Category` member with the matching *value* or a empty string if no member match. Example: >>> class Format(Category): ... hour = 'hh' ... minute = 'mm' ... second = 'ss' >>> Format.get_...
[ "def", "get_name", "(", "cls", ",", "value", ")", ":", "for", "member", "in", "cls", ":", "if", "member", ".", "value", "==", "value", ":", "return", "member", ".", "name", "return", "str", "(", ")" ]
Returns the `name` of the `Category` member with the matching *value* or a empty string if no member match. Example: >>> class Format(Category): ... hour = 'hh' ... minute = 'mm' ... second = 'ss' >>> Format.get_name('hh') 'hour' >>> ...
[ "Returns", "the", "name", "of", "the", "Category", "member", "with", "the", "matching", "*", "value", "*", "or", "a", "empty", "string", "if", "no", "member", "match", "." ]
0c62ef5c2bed4deaf908b34082e4de2544532fdc
https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/categories.py#L157-L175
train
Returns the name of the category member with the matching value.
JoeVirtual/KonFoo
konfoo/categories.py
Category.get_value
def get_value(cls, name): """ Returns the `value` of the `Category` member with the matching *name* or `None` if no member match. Example: >>> class Format(Category): ... hour = 'hh' ... minute = 'mm' ... second = 'ss' >>> Format.get_value('h...
python
def get_value(cls, name): """ Returns the `value` of the `Category` member with the matching *name* or `None` if no member match. Example: >>> class Format(Category): ... hour = 'hh' ... minute = 'mm' ... second = 'ss' >>> Format.get_value('h...
[ "def", "get_value", "(", "cls", ",", "name", ")", ":", "for", "member", "in", "cls", ":", "if", "member", ".", "name", "==", "name", ":", "return", "member", ".", "value", "return", "None" ]
Returns the `value` of the `Category` member with the matching *name* or `None` if no member match. Example: >>> class Format(Category): ... hour = 'hh' ... minute = 'mm' ... second = 'ss' >>> Format.get_value('hour') 'hh' >>> Format....
[ "Returns", "the", "value", "of", "the", "Category", "member", "with", "the", "matching", "*", "name", "*", "or", "None", "if", "no", "member", "match", "." ]
0c62ef5c2bed4deaf908b34082e4de2544532fdc
https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/categories.py#L178-L196
train
Returns the value of the category member with the matching name or None if no match.
JoeVirtual/KonFoo
konfoo/categories.py
Category.get_member
def get_member(cls, value, default=None): """ Returns the first `Category` member with the matching *value* or the specified *default* value if no member match. Example: >>> class Format(Category): ... hour = 'hh' ... minute = 'mm' ... second = 'ss'...
python
def get_member(cls, value, default=None): """ Returns the first `Category` member with the matching *value* or the specified *default* value if no member match. Example: >>> class Format(Category): ... hour = 'hh' ... minute = 'mm' ... second = 'ss'...
[ "def", "get_member", "(", "cls", ",", "value", ",", "default", "=", "None", ")", ":", "for", "member", "in", "cls", ":", "if", "member", ".", "value", "==", "value", ":", "return", "member", "return", "default" ]
Returns the first `Category` member with the matching *value* or the specified *default* value if no member match. Example: >>> class Format(Category): ... hour = 'hh' ... minute = 'mm' ... second = 'ss' >>> Format.get_member('hh') Format.ho...
[ "Returns", "the", "first", "Category", "member", "with", "the", "matching", "*", "value", "*", "or", "the", "specified", "*", "default", "*", "value", "if", "no", "member", "match", "." ]
0c62ef5c2bed4deaf908b34082e4de2544532fdc
https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/categories.py#L199-L217
train
Returns the first Category member with the matching value or the specified default value if no match is found.
tjcsl/cslbot
cslbot/commands/admins.py
cmd
def cmd(send, _, args): """Returns a list of admins. V = Verified (authed to NickServ), U = Unverified. Syntax: {command} """ adminlist = [] for admin in args['db'].query(Permissions).order_by(Permissions.nick).all(): if admin.registered: adminlist.append("%s (V)" % admin.n...
python
def cmd(send, _, args): """Returns a list of admins. V = Verified (authed to NickServ), U = Unverified. Syntax: {command} """ adminlist = [] for admin in args['db'].query(Permissions).order_by(Permissions.nick).all(): if admin.registered: adminlist.append("%s (V)" % admin.n...
[ "def", "cmd", "(", "send", ",", "_", ",", "args", ")", ":", "adminlist", "=", "[", "]", "for", "admin", "in", "args", "[", "'db'", "]", ".", "query", "(", "Permissions", ")", ".", "order_by", "(", "Permissions", ".", "nick", ")", ".", "all", "(",...
Returns a list of admins. V = Verified (authed to NickServ), U = Unverified. Syntax: {command}
[ "Returns", "a", "list", "of", "admins", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/admins.py#L23-L36
train
Returns a list of admins.
acutesoftware/virtual-AI-simulator
vais/AI_sample_game.py
ReallySimpleGameAI.run
def run(self): """ This AI simple moves the characters towards the opposite edges of the grid for 3 steps or until event halts the simulation """ x, y = 1,0 # set the direction num_steps = 0 while self.s.get_state() != 'Halted': self.s.comman...
python
def run(self): """ This AI simple moves the characters towards the opposite edges of the grid for 3 steps or until event halts the simulation """ x, y = 1,0 # set the direction num_steps = 0 while self.s.get_state() != 'Halted': self.s.comman...
[ "def", "run", "(", "self", ")", ":", "x", ",", "y", "=", "1", ",", "0", "# set the direction", "num_steps", "=", "0", "while", "self", ".", "s", ".", "get_state", "(", ")", "!=", "'Halted'", ":", "self", ".", "s", ".", "command", "(", "{", "'name...
This AI simple moves the characters towards the opposite edges of the grid for 3 steps or until event halts the simulation
[ "This", "AI", "simple", "moves", "the", "characters", "towards", "the", "opposite", "edges", "of", "the", "grid", "for", "3", "steps", "or", "until", "event", "halts", "the", "simulation" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/AI_sample_game.py#L28-L43
train
This AI simple moves the characters towards the opposite edges of the simulation for 3 steps.
louib/confirm
confirm/main.py
validate
def validate(schema_file, config_file, deprecation): '''Validate a configuration file against a confirm schema.''' result = validator_from_config_file(config_file, schema_file) result.validate(error_on_deprecated=deprecation) for error in result.errors(): click.secho('Error : %s' % error, er...
python
def validate(schema_file, config_file, deprecation): '''Validate a configuration file against a confirm schema.''' result = validator_from_config_file(config_file, schema_file) result.validate(error_on_deprecated=deprecation) for error in result.errors(): click.secho('Error : %s' % error, er...
[ "def", "validate", "(", "schema_file", ",", "config_file", ",", "deprecation", ")", ":", "result", "=", "validator_from_config_file", "(", "config_file", ",", "schema_file", ")", "result", ".", "validate", "(", "error_on_deprecated", "=", "deprecation", ")", "for"...
Validate a configuration file against a confirm schema.
[ "Validate", "a", "configuration", "file", "against", "a", "confirm", "schema", "." ]
0acd1eccda6cd71c69d2ae33166a16a257685811
https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L25-L35
train
Validate a configuration file against a confirm schema.
louib/confirm
confirm/main.py
migrate
def migrate(schema_file, config_file): '''Migrates a configuration file using a confirm schema.''' schema = load_schema_file(open(schema_file, 'r')) config = load_config_file(config_file, open(config_file, 'r').read()) config = append_existing_values(schema, config) migrated_config = generate_con...
python
def migrate(schema_file, config_file): '''Migrates a configuration file using a confirm schema.''' schema = load_schema_file(open(schema_file, 'r')) config = load_config_file(config_file, open(config_file, 'r').read()) config = append_existing_values(schema, config) migrated_config = generate_con...
[ "def", "migrate", "(", "schema_file", ",", "config_file", ")", ":", "schema", "=", "load_schema_file", "(", "open", "(", "schema_file", ",", "'r'", ")", ")", "config", "=", "load_config_file", "(", "config_file", ",", "open", "(", "config_file", ",", "'r'", ...
Migrates a configuration file using a confirm schema.
[ "Migrates", "a", "configuration", "file", "using", "a", "confirm", "schema", "." ]
0acd1eccda6cd71c69d2ae33166a16a257685811
https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L41-L50
train
Migrates a configuration file using a confirm schema.
louib/confirm
confirm/main.py
document
def document(schema_file): '''Generate reStructuredText documentation from a confirm schema.''' schema = load_schema_file(open(schema_file, 'r')) documentation = generate_documentation(schema) sys.stdout.write(documentation)
python
def document(schema_file): '''Generate reStructuredText documentation from a confirm schema.''' schema = load_schema_file(open(schema_file, 'r')) documentation = generate_documentation(schema) sys.stdout.write(documentation)
[ "def", "document", "(", "schema_file", ")", ":", "schema", "=", "load_schema_file", "(", "open", "(", "schema_file", ",", "'r'", ")", ")", "documentation", "=", "generate_documentation", "(", "schema", ")", "sys", ".", "stdout", ".", "write", "(", "documenta...
Generate reStructuredText documentation from a confirm schema.
[ "Generate", "reStructuredText", "documentation", "from", "a", "confirm", "schema", "." ]
0acd1eccda6cd71c69d2ae33166a16a257685811
https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L55-L59
train
Generate reStructuredText documentation from a confirm schema.
louib/confirm
confirm/main.py
generate
def generate(schema_file, all_options): '''Generates a template configuration file from a confirm schema.''' schema = load_schema_file(open(schema_file, 'r')) config_parser = generate_config_parser(schema, include_all=all_options) config_parser.write(sys.stdout)
python
def generate(schema_file, all_options): '''Generates a template configuration file from a confirm schema.''' schema = load_schema_file(open(schema_file, 'r')) config_parser = generate_config_parser(schema, include_all=all_options) config_parser.write(sys.stdout)
[ "def", "generate", "(", "schema_file", ",", "all_options", ")", ":", "schema", "=", "load_schema_file", "(", "open", "(", "schema_file", ",", "'r'", ")", ")", "config_parser", "=", "generate_config_parser", "(", "schema", ",", "include_all", "=", "all_options", ...
Generates a template configuration file from a confirm schema.
[ "Generates", "a", "template", "configuration", "file", "from", "a", "confirm", "schema", "." ]
0acd1eccda6cd71c69d2ae33166a16a257685811
https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L65-L69
train
Generates a template configuration file from a confirm schema.
louib/confirm
confirm/main.py
init
def init(config_file): '''Initialize a confirm schema from an existing configuration file.''' schema = generate_schema_file(open(config_file, 'r').read()) sys.stdout.write(schema)
python
def init(config_file): '''Initialize a confirm schema from an existing configuration file.''' schema = generate_schema_file(open(config_file, 'r').read()) sys.stdout.write(schema)
[ "def", "init", "(", "config_file", ")", ":", "schema", "=", "generate_schema_file", "(", "open", "(", "config_file", ",", "'r'", ")", ".", "read", "(", ")", ")", "sys", ".", "stdout", ".", "write", "(", "schema", ")" ]
Initialize a confirm schema from an existing configuration file.
[ "Initialize", "a", "confirm", "schema", "from", "an", "existing", "configuration", "file", "." ]
0acd1eccda6cd71c69d2ae33166a16a257685811
https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L74-L77
train
Initialize a confirm schema from an existing configuration file.
VIVelev/PyDojoML
dojo/cluster/mixture/gaussian_mixture_model.py
GaussianMixtureModel._init_random_gaussians
def _init_random_gaussians(self, X): """Initialize gaussian randomly""" n_samples = np.shape(X)[0] self.priors = (1 / self.k) * np.ones(self.k) for _ in range(self.k): params = {} params["mean"] = X[np.random.choice(range(n_samples))] params["cov"] = ...
python
def _init_random_gaussians(self, X): """Initialize gaussian randomly""" n_samples = np.shape(X)[0] self.priors = (1 / self.k) * np.ones(self.k) for _ in range(self.k): params = {} params["mean"] = X[np.random.choice(range(n_samples))] params["cov"] = ...
[ "def", "_init_random_gaussians", "(", "self", ",", "X", ")", ":", "n_samples", "=", "np", ".", "shape", "(", "X", ")", "[", "0", "]", "self", ".", "priors", "=", "(", "1", "/", "self", ".", "k", ")", "*", "np", ".", "ones", "(", "self", ".", ...
Initialize gaussian randomly
[ "Initialize", "gaussian", "randomly" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L36-L45
train
Initialize gaussian randomly
VIVelev/PyDojoML
dojo/cluster/mixture/gaussian_mixture_model.py
GaussianMixtureModel.multivariate_gaussian
def multivariate_gaussian(self, X, params): """Likelihood""" n_features = np.shape(X)[1] mean = params["mean"] covar = params["cov"] determinant = np.linalg.det(covar) likelihoods = np.zeros(np.shape(X)[0]) for i, sample in enumerate(X): d = n_feature...
python
def multivariate_gaussian(self, X, params): """Likelihood""" n_features = np.shape(X)[1] mean = params["mean"] covar = params["cov"] determinant = np.linalg.det(covar) likelihoods = np.zeros(np.shape(X)[0]) for i, sample in enumerate(X): d = n_feature...
[ "def", "multivariate_gaussian", "(", "self", ",", "X", ",", "params", ")", ":", "n_features", "=", "np", ".", "shape", "(", "X", ")", "[", "1", "]", "mean", "=", "params", "[", "\"mean\"", "]", "covar", "=", "params", "[", "\"cov\"", "]", "determinan...
Likelihood
[ "Likelihood" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L47-L61
train
multivariate Gaussian likelihood
VIVelev/PyDojoML
dojo/cluster/mixture/gaussian_mixture_model.py
GaussianMixtureModel._get_likelihoods
def _get_likelihoods(self, X): """Calculate the likelihood over all samples""" n_samples = np.shape(X)[0] likelihoods = np.zeros((n_samples, self.k)) for i in range(self.k): likelihoods[:, i] = self.multivariate_gaussian(X, self.parameters[i]) return likelihoods
python
def _get_likelihoods(self, X): """Calculate the likelihood over all samples""" n_samples = np.shape(X)[0] likelihoods = np.zeros((n_samples, self.k)) for i in range(self.k): likelihoods[:, i] = self.multivariate_gaussian(X, self.parameters[i]) return likelihoods
[ "def", "_get_likelihoods", "(", "self", ",", "X", ")", ":", "n_samples", "=", "np", ".", "shape", "(", "X", ")", "[", "0", "]", "likelihoods", "=", "np", ".", "zeros", "(", "(", "n_samples", ",", "self", ".", "k", ")", ")", "for", "i", "in", "r...
Calculate the likelihood over all samples
[ "Calculate", "the", "likelihood", "over", "all", "samples" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L63-L71
train
Calculate the likelihood over all samples
VIVelev/PyDojoML
dojo/cluster/mixture/gaussian_mixture_model.py
GaussianMixtureModel._maximization
def _maximization(self, X): """Update the parameters and priors""" # Iterate through clusters and recalculate mean and covariance for i in range(self.k): resp = np.expand_dims(self.responsibility[:, i], axis=1) mean = (resp * X).sum(axis=0) / resp.sum() covar...
python
def _maximization(self, X): """Update the parameters and priors""" # Iterate through clusters and recalculate mean and covariance for i in range(self.k): resp = np.expand_dims(self.responsibility[:, i], axis=1) mean = (resp * X).sum(axis=0) / resp.sum() covar...
[ "def", "_maximization", "(", "self", ",", "X", ")", ":", "# Iterate through clusters and recalculate mean and covariance", "for", "i", "in", "range", "(", "self", ".", "k", ")", ":", "resp", "=", "np", ".", "expand_dims", "(", "self", ".", "responsibility", "[...
Update the parameters and priors
[ "Update", "the", "parameters", "and", "priors" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L86-L98
train
Update the parameters and priors based on the cluster weights and the residual.
VIVelev/PyDojoML
dojo/cluster/mixture/gaussian_mixture_model.py
GaussianMixtureModel._converged
def _converged(self, X): """Covergence if || likehood - last_likelihood || < tolerance""" if len(self.responsibilities) < 2: return False diff = np.linalg.norm(self.responsibilities[-1] - self.responsibilities[-2]) return diff <= self.tolerance
python
def _converged(self, X): """Covergence if || likehood - last_likelihood || < tolerance""" if len(self.responsibilities) < 2: return False diff = np.linalg.norm(self.responsibilities[-1] - self.responsibilities[-2]) return diff <= self.tolerance
[ "def", "_converged", "(", "self", ",", "X", ")", ":", "if", "len", "(", "self", ".", "responsibilities", ")", "<", "2", ":", "return", "False", "diff", "=", "np", ".", "linalg", ".", "norm", "(", "self", ".", "responsibilities", "[", "-", "1", "]",...
Covergence if || likehood - last_likelihood || < tolerance
[ "Covergence", "if", "||", "likehood", "-", "last_likelihood", "||", "<", "tolerance" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L100-L107
train
Covergence check for the current class.
VIVelev/PyDojoML
dojo/cluster/mixture/gaussian_mixture_model.py
GaussianMixtureModel.cluster
def cluster(self, X): """Run GMM and return the cluster indices""" # Initialize the gaussians randomly self._init_random_gaussians(X) # Run EM until convergence or for max iterations for _ in range(self.max_iterations): self._expectation(X) # E-step s...
python
def cluster(self, X): """Run GMM and return the cluster indices""" # Initialize the gaussians randomly self._init_random_gaussians(X) # Run EM until convergence or for max iterations for _ in range(self.max_iterations): self._expectation(X) # E-step s...
[ "def", "cluster", "(", "self", ",", "X", ")", ":", "# Initialize the gaussians randomly", "self", ".", "_init_random_gaussians", "(", "X", ")", "# Run EM until convergence or for max iterations", "for", "_", "in", "range", "(", "self", ".", "max_iterations", ")", ":...
Run GMM and return the cluster indices
[ "Run", "GMM", "and", "return", "the", "cluster", "indices" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L109-L126
train
Run GMM and return the cluster indices
tjcsl/cslbot
cslbot/commands/translate.py
cmd
def cmd(send, msg, args): """Translate something. Syntax: {command} [--from <language code>] [--to <language code>] <text> See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes """ parser = arguments.ArgParser(args['config']) parse...
python
def cmd(send, msg, args): """Translate something. Syntax: {command} [--from <language code>] [--to <language code>] <text> See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes """ parser = arguments.ArgParser(args['config']) parse...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "parser", "=", "arguments", ".", "ArgParser", "(", "args", "[", "'config'", "]", ")", "parser", ".", "add_argument", "(", "'--lang'", ",", "'--from'", ",", "default", "=", "None", ")", "pa...
Translate something. Syntax: {command} [--from <language code>] [--to <language code>] <text> See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes
[ "Translate", "something", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/translate.py#L24-L40
train
Translate something.
tjcsl/cslbot
cslbot/commands/coin.py
cmd
def cmd(send, msg, _): """Flips a coin a number of times. Syntax: {command} [number] """ coin = ['heads', 'tails'] if not msg: send('The coin lands on... %s' % choice(coin)) elif not msg.lstrip('-').isdigit(): send("Not A Valid Positive Integer.") else: msg = int(ms...
python
def cmd(send, msg, _): """Flips a coin a number of times. Syntax: {command} [number] """ coin = ['heads', 'tails'] if not msg: send('The coin lands on... %s' % choice(coin)) elif not msg.lstrip('-').isdigit(): send("Not A Valid Positive Integer.") else: msg = int(ms...
[ "def", "cmd", "(", "send", ",", "msg", ",", "_", ")", ":", "coin", "=", "[", "'heads'", ",", "'tails'", "]", "if", "not", "msg", ":", "send", "(", "'The coin lands on... %s'", "%", "choice", "(", "coin", ")", ")", "elif", "not", "msg", ".", "lstrip...
Flips a coin a number of times. Syntax: {command} [number]
[ "Flips", "a", "coin", "a", "number", "of", "times", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/coin.py#L24-L42
train
Flips a coin a number of times.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.get_data
def get_data(self): """Saves the handler's data for :func:`.reloader.do_reload`""" data = {} data['guarded'] = self.guarded[:] data['voiced'] = copy.deepcopy(self.voiced) data['opers'] = copy.deepcopy(self.opers) data['features'] = self.features.copy() data['uptim...
python
def get_data(self): """Saves the handler's data for :func:`.reloader.do_reload`""" data = {} data['guarded'] = self.guarded[:] data['voiced'] = copy.deepcopy(self.voiced) data['opers'] = copy.deepcopy(self.opers) data['features'] = self.features.copy() data['uptim...
[ "def", "get_data", "(", "self", ")", ":", "data", "=", "{", "}", "data", "[", "'guarded'", "]", "=", "self", ".", "guarded", "[", ":", "]", "data", "[", "'voiced'", "]", "=", "copy", ".", "deepcopy", "(", "self", ".", "voiced", ")", "data", "[", ...
Saves the handler's data for :func:`.reloader.do_reload`
[ "Saves", "the", "handler", "s", "data", "for", ":", "func", ":", ".", "reloader", ".", "do_reload" ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L73-L83
train
Saves the handler s data for the reload method.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.set_data
def set_data(self, data): """Called from :func:`.reloader.do_reload` to restore the handler's data.""" for key, val in data.items(): setattr(self, key, val) self.uptime['reloaded'] = datetime.now()
python
def set_data(self, data): """Called from :func:`.reloader.do_reload` to restore the handler's data.""" for key, val in data.items(): setattr(self, key, val) self.uptime['reloaded'] = datetime.now()
[ "def", "set_data", "(", "self", ",", "data", ")", ":", "for", "key", ",", "val", "in", "data", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "val", ")", "self", ".", "uptime", "[", "'reloaded'", "]", "=", "datetime", ".", ...
Called from :func:`.reloader.do_reload` to restore the handler's data.
[ "Called", "from", ":", "func", ":", ".", "reloader", ".", "do_reload", "to", "restore", "the", "handler", "s", "data", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L85-L89
train
Called from. reloader. do_reload to restore the handler s data.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.is_admin
def is_admin(self, send, nick, required_role='admin'): """Checks if a nick is a admin. If NickServ hasn't responded yet, then the admin is unverified, so assume they aren't a admin. """ # If the required role is None, bypass checks. if not required_role: ret...
python
def is_admin(self, send, nick, required_role='admin'): """Checks if a nick is a admin. If NickServ hasn't responded yet, then the admin is unverified, so assume they aren't a admin. """ # If the required role is None, bypass checks. if not required_role: ret...
[ "def", "is_admin", "(", "self", ",", "send", ",", "nick", ",", "required_role", "=", "'admin'", ")", ":", "# If the required role is None, bypass checks.", "if", "not", "required_role", ":", "return", "True", "# Current roles are admin and owner, which is a superset of admi...
Checks if a nick is a admin. If NickServ hasn't responded yet, then the admin is unverified, so assume they aren't a admin.
[ "Checks", "if", "a", "nick", "is", "a", "admin", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L106-L138
train
Checks if a nick is an admin.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.get_admins
def get_admins(self): """Check verification for all admins.""" # no nickserv support, assume people are who they say they are. if not self.config['feature'].getboolean('nickserv'): return with self.db.session_scope() as session: for a in session.query(orm.Permissi...
python
def get_admins(self): """Check verification for all admins.""" # no nickserv support, assume people are who they say they are. if not self.config['feature'].getboolean('nickserv'): return with self.db.session_scope() as session: for a in session.query(orm.Permissi...
[ "def", "get_admins", "(", "self", ")", ":", "# no nickserv support, assume people are who they say they are.", "if", "not", "self", ".", "config", "[", "'feature'", "]", ".", "getboolean", "(", "'nickserv'", ")", ":", "return", "with", "self", ".", "db", ".", "s...
Check verification for all admins.
[ "Check", "verification", "for", "all", "admins", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L140-L148
train
Check verification for all admins.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.abusecheck
def abusecheck(self, send, nick, target, limit, cmd): """ Rate-limits commands. | If a nick uses commands with the limit attr set, record the time | at which they were used. | If the command is used more than `limit` times in a | minute, ignore the nick. """ if n...
python
def abusecheck(self, send, nick, target, limit, cmd): """ Rate-limits commands. | If a nick uses commands with the limit attr set, record the time | at which they were used. | If the command is used more than `limit` times in a | minute, ignore the nick. """ if n...
[ "def", "abusecheck", "(", "self", ",", "send", ",", "nick", ",", "target", ",", "limit", ",", "cmd", ")", ":", "if", "nick", "not", "in", "self", ".", "abuselist", ":", "self", ".", "abuselist", "[", "nick", "]", "=", "{", "}", "if", "cmd", "not"...
Rate-limits commands. | If a nick uses commands with the limit attr set, record the time | at which they were used. | If the command is used more than `limit` times in a | minute, ignore the nick.
[ "Rate", "-", "limits", "commands", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L150-L174
train
Check if a user abuses the bot.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.send
def send(self, target, nick, msg, msgtype, ignore_length=False, filters=None): """Send a message. Records the message in the log. """ if not isinstance(msg, str): raise Exception("Trying to send a %s to irc, only strings allowed." % type(msg).__name__) if filters is...
python
def send(self, target, nick, msg, msgtype, ignore_length=False, filters=None): """Send a message. Records the message in the log. """ if not isinstance(msg, str): raise Exception("Trying to send a %s to irc, only strings allowed." % type(msg).__name__) if filters is...
[ "def", "send", "(", "self", ",", "target", ",", "nick", ",", "msg", ",", "msgtype", ",", "ignore_length", "=", "False", ",", "filters", "=", "None", ")", ":", "if", "not", "isinstance", "(", "msg", ",", "str", ")", ":", "raise", "Exception", "(", "...
Send a message. Records the message in the log.
[ "Send", "a", "message", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L186-L213
train
Send a message to the irc.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.do_log
def do_log(self, target, nick, msg, msgtype): """Handles logging. | Logs to a sql db. """ if not isinstance(msg, str): raise Exception("IRC doesn't like it when you send it a %s" % type(msg).__name__) target = target.lower() flags = 0 # Properly hand...
python
def do_log(self, target, nick, msg, msgtype): """Handles logging. | Logs to a sql db. """ if not isinstance(msg, str): raise Exception("IRC doesn't like it when you send it a %s" % type(msg).__name__) target = target.lower() flags = 0 # Properly hand...
[ "def", "do_log", "(", "self", ",", "target", ",", "nick", ",", "msg", ",", "msgtype", ")", ":", "if", "not", "isinstance", "(", "msg", ",", "str", ")", ":", "raise", "Exception", "(", "\"IRC doesn't like it when you send it a %s\"", "%", "type", "(", "msg"...
Handles logging. | Logs to a sql db.
[ "Handles", "logging", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L226-L257
train
Handles logging.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.do_part
def do_part(self, cmdargs, nick, target, msgtype, send, c): """Leaves a channel. Prevent user from leaving the primary channel. """ channel = self.config['core']['channel'] botnick = self.config['core']['nick'] if not cmdargs: # don't leave the primary chann...
python
def do_part(self, cmdargs, nick, target, msgtype, send, c): """Leaves a channel. Prevent user from leaving the primary channel. """ channel = self.config['core']['channel'] botnick = self.config['core']['nick'] if not cmdargs: # don't leave the primary chann...
[ "def", "do_part", "(", "self", ",", "cmdargs", ",", "nick", ",", "target", ",", "msgtype", ",", "send", ",", "c", ")", ":", "channel", "=", "self", ".", "config", "[", "'core'", "]", "[", "'channel'", "]", "botnick", "=", "self", ".", "config", "["...
Leaves a channel. Prevent user from leaving the primary channel.
[ "Leaves", "a", "channel", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L259-L285
train
Leaves a channel.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.do_join
def do_join(self, cmdargs, nick, msgtype, send, c): """Join a channel. | Checks if bot is already joined to channel. """ if not cmdargs: send("Join what?") return if cmdargs == '0': send("I'm sorry, Dave. I'm afraid I can't do that.") ...
python
def do_join(self, cmdargs, nick, msgtype, send, c): """Join a channel. | Checks if bot is already joined to channel. """ if not cmdargs: send("Join what?") return if cmdargs == '0': send("I'm sorry, Dave. I'm afraid I can't do that.") ...
[ "def", "do_join", "(", "self", ",", "cmdargs", ",", "nick", ",", "msgtype", ",", "send", ",", "c", ")", ":", "if", "not", "cmdargs", ":", "send", "(", "\"Join what?\"", ")", "return", "if", "cmdargs", "==", "'0'", ":", "send", "(", "\"I'm sorry, Dave. ...
Join a channel. | Checks if bot is already joined to channel.
[ "Join", "a", "channel", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L287-L307
train
Join a channel.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.do_mode
def do_mode(self, target, msg, nick, send): """reop and handle guard violations.""" mode_changes = irc.modes.parse_channel_modes(msg) with self.data_lock: for change in mode_changes: if change[1] == 'v': self.voiced[target][change[2]] = True if cha...
python
def do_mode(self, target, msg, nick, send): """reop and handle guard violations.""" mode_changes = irc.modes.parse_channel_modes(msg) with self.data_lock: for change in mode_changes: if change[1] == 'v': self.voiced[target][change[2]] = True if cha...
[ "def", "do_mode", "(", "self", ",", "target", ",", "msg", ",", "nick", ",", "send", ")", ":", "mode_changes", "=", "irc", ".", "modes", ".", "parse_channel_modes", "(", "msg", ")", "with", "self", ".", "data_lock", ":", "for", "change", "in", "mode_cha...
reop and handle guard violations.
[ "reop", "and", "handle", "guard", "violations", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L318-L343
train
reop and handle guard violations.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.do_kick
def do_kick(self, send, target, nick, msg, slogan=True): """Kick users. - If kick is disabled, don't do anything. - If the bot is not a op, rage at a op. - Kick the user. """ if not self.kick_enabled: return if target not in self.channels: ...
python
def do_kick(self, send, target, nick, msg, slogan=True): """Kick users. - If kick is disabled, don't do anything. - If the bot is not a op, rage at a op. - Kick the user. """ if not self.kick_enabled: return if target not in self.channels: ...
[ "def", "do_kick", "(", "self", ",", "send", ",", "target", ",", "nick", ",", "msg", ",", "slogan", "=", "True", ")", ":", "if", "not", "self", ".", "kick_enabled", ":", "return", "if", "target", "not", "in", "self", ".", "channels", ":", "send", "(...
Kick users. - If kick is disabled, don't do anything. - If the bot is not a op, rage at a op. - Kick the user.
[ "Kick", "users", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L345-L374
train
Kick the user.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.do_args
def do_args(self, modargs, send, nick, target, source, name, msgtype): """Handle the various args that modules need.""" realargs = {} args = { 'nick': nick, 'handler': self, 'db': None, 'config': self.config, 'source': source, ...
python
def do_args(self, modargs, send, nick, target, source, name, msgtype): """Handle the various args that modules need.""" realargs = {} args = { 'nick': nick, 'handler': self, 'db': None, 'config': self.config, 'source': source, ...
[ "def", "do_args", "(", "self", ",", "modargs", ",", "send", ",", "nick", ",", "target", ",", "source", ",", "name", ",", "msgtype", ")", ":", "realargs", "=", "{", "}", "args", "=", "{", "'nick'", ":", "nick", ",", "'handler'", ":", "self", ",", ...
Handle the various args that modules need.
[ "Handle", "the", "various", "args", "that", "modules", "need", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L376-L398
train
Handle the various args that modules need.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.do_welcome
def do_welcome(self): """Do setup when connected to server. - Join the primary channel. - Join the control channel. """ self.rate_limited_send('join', self.config['core']['channel']) self.rate_limited_send('join', self.config['core']['ctrlchan'], self.config['auth']['ct...
python
def do_welcome(self): """Do setup when connected to server. - Join the primary channel. - Join the control channel. """ self.rate_limited_send('join', self.config['core']['channel']) self.rate_limited_send('join', self.config['core']['ctrlchan'], self.config['auth']['ct...
[ "def", "do_welcome", "(", "self", ")", ":", "self", ".", "rate_limited_send", "(", "'join'", ",", "self", ".", "config", "[", "'core'", "]", "[", "'channel'", "]", ")", "self", ".", "rate_limited_send", "(", "'join'", ",", "self", ".", "config", "[", "...
Do setup when connected to server. - Join the primary channel. - Join the control channel.
[ "Do", "setup", "when", "connected", "to", "server", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L400-L414
train
Do setup when connected to server.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.get_filtered_send
def get_filtered_send(self, cmdargs, send, target): """Parse out any filters.""" parser = arguments.ArgParser(self.config) parser.add_argument('--filter') try: filterargs, remainder = parser.parse_known_args(cmdargs) except arguments.ArgumentException as ex: ...
python
def get_filtered_send(self, cmdargs, send, target): """Parse out any filters.""" parser = arguments.ArgParser(self.config) parser.add_argument('--filter') try: filterargs, remainder = parser.parse_known_args(cmdargs) except arguments.ArgumentException as ex: ...
[ "def", "get_filtered_send", "(", "self", ",", "cmdargs", ",", "send", ",", "target", ")", ":", "parser", "=", "arguments", ".", "ArgParser", "(", "self", ".", "config", ")", "parser", ".", "add_argument", "(", "'--filter'", ")", "try", ":", "filterargs", ...
Parse out any filters.
[ "Parse", "out", "any", "filters", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L420-L439
train
Parse out any filters and send them to target.
tjcsl/cslbot
cslbot/helpers/handler.py
BotHandler.handle_msg
def handle_msg(self, c, e): """The Heart and Soul of IrcBot.""" if e.type not in ['authenticate', 'error', 'join', 'part', 'quit']: nick = e.source.nick else: nick = e.source if e.arguments is None: msg = "" else: msg = " ".join(e...
python
def handle_msg(self, c, e): """The Heart and Soul of IrcBot.""" if e.type not in ['authenticate', 'error', 'join', 'part', 'quit']: nick = e.source.nick else: nick = e.source if e.arguments is None: msg = "" else: msg = " ".join(e...
[ "def", "handle_msg", "(", "self", ",", "c", ",", "e", ")", ":", "if", "e", ".", "type", "not", "in", "[", "'authenticate'", ",", "'error'", ",", "'join'", ",", "'part'", ",", "'quit'", "]", ":", "nick", "=", "e", ".", "source", ".", "nick", "else...
The Heart and Soul of IrcBot.
[ "The", "Heart", "and", "Soul", "of", "IrcBot", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L605-L675
train
The Heart and Soul of IrcBot.
tjcsl/cslbot
cslbot/commands/ebay.py
cmd
def cmd(send, _, args): """Implements xkcd 576. Syntax: {command} """ apikey = args['config']['api']['ebayapikey'] categories = get_categories(apikey) item = None while not item: item = get_item(choice(categories), apikey) send(item)
python
def cmd(send, _, args): """Implements xkcd 576. Syntax: {command} """ apikey = args['config']['api']['ebayapikey'] categories = get_categories(apikey) item = None while not item: item = get_item(choice(categories), apikey) send(item)
[ "def", "cmd", "(", "send", ",", "_", ",", "args", ")", ":", "apikey", "=", "args", "[", "'config'", "]", "[", "'api'", "]", "[", "'ebayapikey'", "]", "categories", "=", "get_categories", "(", "apikey", ")", "item", "=", "None", "while", "not", "item"...
Implements xkcd 576. Syntax: {command}
[ "Implements", "xkcd", "576", ".", "Syntax", ":", "{", "command", "}" ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/ebay.py#L63-L72
train
Implements xkcd 576. Syntax
jmbeach/KEP.py
src/keppy/simulator_device.py
SimulatorDevice.process_tag
def process_tag(self, tag): """Processes tag and detects which function to use""" try: if not self._is_function(tag): self._tag_type_processor[tag.data_type](tag) except KeyError as ex: raise Exception('Tag type {0} not recognized for tag {1}' ...
python
def process_tag(self, tag): """Processes tag and detects which function to use""" try: if not self._is_function(tag): self._tag_type_processor[tag.data_type](tag) except KeyError as ex: raise Exception('Tag type {0} not recognized for tag {1}' ...
[ "def", "process_tag", "(", "self", ",", "tag", ")", ":", "try", ":", "if", "not", "self", ".", "_is_function", "(", "tag", ")", ":", "self", ".", "_tag_type_processor", "[", "tag", ".", "data_type", "]", "(", "tag", ")", "except", "KeyError", "as", "...
Processes tag and detects which function to use
[ "Processes", "tag", "and", "detects", "which", "function", "to", "use" ]
68cda64ab649640a486534867c81274c41e39446
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L48-L58
train
Processes a tag and detects which function to use
jmbeach/KEP.py
src/keppy/simulator_device.py
SimulatorDevice.process_boolean
def process_boolean(self, tag): """Process Boolean type tags""" tag.set_address(self.normal_register.current_bit_address) self.normal_register.move_to_next_bit_address()
python
def process_boolean(self, tag): """Process Boolean type tags""" tag.set_address(self.normal_register.current_bit_address) self.normal_register.move_to_next_bit_address()
[ "def", "process_boolean", "(", "self", ",", "tag", ")", ":", "tag", ".", "set_address", "(", "self", ".", "normal_register", ".", "current_bit_address", ")", "self", ".", "normal_register", ".", "move_to_next_bit_address", "(", ")" ]
Process Boolean type tags
[ "Process", "Boolean", "type", "tags" ]
68cda64ab649640a486534867c81274c41e39446
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L61-L64
train
Process Boolean type tags
jmbeach/KEP.py
src/keppy/simulator_device.py
SimulatorDevice.process_boolean_array
def process_boolean_array(self, tag): """Process Boolean array type tags""" array_size = tag.get_array_size() tag.set_address(self.normal_register.get_array(array_size)) if self.is_sixteen_bit: # each boolean address needs 1/16 byte self.normal_register.move_to_ne...
python
def process_boolean_array(self, tag): """Process Boolean array type tags""" array_size = tag.get_array_size() tag.set_address(self.normal_register.get_array(array_size)) if self.is_sixteen_bit: # each boolean address needs 1/16 byte self.normal_register.move_to_ne...
[ "def", "process_boolean_array", "(", "self", ",", "tag", ")", ":", "array_size", "=", "tag", ".", "get_array_size", "(", ")", "tag", ".", "set_address", "(", "self", ".", "normal_register", ".", "get_array", "(", "array_size", ")", ")", "if", "self", ".", ...
Process Boolean array type tags
[ "Process", "Boolean", "array", "type", "tags" ]
68cda64ab649640a486534867c81274c41e39446
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L66-L75
train
Process Boolean array type tags
jmbeach/KEP.py
src/keppy/simulator_device.py
SimulatorDevice.process_byte
def process_byte(self, tag): """Process byte type tags""" tag.set_address(self.normal_register.current_address) # each address needs 1 byte self.normal_register.move_to_next_address(1)
python
def process_byte(self, tag): """Process byte type tags""" tag.set_address(self.normal_register.current_address) # each address needs 1 byte self.normal_register.move_to_next_address(1)
[ "def", "process_byte", "(", "self", ",", "tag", ")", ":", "tag", ".", "set_address", "(", "self", ".", "normal_register", ".", "current_address", ")", "# each address needs 1 byte", "self", ".", "normal_register", ".", "move_to_next_address", "(", "1", ")" ]
Process byte type tags
[ "Process", "byte", "type", "tags" ]
68cda64ab649640a486534867c81274c41e39446
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L77-L81
train
Process a byte type tag.