repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
callowayproject/django-categories
categories/migration.py
migrate_app
def migrate_app(sender, *args, **kwargs): """ Migrate all models of this app registered """ from .registration import registry if 'app_config' not in kwargs: return app_config = kwargs['app_config'] app_name = app_config.label fields = [fld for fld in list(registry._field_regis...
python
def migrate_app(sender, *args, **kwargs): """ Migrate all models of this app registered """ from .registration import registry if 'app_config' not in kwargs: return app_config = kwargs['app_config'] app_name = app_config.label fields = [fld for fld in list(registry._field_regis...
[ "def", "migrate_app", "(", "sender", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "registration", "import", "registry", "if", "'app_config'", "not", "in", "kwargs", ":", "return", "app_config", "=", "kwargs", "[", "'app_config'", "]", ...
Migrate all models of this app registered
[ "Migrate", "all", "models", "of", "this", "app", "registered" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/migration.py#L39-L66
train
callowayproject/django-categories
categories/models.py
Category.get_absolute_url
def get_absolute_url(self): """Return a path""" from django.urls import NoReverseMatch if self.alternate_url: return self.alternate_url try: prefix = reverse('categories_tree_list') except NoReverseMatch: prefix = '/' ancestors = list(...
python
def get_absolute_url(self): """Return a path""" from django.urls import NoReverseMatch if self.alternate_url: return self.alternate_url try: prefix = reverse('categories_tree_list') except NoReverseMatch: prefix = '/' ancestors = list(...
[ "def", "get_absolute_url", "(", "self", ")", ":", "from", "django", ".", "urls", "import", "NoReverseMatch", "if", "self", ".", "alternate_url", ":", "return", "self", ".", "alternate_url", "try", ":", "prefix", "=", "reverse", "(", "'categories_tree_list'", "...
Return a path
[ "Return", "a", "path" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/models.py#L56-L67
train
callowayproject/django-categories
categories/models.py
CategoryRelationManager.get_content_type
def get_content_type(self, content_type): """ Get all the items of the given content type related to this item. """ qs = self.get_queryset() return qs.filter(content_type__name=content_type)
python
def get_content_type(self, content_type): """ Get all the items of the given content type related to this item. """ qs = self.get_queryset() return qs.filter(content_type__name=content_type)
[ "def", "get_content_type", "(", "self", ",", "content_type", ")", ":", "qs", "=", "self", ".", "get_queryset", "(", ")", "return", "qs", ".", "filter", "(", "content_type__name", "=", "content_type", ")" ]
Get all the items of the given content type related to this item.
[ "Get", "all", "the", "items", "of", "the", "given", "content", "type", "related", "to", "this", "item", "." ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/models.py#L109-L114
train
callowayproject/django-categories
categories/models.py
CategoryRelationManager.get_relation_type
def get_relation_type(self, relation_type): """ Get all the items of the given relationship type related to this item. """ qs = self.get_queryset() return qs.filter(relation_type=relation_type)
python
def get_relation_type(self, relation_type): """ Get all the items of the given relationship type related to this item. """ qs = self.get_queryset() return qs.filter(relation_type=relation_type)
[ "def", "get_relation_type", "(", "self", ",", "relation_type", ")", ":", "qs", "=", "self", ".", "get_queryset", "(", ")", "return", "qs", ".", "filter", "(", "relation_type", "=", "relation_type", ")" ]
Get all the items of the given relationship type related to this item.
[ "Get", "all", "the", "items", "of", "the", "given", "relationship", "type", "related", "to", "this", "item", "." ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/models.py#L116-L121
train
callowayproject/django-categories
categories/apps.py
handle_class_prepared
def handle_class_prepared(sender, **kwargs): """ See if this class needs registering of fields """ from .settings import M2M_REGISTRY, FK_REGISTRY from .registration import registry sender_app = sender._meta.app_label sender_name = sender._meta.model_name for key, val in list(FK_REGISTR...
python
def handle_class_prepared(sender, **kwargs): """ See if this class needs registering of fields """ from .settings import M2M_REGISTRY, FK_REGISTRY from .registration import registry sender_app = sender._meta.app_label sender_name = sender._meta.model_name for key, val in list(FK_REGISTR...
[ "def", "handle_class_prepared", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "from", ".", "settings", "import", "M2M_REGISTRY", ",", "FK_REGISTRY", "from", ".", "registration", "import", "registry", "sender_app", "=", "sender", ".", "_meta", ".", "app_lab...
See if this class needs registering of fields
[ "See", "if", "this", "class", "needs", "registering", "of", "fields" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/apps.py#L20-L37
train
callowayproject/django-categories
categories/editor/tree_editor.py
TreeEditor.get_queryset
def get_queryset(self, request): """ Returns a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() qs.__class__ = TreeEditorQuerySet return qs
python
def get_queryset(self, request): """ Returns a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() qs.__class__ = TreeEditorQuerySet return qs
[ "def", "get_queryset", "(", "self", ",", "request", ")", ":", "qs", "=", "self", ".", "model", ".", "_default_manager", ".", "get_queryset", "(", ")", "qs", ".", "__class__", "=", "TreeEditorQuerySet", "return", "qs" ]
Returns a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view.
[ "Returns", "a", "QuerySet", "of", "all", "model", "instances", "that", "can", "be", "edited", "by", "the", "admin", "site", ".", "This", "is", "used", "by", "changelist_view", "." ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/editor/tree_editor.py#L283-L290
train
callowayproject/django-categories
categories/base.py
CategoryBaseAdmin.deactivate
def deactivate(self, request, queryset): """ Set active to False for selected items """ selected_cats = self.model.objects.filter( pk__in=[int(x) for x in request.POST.getlist('_selected_action')]) for item in selected_cats: if item.active: ...
python
def deactivate(self, request, queryset): """ Set active to False for selected items """ selected_cats = self.model.objects.filter( pk__in=[int(x) for x in request.POST.getlist('_selected_action')]) for item in selected_cats: if item.active: ...
[ "def", "deactivate", "(", "self", ",", "request", ",", "queryset", ")", ":", "selected_cats", "=", "self", ".", "model", ".", "objects", ".", "filter", "(", "pk__in", "=", "[", "int", "(", "x", ")", "for", "x", "in", "request", ".", "POST", ".", "g...
Set active to False for selected items
[ "Set", "active", "to", "False", "for", "selected", "items" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/base.py#L144-L155
train
callowayproject/django-categories
categories/management/commands/import_categories.py
Command.get_indent
def get_indent(self, string): """ Look through the string and count the spaces """ indent_amt = 0 if string[0] == '\t': return '\t' for char in string: if char == ' ': indent_amt += 1 else: return ' ' * ...
python
def get_indent(self, string): """ Look through the string and count the spaces """ indent_amt = 0 if string[0] == '\t': return '\t' for char in string: if char == ' ': indent_amt += 1 else: return ' ' * ...
[ "def", "get_indent", "(", "self", ",", "string", ")", ":", "indent_amt", "=", "0", "if", "string", "[", "0", "]", "==", "'\\t'", ":", "return", "'\\t'", "for", "char", "in", "string", ":", "if", "char", "==", "' '", ":", "indent_amt", "+=", "1", "e...
Look through the string and count the spaces
[ "Look", "through", "the", "string", "and", "count", "the", "spaces" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/management/commands/import_categories.py#L16-L28
train
callowayproject/django-categories
categories/management/commands/import_categories.py
Command.make_category
def make_category(self, string, parent=None, order=1): """ Make and save a category object from a string """ cat = Category( name=string.strip(), slug=slugify(SLUG_TRANSLITERATOR(string.strip()))[:49], # arent=parent, order=order ) ...
python
def make_category(self, string, parent=None, order=1): """ Make and save a category object from a string """ cat = Category( name=string.strip(), slug=slugify(SLUG_TRANSLITERATOR(string.strip()))[:49], # arent=parent, order=order ) ...
[ "def", "make_category", "(", "self", ",", "string", ",", "parent", "=", "None", ",", "order", "=", "1", ")", ":", "cat", "=", "Category", "(", "name", "=", "string", ".", "strip", "(", ")", ",", "slug", "=", "slugify", "(", "SLUG_TRANSLITERATOR", "("...
Make and save a category object from a string
[ "Make", "and", "save", "a", "category", "object", "from", "a", "string" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/management/commands/import_categories.py#L31-L46
train
callowayproject/django-categories
categories/management/commands/import_categories.py
Command.parse_lines
def parse_lines(self, lines): """ Do the work of parsing each line """ indent = '' level = 0 if lines[0][0] == ' ' or lines[0][0] == '\t': raise CommandError("The first line in the file cannot start with a space or tab.") # This keeps track of the cu...
python
def parse_lines(self, lines): """ Do the work of parsing each line """ indent = '' level = 0 if lines[0][0] == ' ' or lines[0][0] == '\t': raise CommandError("The first line in the file cannot start with a space or tab.") # This keeps track of the cu...
[ "def", "parse_lines", "(", "self", ",", "lines", ")", ":", "indent", "=", "''", "level", "=", "0", "if", "lines", "[", "0", "]", "[", "0", "]", "==", "' '", "or", "lines", "[", "0", "]", "[", "0", "]", "==", "'\\t'", ":", "raise", "CommandError...
Do the work of parsing each line
[ "Do", "the", "work", "of", "parsing", "each", "line" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/management/commands/import_categories.py#L48-L74
train
callowayproject/django-categories
categories/management/commands/import_categories.py
Command.handle
def handle(self, *file_paths, **options): """ Handle the basic import """ import os for file_path in file_paths: if not os.path.isfile(file_path): print("File %s not found." % file_path) continue f = open(file_path, 'r') ...
python
def handle(self, *file_paths, **options): """ Handle the basic import """ import os for file_path in file_paths: if not os.path.isfile(file_path): print("File %s not found." % file_path) continue f = open(file_path, 'r') ...
[ "def", "handle", "(", "self", ",", "*", "file_paths", ",", "*", "*", "options", ")", ":", "import", "os", "for", "file_path", "in", "file_paths", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "print", "(", "\"File %s...
Handle the basic import
[ "Handle", "the", "basic", "import" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/management/commands/import_categories.py#L76-L90
train
callowayproject/django-categories
categories/templatetags/category_tags.py
get_cat_model
def get_cat_model(model): """ Return a class from a string or class """ try: if isinstance(model, string_types): model_class = apps.get_model(*model.split(".")) elif issubclass(model, CategoryBase): model_class = model if model_class is None: r...
python
def get_cat_model(model): """ Return a class from a string or class """ try: if isinstance(model, string_types): model_class = apps.get_model(*model.split(".")) elif issubclass(model, CategoryBase): model_class = model if model_class is None: r...
[ "def", "get_cat_model", "(", "model", ")", ":", "try", ":", "if", "isinstance", "(", "model", ",", "string_types", ")", ":", "model_class", "=", "apps", ".", "get_model", "(", "*", "model", ".", "split", "(", "\".\"", ")", ")", "elif", "issubclass", "(...
Return a class from a string or class
[ "Return", "a", "class", "from", "a", "string", "or", "class" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L29-L42
train
callowayproject/django-categories
categories/templatetags/category_tags.py
get_category
def get_category(category_string, model=Category): """ Convert a string, including a path, and return the Category object """ model_class = get_cat_model(model) category = str(category_string).strip("'\"") category = category.strip('/') cat_list = category.split('/') if len(cat_list) ==...
python
def get_category(category_string, model=Category): """ Convert a string, including a path, and return the Category object """ model_class = get_cat_model(model) category = str(category_string).strip("'\"") category = category.strip('/') cat_list = category.split('/') if len(cat_list) ==...
[ "def", "get_category", "(", "category_string", ",", "model", "=", "Category", ")", ":", "model_class", "=", "get_cat_model", "(", "model", ")", "category", "=", "str", "(", "category_string", ")", ".", "strip", "(", "\"'\\\"\"", ")", "category", "=", "catego...
Convert a string, including a path, and return the Category object
[ "Convert", "a", "string", "including", "a", "path", "and", "return", "the", "Category", "object" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L45-L69
train
callowayproject/django-categories
categories/templatetags/category_tags.py
get_category_drilldown
def get_category_drilldown(parser, token): """ Retrieves the specified category, its ancestors and its immediate children as an iterable. Syntax:: {% get_category_drilldown "category name" [using "app.Model"] as varname %} Example:: {% get_category_drilldown "/Grandparent/Parent"...
python
def get_category_drilldown(parser, token): """ Retrieves the specified category, its ancestors and its immediate children as an iterable. Syntax:: {% get_category_drilldown "category name" [using "app.Model"] as varname %} Example:: {% get_category_drilldown "/Grandparent/Parent"...
[ "def", "get_category_drilldown", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "error_str", "=", "'%(tagname)s tag should be in the format {%% %(tagname)s '", "'\"category name\" [using \"app.Model\"] as varname %%} or '", "'{%% %...
Retrieves the specified category, its ancestors and its immediate children as an iterable. Syntax:: {% get_category_drilldown "category name" [using "app.Model"] as varname %} Example:: {% get_category_drilldown "/Grandparent/Parent" [using "app.Model"] as family %} or :: {...
[ "Retrieves", "the", "specified", "category", "its", "ancestors", "and", "its", "immediate", "children", "as", "an", "iterable", "." ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L95-L136
train
callowayproject/django-categories
categories/templatetags/category_tags.py
get_top_level_categories
def get_top_level_categories(parser, token): """ Retrieves an alphabetical list of all the categories that have no parents. Syntax:: {% get_top_level_categories [using "app.Model"] as categories %} Returns an list of categories [<category>, <category>, <category, ...] """ bits = token...
python
def get_top_level_categories(parser, token): """ Retrieves an alphabetical list of all the categories that have no parents. Syntax:: {% get_top_level_categories [using "app.Model"] as categories %} Returns an list of categories [<category>, <category>, <category, ...] """ bits = token...
[ "def", "get_top_level_categories", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "usage", "=", "'Usage: {%% %s [using \"app.Model\"] as <variable> %%}'", "%", "bits", "[", "0", "]", "if", "len", "(", "bits", ")", ...
Retrieves an alphabetical list of all the categories that have no parents. Syntax:: {% get_top_level_categories [using "app.Model"] as categories %} Returns an list of categories [<category>, <category>, <category, ...]
[ "Retrieves", "an", "alphabetical", "list", "of", "all", "the", "categories", "that", "have", "no", "parents", "." ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L237-L264
train
callowayproject/django-categories
categories/templatetags/category_tags.py
tree_queryset
def tree_queryset(value): """ Converts a normal queryset from an MPTT model to include all the ancestors so a filtered subset of items can be formatted correctly """ from django.db.models.query import QuerySet from copy import deepcopy if not isinstance(value, QuerySet): return value...
python
def tree_queryset(value): """ Converts a normal queryset from an MPTT model to include all the ancestors so a filtered subset of items can be formatted correctly """ from django.db.models.query import QuerySet from copy import deepcopy if not isinstance(value, QuerySet): return value...
[ "def", "tree_queryset", "(", "value", ")", ":", "from", "django", ".", "db", ".", "models", ".", "query", "import", "QuerySet", "from", "copy", "import", "deepcopy", "if", "not", "isinstance", "(", "value", ",", "QuerySet", ")", ":", "return", "value", "...
Converts a normal queryset from an MPTT model to include all the ancestors so a filtered subset of items can be formatted correctly
[ "Converts", "a", "normal", "queryset", "from", "an", "MPTT", "model", "to", "include", "all", "the", "ancestors", "so", "a", "filtered", "subset", "of", "items", "can", "be", "formatted", "correctly" ]
3765851320a79b12c6d3306f3784a2302ea64812
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L346-L377
train
maweigert/gputools
gputools/convolve/convolve.py
convolve
def convolve(data, h, res_g=None, sub_blocks=None): """ convolves 1d-3d data with kernel h data and h can either be numpy arrays or gpu buffer objects (OCLArray, which must be float32 then) boundary conditions are clamping to zero at edge. """ if not len(data.shape) in [1, 2, 3]: ...
python
def convolve(data, h, res_g=None, sub_blocks=None): """ convolves 1d-3d data with kernel h data and h can either be numpy arrays or gpu buffer objects (OCLArray, which must be float32 then) boundary conditions are clamping to zero at edge. """ if not len(data.shape) in [1, 2, 3]: ...
[ "def", "convolve", "(", "data", ",", "h", ",", "res_g", "=", "None", ",", "sub_blocks", "=", "None", ")", ":", "if", "not", "len", "(", "data", ".", "shape", ")", "in", "[", "1", ",", "2", ",", "3", "]", ":", "raise", "ValueError", "(", "\"dim ...
convolves 1d-3d data with kernel h data and h can either be numpy arrays or gpu buffer objects (OCLArray, which must be float32 then) boundary conditions are clamping to zero at edge.
[ "convolves", "1d", "-", "3d", "data", "with", "kernel", "h" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/convolve.py#L18-L54
train
maweigert/gputools
gputools/convolve/convolve.py
_convolve3_old
def _convolve3_old(data, h, dev=None): """convolves 3d data with kernel h on the GPU Device dev boundary conditions are clamping to edge. h is converted to float32 if dev == None the default one is used """ if dev is None: dev = get_device() if dev is None: raise ValueErro...
python
def _convolve3_old(data, h, dev=None): """convolves 3d data with kernel h on the GPU Device dev boundary conditions are clamping to edge. h is converted to float32 if dev == None the default one is used """ if dev is None: dev = get_device() if dev is None: raise ValueErro...
[ "def", "_convolve3_old", "(", "data", ",", "h", ",", "dev", "=", "None", ")", ":", "if", "dev", "is", "None", ":", "dev", "=", "get_device", "(", ")", "if", "dev", "is", "None", ":", "raise", "ValueError", "(", "\"no OpenCLDevice found...\"", ")", "dty...
convolves 3d data with kernel h on the GPU Device dev boundary conditions are clamping to edge. h is converted to float32 if dev == None the default one is used
[ "convolves", "3d", "data", "with", "kernel", "h", "on", "the", "GPU", "Device", "dev", "boundary", "conditions", "are", "clamping", "to", "edge", ".", "h", "is", "converted", "to", "float32" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/convolve.py#L116-L151
train
maweigert/gputools
gputools/transforms/scale.py
_scale_shape
def _scale_shape(dshape, scale = (1,1,1)): """returns the shape after scaling (should be the same as ndimage.zoom""" nshape = np.round(np.array(dshape) * np.array(scale)) return tuple(nshape.astype(np.int))
python
def _scale_shape(dshape, scale = (1,1,1)): """returns the shape after scaling (should be the same as ndimage.zoom""" nshape = np.round(np.array(dshape) * np.array(scale)) return tuple(nshape.astype(np.int))
[ "def", "_scale_shape", "(", "dshape", ",", "scale", "=", "(", "1", ",", "1", ",", "1", ")", ")", ":", "nshape", "=", "np", ".", "round", "(", "np", ".", "array", "(", "dshape", ")", "*", "np", ".", "array", "(", "scale", ")", ")", "return", "...
returns the shape after scaling (should be the same as ndimage.zoom
[ "returns", "the", "shape", "after", "scaling", "(", "should", "be", "the", "same", "as", "ndimage", ".", "zoom" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/transforms/scale.py#L17-L20
train
maweigert/gputools
gputools/fft/fftshift.py
fftshift
def fftshift(arr_obj, axes = None, res_g = None, return_buffer = False): """ gpu version of fftshift for numpy arrays or OCLArrays Parameters ---------- arr_obj: numpy array or OCLArray (float32/complex64) the array to be fftshifted axes: list or None the axes over which to shif...
python
def fftshift(arr_obj, axes = None, res_g = None, return_buffer = False): """ gpu version of fftshift for numpy arrays or OCLArrays Parameters ---------- arr_obj: numpy array or OCLArray (float32/complex64) the array to be fftshifted axes: list or None the axes over which to shif...
[ "def", "fftshift", "(", "arr_obj", ",", "axes", "=", "None", ",", "res_g", "=", "None", ",", "return_buffer", "=", "False", ")", ":", "if", "axes", "is", "None", ":", "axes", "=", "list", "(", "range", "(", "arr_obj", ".", "ndim", ")", ")", "if", ...
gpu version of fftshift for numpy arrays or OCLArrays Parameters ---------- arr_obj: numpy array or OCLArray (float32/complex64) the array to be fftshifted axes: list or None the axes over which to shift (like np.fft.fftshift) if None, all axes are taken res_g: if gi...
[ "gpu", "version", "of", "fftshift", "for", "numpy", "arrays", "or", "OCLArrays" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/fftshift.py#L27-L80
train
maweigert/gputools
gputools/fft/fftshift.py
_fftshift_single
def _fftshift_single(d_g, res_g, ax = 0): """ basic fftshift of an OCLArray shape(d_g) = [N_0,N_1...., N, .... N_{k-1, N_k] = [N1, N, N2] the we can address each element in the flat buffer by index = i + N2*j + N2*N*k where i = 1 .. N2 j = 1 .. N k = 1 .. N1 ...
python
def _fftshift_single(d_g, res_g, ax = 0): """ basic fftshift of an OCLArray shape(d_g) = [N_0,N_1...., N, .... N_{k-1, N_k] = [N1, N, N2] the we can address each element in the flat buffer by index = i + N2*j + N2*N*k where i = 1 .. N2 j = 1 .. N k = 1 .. N1 ...
[ "def", "_fftshift_single", "(", "d_g", ",", "res_g", ",", "ax", "=", "0", ")", ":", "dtype_kernel_name", "=", "{", "np", ".", "float32", ":", "\"fftshift_1_f\"", ",", "np", ".", "complex64", ":", "\"fftshift_1_c\"", "}", "N", "=", "d_g", ".", "shape", ...
basic fftshift of an OCLArray shape(d_g) = [N_0,N_1...., N, .... N_{k-1, N_k] = [N1, N, N2] the we can address each element in the flat buffer by index = i + N2*j + N2*N*k where i = 1 .. N2 j = 1 .. N k = 1 .. N1 and the swap of elements is performed on the inde...
[ "basic", "fftshift", "of", "an", "OCLArray" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/fftshift.py#L83-L119
train
maweigert/gputools
gputools/fft/oclfft_convolve.py
fft_convolve
def fft_convolve(data, h, res_g = None, plan = None, inplace = False, kernel_is_fft = False, kernel_is_fftshifted = False): """ convolves data with kernel h via FFTs data should be either a numpy array or a OCLArray (see doc for fft) both data an...
python
def fft_convolve(data, h, res_g = None, plan = None, inplace = False, kernel_is_fft = False, kernel_is_fftshifted = False): """ convolves data with kernel h via FFTs data should be either a numpy array or a OCLArray (see doc for fft) both data an...
[ "def", "fft_convolve", "(", "data", ",", "h", ",", "res_g", "=", "None", ",", "plan", "=", "None", ",", "inplace", "=", "False", ",", "kernel_is_fft", "=", "False", ",", "kernel_is_fftshifted", "=", "False", ")", ":", "if", "isinstance", "(", "data", "...
convolves data with kernel h via FFTs data should be either a numpy array or a OCLArray (see doc for fft) both data and h should be same shape if data/h are OCLArrays, then: - type should be complex64 - shape should be equal and power of two - h is assumed to be already fftshi...
[ "convolves", "data", "with", "kernel", "h", "via", "FFTs" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/oclfft_convolve.py#L15-L45
train
maweigert/gputools
gputools/fft/oclfft_convolve.py
_fft_convolve_numpy
def _fft_convolve_numpy(data, h, plan = None, kernel_is_fft = False, kernel_is_fftshifted = False): """ convolving via opencl fft for numpy arrays data and h must have the same size """ if data.shape != h.shape: raise ValueError("data and kernel ...
python
def _fft_convolve_numpy(data, h, plan = None, kernel_is_fft = False, kernel_is_fftshifted = False): """ convolving via opencl fft for numpy arrays data and h must have the same size """ if data.shape != h.shape: raise ValueError("data and kernel ...
[ "def", "_fft_convolve_numpy", "(", "data", ",", "h", ",", "plan", "=", "None", ",", "kernel_is_fft", "=", "False", ",", "kernel_is_fftshifted", "=", "False", ")", ":", "if", "data", ".", "shape", "!=", "h", ".", "shape", ":", "raise", "ValueError", "(", ...
convolving via opencl fft for numpy arrays data and h must have the same size
[ "convolving", "via", "opencl", "fft", "for", "numpy", "arrays" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/oclfft_convolve.py#L49-L80
train
maweigert/gputools
gputools/fft/oclfft_convolve.py
_fft_convolve_gpu
def _fft_convolve_gpu(data_g, h_g, res_g = None, plan = None, inplace = False, kernel_is_fft = False): """ fft convolve for gpu buffer """ assert_bufs_type(np.complex64,data_g,h_g) if data_g.shape != h_g.shape: raise ValueError("data and kernel mu...
python
def _fft_convolve_gpu(data_g, h_g, res_g = None, plan = None, inplace = False, kernel_is_fft = False): """ fft convolve for gpu buffer """ assert_bufs_type(np.complex64,data_g,h_g) if data_g.shape != h_g.shape: raise ValueError("data and kernel mu...
[ "def", "_fft_convolve_gpu", "(", "data_g", ",", "h_g", ",", "res_g", "=", "None", ",", "plan", "=", "None", ",", "inplace", "=", "False", ",", "kernel_is_fft", "=", "False", ")", ":", "assert_bufs_type", "(", "np", ".", "complex64", ",", "data_g", ",", ...
fft convolve for gpu buffer
[ "fft", "convolve", "for", "gpu", "buffer" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/oclfft_convolve.py#L83-L124
train
maweigert/gputools
gputools/convolve/median_filter.py
median_filter
def median_filter(data, size=3, cval = 0, res_g=None, sub_blocks=None): """ median filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider cval: scalar, ...
python
def median_filter(data, size=3, cval = 0, res_g=None, sub_blocks=None): """ median filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider cval: scalar, ...
[ "def", "median_filter", "(", "data", ",", "size", "=", "3", ",", "cval", "=", "0", ",", "res_g", "=", "None", ",", "sub_blocks", "=", "None", ")", ":", "if", "data", ".", "ndim", "==", "2", ":", "_filt", "=", "make_filter", "(", "_median_filter_gpu_2...
median filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider cval: scalar, the constant value for out of border access (cf mode = "constant") res_g: O...
[ "median", "filter", "of", "given", "size" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/median_filter.py#L112-L141
train
maweigert/gputools
gputools/transforms/transformations.py
rotate
def rotate(data, axis=(1., 0, 0), angle=0., center=None, mode="constant", interpolation="linear"): """ rotates data around axis by a given angle Parameters ---------- data: ndarray 3d array axis: tuple axis to rotate by angle about axis = (x,y,z) angle: float cen...
python
def rotate(data, axis=(1., 0, 0), angle=0., center=None, mode="constant", interpolation="linear"): """ rotates data around axis by a given angle Parameters ---------- data: ndarray 3d array axis: tuple axis to rotate by angle about axis = (x,y,z) angle: float cen...
[ "def", "rotate", "(", "data", ",", "axis", "=", "(", "1.", ",", "0", ",", "0", ")", ",", "angle", "=", "0.", ",", "center", "=", "None", ",", "mode", "=", "\"constant\"", ",", "interpolation", "=", "\"linear\"", ")", ":", "if", "center", "is", "N...
rotates data around axis by a given angle Parameters ---------- data: ndarray 3d array axis: tuple axis to rotate by angle about axis = (x,y,z) angle: float center: tuple or None origin of rotation (cz,cy,cx) in pixels if None, center is the middle of dat...
[ "rotates", "data", "around", "axis", "by", "a", "given", "angle" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/transforms/transformations.py#L128-L171
train
maweigert/gputools
gputools/transforms/transformations.py
map_coordinates
def map_coordinates(data, coordinates, interpolation="linear", mode='constant'): """ Map data to new coordinates by interpolation. The array of coordinates is used to find, for each point in the output, the corresponding coordinates in the input. should correspond to scipy.ndima...
python
def map_coordinates(data, coordinates, interpolation="linear", mode='constant'): """ Map data to new coordinates by interpolation. The array of coordinates is used to find, for each point in the output, the corresponding coordinates in the input. should correspond to scipy.ndima...
[ "def", "map_coordinates", "(", "data", ",", "coordinates", ",", "interpolation", "=", "\"linear\"", ",", "mode", "=", "'constant'", ")", ":", "if", "not", "(", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", "and", "data", ".", "ndim", "in", ...
Map data to new coordinates by interpolation. The array of coordinates is used to find, for each point in the output, the corresponding coordinates in the input. should correspond to scipy.ndimage.map_coordinates Parameters ---------- data coordinates output interpolation m...
[ "Map", "data", "to", "new", "coordinates", "by", "interpolation", ".", "The", "array", "of", "coordinates", "is", "used", "to", "find", "for", "each", "point", "in", "the", "output", "the", "corresponding", "coordinates", "in", "the", "input", "." ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/transforms/transformations.py#L174-L237
train
maweigert/gputools
gputools/utils/utils.py
pad_to_shape
def pad_to_shape(d, dshape, mode = "constant"): """ pad array d to shape dshape """ if d.shape == dshape: return d diff = np.array(dshape)- np.array(d.shape) #first shrink slices = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff) res = d[slices] #then pad...
python
def pad_to_shape(d, dshape, mode = "constant"): """ pad array d to shape dshape """ if d.shape == dshape: return d diff = np.array(dshape)- np.array(d.shape) #first shrink slices = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff) res = d[slices] #then pad...
[ "def", "pad_to_shape", "(", "d", ",", "dshape", ",", "mode", "=", "\"constant\"", ")", ":", "if", "d", ".", "shape", "==", "dshape", ":", "return", "d", "diff", "=", "np", ".", "array", "(", "dshape", ")", "-", "np", ".", "array", "(", "d", ".", ...
pad array d to shape dshape
[ "pad", "array", "d", "to", "shape", "dshape" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/utils/utils.py#L4-L17
train
maweigert/gputools
gputools/utils/utils.py
pad_to_power2
def pad_to_power2(data, axis = None, mode="constant"): """ pad data to a shape of power 2 if axis == None all axis are padded """ if axis is None: axis = list(range(data.ndim)) if np.all([_is_power2(n) for i, n in enumerate(data.shape) if i in axis]): return data else: ...
python
def pad_to_power2(data, axis = None, mode="constant"): """ pad data to a shape of power 2 if axis == None all axis are padded """ if axis is None: axis = list(range(data.ndim)) if np.all([_is_power2(n) for i, n in enumerate(data.shape) if i in axis]): return data else: ...
[ "def", "pad_to_power2", "(", "data", ",", "axis", "=", "None", ",", "mode", "=", "\"constant\"", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "list", "(", "range", "(", "data", ".", "ndim", ")", ")", "if", "np", ".", "all", "(", "[", ...
pad data to a shape of power 2 if axis == None all axis are padded
[ "pad", "data", "to", "a", "shape", "of", "power", "2", "if", "axis", "==", "None", "all", "axis", "are", "padded" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/utils/utils.py#L27-L38
train
maweigert/gputools
gputools/convolve/generic_separable_filters.py
max_filter
def max_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)): """ maximum filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray st...
python
def max_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)): """ maximum filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray st...
[ "def", "max_filter", "(", "data", ",", "size", "=", "7", ",", "res_g", "=", "None", ",", "sub_blocks", "=", "(", "1", ",", "1", ",", "1", ")", ")", ":", "if", "data", ".", "ndim", "==", "2", ":", "_filt", "=", "make_filter", "(", "_generic_filter...
maximum filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray store result in buffer if given sub_blocks: perform over subblock tili...
[ "maximum", "filter", "of", "given", "size" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L115-L139
train
maweigert/gputools
gputools/convolve/generic_separable_filters.py
min_filter
def min_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)): """ minimum filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray st...
python
def min_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)): """ minimum filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray st...
[ "def", "min_filter", "(", "data", ",", "size", "=", "7", ",", "res_g", "=", "None", ",", "sub_blocks", "=", "(", "1", ",", "1", ",", "1", ")", ")", ":", "if", "data", ".", "ndim", "==", "2", ":", "_filt", "=", "make_filter", "(", "_generic_filter...
minimum filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray store result in buffer if given sub_blocks: perform over subblock tili...
[ "minimum", "filter", "of", "given", "size" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L142-L167
train
maweigert/gputools
gputools/convolve/generic_separable_filters.py
uniform_filter
def uniform_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1), normalized = True): """ mean filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g:...
python
def uniform_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1), normalized = True): """ mean filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g:...
[ "def", "uniform_filter", "(", "data", ",", "size", "=", "7", ",", "res_g", "=", "None", ",", "sub_blocks", "=", "(", "1", ",", "1", ",", "1", ")", ",", "normalized", "=", "True", ")", ":", "if", "normalized", ":", "if", "np", ".", "isscalar", "("...
mean filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray store result in buffer if given sub_blocks: perform over subblock tiling ...
[ "mean", "filter", "of", "given", "size" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L171-L210
train
maweigert/gputools
gputools/convolve/generic_separable_filters.py
_gauss_filter
def _gauss_filter(data, sigma=4, res_g=None, sub_blocks=(1, 1, 1)): """ gaussian filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray ...
python
def _gauss_filter(data, sigma=4, res_g=None, sub_blocks=(1, 1, 1)): """ gaussian filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray ...
[ "def", "_gauss_filter", "(", "data", ",", "sigma", "=", "4", ",", "res_g", "=", "None", ",", "sub_blocks", "=", "(", "1", ",", "1", ",", "1", ")", ")", ":", "truncate", "=", "4.", "radius", "=", "tuple", "(", "int", "(", "truncate", "*", "s", "...
gaussian filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray store result in buffer if given sub_blocks: perform over subblock til...
[ "gaussian", "filter", "of", "given", "size" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L216-L248
train
maweigert/gputools
gputools/separable/separable_approx.py
_separable_series2
def _separable_series2(h, N=1): """ finds separable approximations to the 2d function 2d h returns res = (hx, hy)[N] s.t. h \approx sum_i outer(res[i,0],res[i,1]) """ if min(h.shape)<N: raise ValueError("smallest dimension of h is smaller than approximation order! (%s < %s)"%(min(h.shape),N...
python
def _separable_series2(h, N=1): """ finds separable approximations to the 2d function 2d h returns res = (hx, hy)[N] s.t. h \approx sum_i outer(res[i,0],res[i,1]) """ if min(h.shape)<N: raise ValueError("smallest dimension of h is smaller than approximation order! (%s < %s)"%(min(h.shape),N...
[ "def", "_separable_series2", "(", "h", ",", "N", "=", "1", ")", ":", "if", "min", "(", "h", ".", "shape", ")", "<", "N", ":", "raise", "ValueError", "(", "\"smallest dimension of h is smaller than approximation order! (%s < %s)\"", "%", "(", "min", "(", "h", ...
finds separable approximations to the 2d function 2d h returns res = (hx, hy)[N] s.t. h \approx sum_i outer(res[i,0],res[i,1])
[ "finds", "separable", "approximations", "to", "the", "2d", "function", "2d", "h" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/separable/separable_approx.py#L16-L29
train
maweigert/gputools
gputools/separable/separable_approx.py
_separable_approx2
def _separable_approx2(h, N=1): """ returns the N first approximations to the 2d function h whose sum should be h """ return np.cumsum([np.outer(fy, fx) for fy, fx in _separable_series2(h, N)], 0)
python
def _separable_approx2(h, N=1): """ returns the N first approximations to the 2d function h whose sum should be h """ return np.cumsum([np.outer(fy, fx) for fy, fx in _separable_series2(h, N)], 0)
[ "def", "_separable_approx2", "(", "h", ",", "N", "=", "1", ")", ":", "return", "np", ".", "cumsum", "(", "[", "np", ".", "outer", "(", "fy", ",", "fx", ")", "for", "fy", ",", "fx", "in", "_separable_series2", "(", "h", ",", "N", ")", "]", ",", ...
returns the N first approximations to the 2d function h whose sum should be h
[ "returns", "the", "N", "first", "approximations", "to", "the", "2d", "function", "h", "whose", "sum", "should", "be", "h" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/separable/separable_approx.py#L32-L36
train
maweigert/gputools
gputools/separable/separable_approx.py
_separable_approx3
def _separable_approx3(h, N=1): """ returns the N first approximations to the 3d function h """ return np.cumsum([np.einsum("i,j,k", fz, fy, fx) for fz, fy, fx in _separable_series3(h, N)], 0)
python
def _separable_approx3(h, N=1): """ returns the N first approximations to the 3d function h """ return np.cumsum([np.einsum("i,j,k", fz, fy, fx) for fz, fy, fx in _separable_series3(h, N)], 0)
[ "def", "_separable_approx3", "(", "h", ",", "N", "=", "1", ")", ":", "return", "np", ".", "cumsum", "(", "[", "np", ".", "einsum", "(", "\"i,j,k\"", ",", "fz", ",", "fy", ",", "fx", ")", "for", "fz", ",", "fy", ",", "fx", "in", "_separable_series...
returns the N first approximations to the 3d function h
[ "returns", "the", "N", "first", "approximations", "to", "the", "3d", "function", "h" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/separable/separable_approx.py#L85-L88
train
maweigert/gputools
gputools/separable/separable_approx.py
separable_approx
def separable_approx(h, N=1): """ finds the k-th rank approximation to h, where k = 1..N similar to separable_series Parameters ---------- h: ndarray input array (2 or 2 dimensional) N: int order of approximation Returns ------- all N apprxoimations res[i],...
python
def separable_approx(h, N=1): """ finds the k-th rank approximation to h, where k = 1..N similar to separable_series Parameters ---------- h: ndarray input array (2 or 2 dimensional) N: int order of approximation Returns ------- all N apprxoimations res[i],...
[ "def", "separable_approx", "(", "h", ",", "N", "=", "1", ")", ":", "if", "h", ".", "ndim", "==", "2", ":", "return", "_separable_approx2", "(", "h", ",", "N", ")", "elif", "h", ".", "ndim", "==", "3", ":", "return", "_separable_approx3", "(", "h", ...
finds the k-th rank approximation to h, where k = 1..N similar to separable_series Parameters ---------- h: ndarray input array (2 or 2 dimensional) N: int order of approximation Returns ------- all N apprxoimations res[i], the i-th approximation
[ "finds", "the", "k", "-", "th", "rank", "approximation", "to", "h", "where", "k", "=", "1", "..", "N" ]
6ab26efeb05dceef74cf13aadeeeb9b009b529dd
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/separable/separable_approx.py#L127-L150
train
alculquicondor/psqlparse
psqlparse/nodes/nodes.py
Node.tables
def tables(self): """ Generic method that does a depth-first search on the node attributes. Child classes should override this method for better performance. """ _tables = set() for attr in six.itervalues(self.__dict__): if isinstance(attr, list): ...
python
def tables(self): """ Generic method that does a depth-first search on the node attributes. Child classes should override this method for better performance. """ _tables = set() for attr in six.itervalues(self.__dict__): if isinstance(attr, list): ...
[ "def", "tables", "(", "self", ")", ":", "_tables", "=", "set", "(", ")", "for", "attr", "in", "six", ".", "itervalues", "(", "self", ".", "__dict__", ")", ":", "if", "isinstance", "(", "attr", ",", "list", ")", ":", "for", "item", "in", "attr", "...
Generic method that does a depth-first search on the node attributes. Child classes should override this method for better performance.
[ "Generic", "method", "that", "does", "a", "depth", "-", "first", "search", "on", "the", "node", "attributes", "." ]
9c2af04f45ddc4068d7fd87580612457d374e97d
https://github.com/alculquicondor/psqlparse/blob/9c2af04f45ddc4068d7fd87580612457d374e97d/psqlparse/nodes/nodes.py#L6-L22
train
sloria/konch
docopt.py
Pattern.fix_identities
def fix_identities(self, uniq=None): """Make pattern-tree tips point to same object if they are equal.""" if not hasattr(self, 'children'): return self uniq = list(set(self.flat())) if uniq is None else uniq for i, child in enumerate(self.children): if not hasattr...
python
def fix_identities(self, uniq=None): """Make pattern-tree tips point to same object if they are equal.""" if not hasattr(self, 'children'): return self uniq = list(set(self.flat())) if uniq is None else uniq for i, child in enumerate(self.children): if not hasattr...
[ "def", "fix_identities", "(", "self", ",", "uniq", "=", "None", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'children'", ")", ":", "return", "self", "uniq", "=", "list", "(", "set", "(", "self", ".", "flat", "(", ")", ")", ")", "if", "un...
Make pattern-tree tips point to same object if they are equal.
[ "Make", "pattern", "-", "tree", "tips", "point", "to", "same", "object", "if", "they", "are", "equal", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L46-L56
train
sloria/konch
setup.py
find_version
def find_version(fname): """Attempts to find the version number in the file names fname. Raises RuntimeError if not found. """ version = "" with open(fname, "r") as fp: reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]') for line in fp: m = reg.match(line) ...
python
def find_version(fname): """Attempts to find the version number in the file names fname. Raises RuntimeError if not found. """ version = "" with open(fname, "r") as fp: reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]') for line in fp: m = reg.match(line) ...
[ "def", "find_version", "(", "fname", ")", ":", "version", "=", "\"\"", "with", "open", "(", "fname", ",", "\"r\"", ")", "as", "fp", ":", "reg", "=", "re", ".", "compile", "(", "r'__version__ = [\\'\"]([^\\'\"]*)[\\'\"]'", ")", "for", "line", "in", "fp", ...
Attempts to find the version number in the file names fname. Raises RuntimeError if not found.
[ "Attempts", "to", "find", "the", "version", "number", "in", "the", "file", "names", "fname", ".", "Raises", "RuntimeError", "if", "not", "found", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/setup.py#L46-L60
train
sloria/konch
konch.py
format_context
def format_context( context: Context, formatter: typing.Union[str, Formatter] = "full" ) -> str: """Output the a context dictionary as a string.""" if not context: return "" if callable(formatter): formatter_func = formatter else: if formatter in CONTEXT_FORMATTERS: ...
python
def format_context( context: Context, formatter: typing.Union[str, Formatter] = "full" ) -> str: """Output the a context dictionary as a string.""" if not context: return "" if callable(formatter): formatter_func = formatter else: if formatter in CONTEXT_FORMATTERS: ...
[ "def", "format_context", "(", "context", ":", "Context", ",", "formatter", ":", "typing", ".", "Union", "[", "str", ",", "Formatter", "]", "=", "\"full\"", ")", "->", "str", ":", "if", "not", "context", ":", "return", "\"\"", "if", "callable", "(", "fo...
Output the a context dictionary as a string.
[ "Output", "the", "a", "context", "dictionary", "as", "a", "string", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L245-L259
train
sloria/konch
konch.py
make_banner
def make_banner( text: typing.Optional[str] = None, context: typing.Optional[Context] = None, banner_template: typing.Optional[str] = None, context_format: ContextFormat = "full", ) -> str: """Generates a full banner with version info, the given text, and a formatted list of context variables. ...
python
def make_banner( text: typing.Optional[str] = None, context: typing.Optional[Context] = None, banner_template: typing.Optional[str] = None, context_format: ContextFormat = "full", ) -> str: """Generates a full banner with version info, the given text, and a formatted list of context variables. ...
[ "def", "make_banner", "(", "text", ":", "typing", ".", "Optional", "[", "str", "]", "=", "None", ",", "context", ":", "typing", ".", "Optional", "[", "Context", "]", "=", "None", ",", "banner_template", ":", "typing", ".", "Optional", "[", "str", "]", ...
Generates a full banner with version info, the given text, and a formatted list of context variables.
[ "Generates", "a", "full", "banner", "with", "version", "info", "the", "given", "text", "and", "a", "formatted", "list", "of", "context", "variables", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L269-L282
train
sloria/konch
konch.py
config
def config(config_dict: typing.Mapping) -> Config: """Configures the konch shell. This function should be called in a .konchrc file. :param dict config_dict: Dict that may contain 'context', 'banner', and/or 'shell' (default shell class to use). """ logger.debug(f"Updating with {config_dict...
python
def config(config_dict: typing.Mapping) -> Config: """Configures the konch shell. This function should be called in a .konchrc file. :param dict config_dict: Dict that may contain 'context', 'banner', and/or 'shell' (default shell class to use). """ logger.debug(f"Updating with {config_dict...
[ "def", "config", "(", "config_dict", ":", "typing", ".", "Mapping", ")", "->", "Config", ":", "logger", ".", "debug", "(", "f\"Updating with {config_dict}\"", ")", "_cfg", ".", "update", "(", "config_dict", ")", "return", "_cfg" ]
Configures the konch shell. This function should be called in a .konchrc file. :param dict config_dict: Dict that may contain 'context', 'banner', and/or 'shell' (default shell class to use).
[ "Configures", "the", "konch", "shell", ".", "This", "function", "should", "be", "called", "in", "a", ".", "konchrc", "file", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L828-L837
train
sloria/konch
konch.py
named_config
def named_config(name: str, config_dict: typing.Mapping) -> None: """Adds a named config to the config registry. The first argument may either be a string or a collection of strings. This function should be called in a .konchrc file. """ names = ( name if isinstance(name, Iterable) ...
python
def named_config(name: str, config_dict: typing.Mapping) -> None: """Adds a named config to the config registry. The first argument may either be a string or a collection of strings. This function should be called in a .konchrc file. """ names = ( name if isinstance(name, Iterable) ...
[ "def", "named_config", "(", "name", ":", "str", ",", "config_dict", ":", "typing", ".", "Mapping", ")", "->", "None", ":", "names", "=", "(", "name", "if", "isinstance", "(", "name", ",", "Iterable", ")", "and", "not", "isinstance", "(", "name", ",", ...
Adds a named config to the config registry. The first argument may either be a string or a collection of strings. This function should be called in a .konchrc file.
[ "Adds", "a", "named", "config", "to", "the", "config", "registry", ".", "The", "first", "argument", "may", "either", "be", "a", "string", "or", "a", "collection", "of", "strings", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L840-L852
train
sloria/konch
konch.py
__ensure_directory_in_path
def __ensure_directory_in_path(filename: Path) -> None: """Ensures that a file's directory is in the Python path. """ directory = Path(filename).parent.resolve() if directory not in sys.path: logger.debug(f"Adding {directory} to sys.path") sys.path.insert(0, str(directory))
python
def __ensure_directory_in_path(filename: Path) -> None: """Ensures that a file's directory is in the Python path. """ directory = Path(filename).parent.resolve() if directory not in sys.path: logger.debug(f"Adding {directory} to sys.path") sys.path.insert(0, str(directory))
[ "def", "__ensure_directory_in_path", "(", "filename", ":", "Path", ")", "->", "None", ":", "directory", "=", "Path", "(", "filename", ")", ".", "parent", ".", "resolve", "(", ")", "if", "directory", "not", "in", "sys", ".", "path", ":", "logger", ".", ...
Ensures that a file's directory is in the Python path.
[ "Ensures", "that", "a", "file", "s", "directory", "is", "in", "the", "Python", "path", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L861-L867
train
sloria/konch
konch.py
use_file
def use_file( filename: typing.Union[Path, str, None], trust: bool = False ) -> typing.Union[types.ModuleType, None]: """Load filename as a python file. Import ``filename`` and return it as a module. """ config_file = filename or resolve_path(CONFIG_FILE) def preview_unauthorized() -> None: ...
python
def use_file( filename: typing.Union[Path, str, None], trust: bool = False ) -> typing.Union[types.ModuleType, None]: """Load filename as a python file. Import ``filename`` and return it as a module. """ config_file = filename or resolve_path(CONFIG_FILE) def preview_unauthorized() -> None: ...
[ "def", "use_file", "(", "filename", ":", "typing", ".", "Union", "[", "Path", ",", "str", ",", "None", "]", ",", "trust", ":", "bool", "=", "False", ")", "->", "typing", ".", "Union", "[", "types", ".", "ModuleType", ",", "None", "]", ":", "config_...
Load filename as a python file. Import ``filename`` and return it as a module.
[ "Load", "filename", "as", "a", "python", "file", ".", "Import", "filename", "and", "return", "it", "as", "a", "module", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L898-L954
train
sloria/konch
konch.py
resolve_path
def resolve_path(filename: Path) -> typing.Union[Path, None]: """Find a file by walking up parent directories until the file is found. Return the absolute path of the file. """ current = Path.cwd() # Stop search at home directory sentinel_dir = Path.home().parent.resolve() while current != s...
python
def resolve_path(filename: Path) -> typing.Union[Path, None]: """Find a file by walking up parent directories until the file is found. Return the absolute path of the file. """ current = Path.cwd() # Stop search at home directory sentinel_dir = Path.home().parent.resolve() while current != s...
[ "def", "resolve_path", "(", "filename", ":", "Path", ")", "->", "typing", ".", "Union", "[", "Path", ",", "None", "]", ":", "current", "=", "Path", ".", "cwd", "(", ")", "# Stop search at home directory", "sentinel_dir", "=", "Path", ".", "home", "(", ")...
Find a file by walking up parent directories until the file is found. Return the absolute path of the file.
[ "Find", "a", "file", "by", "walking", "up", "parent", "directories", "until", "the", "file", "is", "found", ".", "Return", "the", "absolute", "path", "of", "the", "file", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L957-L971
train
sloria/konch
konch.py
parse_args
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]: """Exposes the docopt command-line arguments parser. Return a dictionary of arguments. """ return docopt(__doc__, argv=argv, version=__version__)
python
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]: """Exposes the docopt command-line arguments parser. Return a dictionary of arguments. """ return docopt(__doc__, argv=argv, version=__version__)
[ "def", "parse_args", "(", "argv", ":", "typing", ".", "Optional", "[", "typing", ".", "Sequence", "]", "=", "None", ")", "->", "typing", ".", "Dict", "[", "str", ",", "str", "]", ":", "return", "docopt", "(", "__doc__", ",", "argv", "=", "argv", ",...
Exposes the docopt command-line arguments parser. Return a dictionary of arguments.
[ "Exposes", "the", "docopt", "command", "-", "line", "arguments", "parser", ".", "Return", "a", "dictionary", "of", "arguments", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L1132-L1136
train
sloria/konch
konch.py
main
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn: """Main entry point for the konch CLI.""" args = parse_args(argv) if args["--debug"]: logging.basicConfig( format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG ) logger.debug(args) ...
python
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn: """Main entry point for the konch CLI.""" args = parse_args(argv) if args["--debug"]: logging.basicConfig( format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG ) logger.debug(args) ...
[ "def", "main", "(", "argv", ":", "typing", ".", "Optional", "[", "typing", ".", "Sequence", "]", "=", "None", ")", "->", "typing", ".", "NoReturn", ":", "args", "=", "parse_args", "(", "argv", ")", "if", "args", "[", "\"--debug\"", "]", ":", "logging...
Main entry point for the konch CLI.
[ "Main", "entry", "point", "for", "the", "konch", "CLI", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L1139-L1184
train
sloria/konch
konch.py
IPythonShell.init_autoreload
def init_autoreload(mode: int) -> None: """Load and initialize the IPython autoreload extension.""" from IPython.extensions import autoreload ip = get_ipython() # type: ignore # noqa: F821 autoreload.load_ipython_extension(ip) ip.magics_manager.magics["line"]["autoreload"](str(...
python
def init_autoreload(mode: int) -> None: """Load and initialize the IPython autoreload extension.""" from IPython.extensions import autoreload ip = get_ipython() # type: ignore # noqa: F821 autoreload.load_ipython_extension(ip) ip.magics_manager.magics["line"]["autoreload"](str(...
[ "def", "init_autoreload", "(", "mode", ":", "int", ")", "->", "None", ":", "from", "IPython", ".", "extensions", "import", "autoreload", "ip", "=", "get_ipython", "(", ")", "# type: ignore # noqa: F821", "autoreload", ".", "load_ipython_extension", "(", "ip", ")...
Load and initialize the IPython autoreload extension.
[ "Load", "and", "initialize", "the", "IPython", "autoreload", "extension", "." ]
15160bd0a0cac967eeeab84794bd6cdd0b5b637d
https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L427-L433
train
JamesPHoughton/pysd
pysd/py_backend/vensim/table2py.py
read_tabular
def read_tabular(table_file, sheetname='Sheet1'): """ Reads a vensim syntax model which has been formatted as a table. This is useful in contexts where model building is performed without the aid of Vensim. Parameters ---------- table_file: .csv, .tab or .xls(x) file Table should have...
python
def read_tabular(table_file, sheetname='Sheet1'): """ Reads a vensim syntax model which has been formatted as a table. This is useful in contexts where model building is performed without the aid of Vensim. Parameters ---------- table_file: .csv, .tab or .xls(x) file Table should have...
[ "def", "read_tabular", "(", "table_file", ",", "sheetname", "=", "'Sheet1'", ")", ":", "if", "isinstance", "(", "table_file", ",", "str", ")", ":", "extension", "=", "table_file", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "if", "extension", "i...
Reads a vensim syntax model which has been formatted as a table. This is useful in contexts where model building is performed without the aid of Vensim. Parameters ---------- table_file: .csv, .tab or .xls(x) file Table should have columns titled as in the table below | Variable | Equat...
[ "Reads", "a", "vensim", "syntax", "model", "which", "has", "been", "formatted", "as", "a", "table", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/table2py.py#L6-L80
train
JamesPHoughton/pysd
pysd/pysd.py
read_xmile
def read_xmile(xmile_file): """ Construct a model object from `.xmile` file. """ from . import py_backend from .py_backend.xmile.xmile2py import translate_xmile py_model_file = translate_xmile(xmile_file) model = load(py_model_file) model.xmile_file = xmile_file return model
python
def read_xmile(xmile_file): """ Construct a model object from `.xmile` file. """ from . import py_backend from .py_backend.xmile.xmile2py import translate_xmile py_model_file = translate_xmile(xmile_file) model = load(py_model_file) model.xmile_file = xmile_file return model
[ "def", "read_xmile", "(", "xmile_file", ")", ":", "from", ".", "import", "py_backend", "from", ".", "py_backend", ".", "xmile", ".", "xmile2py", "import", "translate_xmile", "py_model_file", "=", "translate_xmile", "(", "xmile_file", ")", "model", "=", "load", ...
Construct a model object from `.xmile` file.
[ "Construct", "a", "model", "object", "from", ".", "xmile", "file", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/pysd.py#L16-L23
train
JamesPHoughton/pysd
pysd/pysd.py
read_vensim
def read_vensim(mdl_file): """ Construct a model from Vensim `.mdl` file. Parameters ---------- mdl_file : <string> The relative path filename for a raw Vensim `.mdl` file Returns ------- model: a PySD class object Elements from the python model are loaded into the PySD...
python
def read_vensim(mdl_file): """ Construct a model from Vensim `.mdl` file. Parameters ---------- mdl_file : <string> The relative path filename for a raw Vensim `.mdl` file Returns ------- model: a PySD class object Elements from the python model are loaded into the PySD...
[ "def", "read_vensim", "(", "mdl_file", ")", ":", "from", ".", "py_backend", ".", "vensim", ".", "vensim2py", "import", "translate_vensim", "from", ".", "py_backend", "import", "functions", "py_model_file", "=", "translate_vensim", "(", "mdl_file", ")", "model", ...
Construct a model from Vensim `.mdl` file. Parameters ---------- mdl_file : <string> The relative path filename for a raw Vensim `.mdl` file Returns ------- model: a PySD class object Elements from the python model are loaded into the PySD class and ready to run Examples ...
[ "Construct", "a", "model", "from", "Vensim", ".", "mdl", "file", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/pysd.py#L25-L49
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
cache
def cache(horizon): """ Put a wrapper around a model function Decorators with parameters are tricky, you have to essentially create a decorator that returns a decorator, which itself then returns the function wrapper. Parameters ---------- horizon: string - 'step' means cache j...
python
def cache(horizon): """ Put a wrapper around a model function Decorators with parameters are tricky, you have to essentially create a decorator that returns a decorator, which itself then returns the function wrapper. Parameters ---------- horizon: string - 'step' means cache j...
[ "def", "cache", "(", "horizon", ")", ":", "def", "cache_step", "(", "func", ")", ":", "\"\"\" Decorator for caching at a step level\"\"\"", "@", "wraps", "(", "func", ")", "def", "cached", "(", "*", "args", ")", ":", "\"\"\"Step wise cache function\"\"\"", "try", ...
Put a wrapper around a model function Decorators with parameters are tricky, you have to essentially create a decorator that returns a decorator, which itself then returns the function wrapper. Parameters ---------- horizon: string - 'step' means cache just until the next timestep ...
[ "Put", "a", "wrapper", "around", "a", "model", "function" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L44-L105
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
ramp
def ramp(time, slope, start, finish=0): """ Implements vensim's and xmile's RAMP function Parameters ---------- time: function The current time of modelling slope: float The slope of the ramp starting at zero at time start start: float Time at which the ramp begins ...
python
def ramp(time, slope, start, finish=0): """ Implements vensim's and xmile's RAMP function Parameters ---------- time: function The current time of modelling slope: float The slope of the ramp starting at zero at time start start: float Time at which the ramp begins ...
[ "def", "ramp", "(", "time", ",", "slope", ",", "start", ",", "finish", "=", "0", ")", ":", "t", "=", "time", "(", ")", "if", "t", "<", "start", ":", "return", "0", "else", ":", "if", "finish", "<=", "0", ":", "return", "slope", "*", "(", "t",...
Implements vensim's and xmile's RAMP function Parameters ---------- time: function The current time of modelling slope: float The slope of the ramp starting at zero at time start start: float Time at which the ramp begins finish: float Optional. Time at which the...
[ "Implements", "vensim", "s", "and", "xmile", "s", "RAMP", "function" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L803-L837
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
pulse
def pulse(time, start, duration): """ Implements vensim's PULSE function In range [-inf, start) returns 0 In range [start, start + duration) returns 1 In range [start + duration, +inf] returns 0 """ t = time() return 1 if start <= t < start + duration else 0
python
def pulse(time, start, duration): """ Implements vensim's PULSE function In range [-inf, start) returns 0 In range [start, start + duration) returns 1 In range [start + duration, +inf] returns 0 """ t = time() return 1 if start <= t < start + duration else 0
[ "def", "pulse", "(", "time", ",", "start", ",", "duration", ")", ":", "t", "=", "time", "(", ")", "return", "1", "if", "start", "<=", "t", "<", "start", "+", "duration", "else", "0" ]
Implements vensim's PULSE function In range [-inf, start) returns 0 In range [start, start + duration) returns 1 In range [start + duration, +inf] returns 0
[ "Implements", "vensim", "s", "PULSE", "function" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L859-L867
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
pulse_train
def pulse_train(time, start, duration, repeat_time, end): """ Implements vensim's PULSE TRAIN function In range [-inf, start) returns 0 In range [start + n * repeat_time, start + n * repeat_time + duration) return 1 In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0 ...
python
def pulse_train(time, start, duration, repeat_time, end): """ Implements vensim's PULSE TRAIN function In range [-inf, start) returns 0 In range [start + n * repeat_time, start + n * repeat_time + duration) return 1 In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0 ...
[ "def", "pulse_train", "(", "time", ",", "start", ",", "duration", ",", "repeat_time", ",", "end", ")", ":", "t", "=", "time", "(", ")", "if", "start", "<=", "t", "<", "end", ":", "return", "1", "if", "(", "t", "-", "start", ")", "%", "repeat_time...
Implements vensim's PULSE TRAIN function In range [-inf, start) returns 0 In range [start + n * repeat_time, start + n * repeat_time + duration) return 1 In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
[ "Implements", "vensim", "s", "PULSE", "TRAIN", "function" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L870-L881
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
lookup_extrapolation
def lookup_extrapolation(x, xs, ys): """ Intermediate values are calculated with linear interpolation between the intermediate points. Out-of-range values are calculated with linear extrapolation from the last two values at either end. """ length = len(xs) if x < xs[0]: dx = xs[1] - xs[0...
python
def lookup_extrapolation(x, xs, ys): """ Intermediate values are calculated with linear interpolation between the intermediate points. Out-of-range values are calculated with linear extrapolation from the last two values at either end. """ length = len(xs) if x < xs[0]: dx = xs[1] - xs[0...
[ "def", "lookup_extrapolation", "(", "x", ",", "xs", ",", "ys", ")", ":", "length", "=", "len", "(", "xs", ")", "if", "x", "<", "xs", "[", "0", "]", ":", "dx", "=", "xs", "[", "1", "]", "-", "xs", "[", "0", "]", "dy", "=", "ys", "[", "1", ...
Intermediate values are calculated with linear interpolation between the intermediate points. Out-of-range values are calculated with linear extrapolation from the last two values at either end.
[ "Intermediate", "values", "are", "calculated", "with", "linear", "interpolation", "between", "the", "intermediate", "points", ".", "Out", "-", "of", "-", "range", "values", "are", "calculated", "with", "linear", "extrapolation", "from", "the", "last", "two", "va...
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L917-L933
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
xidz
def xidz(numerator, denominator, value_if_denom_is_zero): """ Implements Vensim's XIDZ function. This function executes a division, robust to denominator being zero. In the case of zero denominator, the final argument is returned. Parameters ---------- numerator: float denominator: floa...
python
def xidz(numerator, denominator, value_if_denom_is_zero): """ Implements Vensim's XIDZ function. This function executes a division, robust to denominator being zero. In the case of zero denominator, the final argument is returned. Parameters ---------- numerator: float denominator: floa...
[ "def", "xidz", "(", "numerator", ",", "denominator", ",", "value_if_denom_is_zero", ")", ":", "small", "=", "1e-6", "# What is considered zero according to Vensim Help", "if", "abs", "(", "denominator", ")", "<", "small", ":", "return", "value_if_denom_is_zero", "else...
Implements Vensim's XIDZ function. This function executes a division, robust to denominator being zero. In the case of zero denominator, the final argument is returned. Parameters ---------- numerator: float denominator: float Components of the division operation value_if_denom_is_z...
[ "Implements", "Vensim", "s", "XIDZ", "function", ".", "This", "function", "executes", "a", "division", "robust", "to", "denominator", "being", "zero", ".", "In", "the", "case", "of", "zero", "denominator", "the", "final", "argument", "is", "returned", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L950-L973
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.initialize
def initialize(self, initialization_order=None): """ This function tries to initialize the stateful objects. In the case where an initialization function for `Stock A` depends on the value of `Stock B`, if we try to initialize `Stock A` before `Stock B` then we will get an error...
python
def initialize(self, initialization_order=None): """ This function tries to initialize the stateful objects. In the case where an initialization function for `Stock A` depends on the value of `Stock B`, if we try to initialize `Stock A` before `Stock B` then we will get an error...
[ "def", "initialize", "(", "self", ",", "initialization_order", "=", "None", ")", ":", "# Initialize time", "if", "self", ".", "time", "is", "None", ":", "if", "self", ".", "time_initialization", "is", "None", ":", "self", ".", "time", "=", "Time", "(", "...
This function tries to initialize the stateful objects. In the case where an initialization function for `Stock A` depends on the value of `Stock B`, if we try to initialize `Stock A` before `Stock B` then we will get an error, as the value will not yet exist. In this case, just skip i...
[ "This", "function", "tries", "to", "initialize", "the", "stateful", "objects", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L320-L363
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.set_components
def set_components(self, params): """ Set the value of exogenous model elements. Element values can be passed as keyword=value pairs in the function call. Values can be numeric type or pandas Series. Series will be interpolated by integrator. Examples -------- >...
python
def set_components(self, params): """ Set the value of exogenous model elements. Element values can be passed as keyword=value pairs in the function call. Values can be numeric type or pandas Series. Series will be interpolated by integrator. Examples -------- >...
[ "def", "set_components", "(", "self", ",", "params", ")", ":", "# It might make sense to allow the params argument to take a pandas series, where", "# the indices of the series are variable names. This would make it easier to", "# do a Pandas apply on a DataFrame of parameter values. However, th...
Set the value of exogenous model elements. Element values can be passed as keyword=value pairs in the function call. Values can be numeric type or pandas Series. Series will be interpolated by integrator. Examples -------- >>> model.set_components({'birth_rate': 10}) ...
[ "Set", "the", "value", "of", "exogenous", "model", "elements", ".", "Element", "values", "can", "be", "passed", "as", "keyword", "=", "value", "pairs", "in", "the", "function", "call", ".", "Values", "can", "be", "numeric", "type", "or", "pandas", "Series"...
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L376-L415
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro._timeseries_component
def _timeseries_component(self, series): """ Internal function for creating a timeseries model element """ # this is only called if the set_component function recognizes a pandas series # Todo: raise a warning if extrapolating from the end of the series. return lambda: np.interp(self.tim...
python
def _timeseries_component(self, series): """ Internal function for creating a timeseries model element """ # this is only called if the set_component function recognizes a pandas series # Todo: raise a warning if extrapolating from the end of the series. return lambda: np.interp(self.tim...
[ "def", "_timeseries_component", "(", "self", ",", "series", ")", ":", "# this is only called if the set_component function recognizes a pandas series", "# Todo: raise a warning if extrapolating from the end of the series.", "return", "lambda", ":", "np", ".", "interp", "(", "self",...
Internal function for creating a timeseries model element
[ "Internal", "function", "for", "creating", "a", "timeseries", "model", "element" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L417-L421
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.set_state
def set_state(self, t, state): """ Set the system state. Parameters ---------- t : numeric The system time state : dict A (possibly partial) dictionary of the system state. The keys to this dictionary may be either pysafe names or original mo...
python
def set_state(self, t, state): """ Set the system state. Parameters ---------- t : numeric The system time state : dict A (possibly partial) dictionary of the system state. The keys to this dictionary may be either pysafe names or original mo...
[ "def", "set_state", "(", "self", ",", "t", ",", "state", ")", ":", "self", ".", "time", ".", "update", "(", "t", ")", "for", "key", ",", "value", "in", "state", ".", "items", "(", ")", ":", "# TODO Implement map with reference between component and stateful ...
Set the system state. Parameters ---------- t : numeric The system time state : dict A (possibly partial) dictionary of the system state. The keys to this dictionary may be either pysafe names or original model file names
[ "Set", "the", "system", "state", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L427-L464
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.clear_caches
def clear_caches(self): """ Clears the Caches for all model elements """ for element_name in dir(self.components): element = getattr(self.components, element_name) if hasattr(element, 'cache_val'): delattr(element, 'cache_val')
python
def clear_caches(self): """ Clears the Caches for all model elements """ for element_name in dir(self.components): element = getattr(self.components, element_name) if hasattr(element, 'cache_val'): delattr(element, 'cache_val')
[ "def", "clear_caches", "(", "self", ")", ":", "for", "element_name", "in", "dir", "(", "self", ".", "components", ")", ":", "element", "=", "getattr", "(", "self", ".", "components", ",", "element_name", ")", "if", "hasattr", "(", "element", ",", "'cache...
Clears the Caches for all model elements
[ "Clears", "the", "Caches", "for", "all", "model", "elements" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L466-L471
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.doc
def doc(self): """ Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: ...
python
def doc(self): """ Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: ...
[ "def", "doc", "(", "self", ")", ":", "collector", "=", "[", "]", "for", "name", ",", "varname", "in", "self", ".", "components", ".", "_namespace", ".", "items", "(", ")", ":", "try", ":", "docstring", "=", "getattr", "(", "self", ".", "components", ...
Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: - Real names ...
[ "Formats", "a", "table", "of", "documentation", "strings", "to", "help", "users", "remember", "variable", "names", "and", "understand", "how", "they", "are", "translated", "into", "python", "safe", "names", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L473-L506
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model.initialize
def initialize(self): """ Initializes the simulation model """ self.time.update(self.components.initial_time()) self.time.stage = 'Initialization' super(Model, self).initialize()
python
def initialize(self): """ Initializes the simulation model """ self.time.update(self.components.initial_time()) self.time.stage = 'Initialization' super(Model, self).initialize()
[ "def", "initialize", "(", "self", ")", ":", "self", ".", "time", ".", "update", "(", "self", ".", "components", ".", "initial_time", "(", ")", ")", "self", ".", "time", ".", "stage", "=", "'Initialization'", "super", "(", "Model", ",", "self", ")", "...
Initializes the simulation model
[ "Initializes", "the", "simulation", "model" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L547-L551
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model._format_return_timestamps
def _format_return_timestamps(self, return_timestamps=None): """ Format the passed in return timestamps value as a numpy array. If no value is passed, build up array of timestamps based upon model start and end times, and the 'saveper' value. """ if return_timestamps is N...
python
def _format_return_timestamps(self, return_timestamps=None): """ Format the passed in return timestamps value as a numpy array. If no value is passed, build up array of timestamps based upon model start and end times, and the 'saveper' value. """ if return_timestamps is N...
[ "def", "_format_return_timestamps", "(", "self", ",", "return_timestamps", "=", "None", ")", ":", "if", "return_timestamps", "is", "None", ":", "# Build based upon model file Start, Stop times and Saveper", "# Vensim's standard is to expect that the data set includes the `final time`...
Format the passed in return timestamps value as a numpy array. If no value is passed, build up array of timestamps based upon model start and end times, and the 'saveper' value.
[ "Format", "the", "passed", "in", "return", "timestamps", "value", "as", "a", "numpy", "array", ".", "If", "no", "value", "is", "passed", "build", "up", "array", "of", "timestamps", "based", "upon", "model", "start", "and", "end", "times", "and", "the", "...
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L588-L613
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model.run
def run(self, params=None, return_columns=None, return_timestamps=None, initial_condition='original', reload=False): """ Simulate the model's behavior over time. Return a pandas dataframe with timestamps as rows, model elements as columns. Parameters ---------- ...
python
def run(self, params=None, return_columns=None, return_timestamps=None, initial_condition='original', reload=False): """ Simulate the model's behavior over time. Return a pandas dataframe with timestamps as rows, model elements as columns. Parameters ---------- ...
[ "def", "run", "(", "self", ",", "params", "=", "None", ",", "return_columns", "=", "None", ",", "return_timestamps", "=", "None", ",", "initial_condition", "=", "'original'", ",", "reload", "=", "False", ")", ":", "if", "reload", ":", "self", ".", "reloa...
Simulate the model's behavior over time. Return a pandas dataframe with timestamps as rows, model elements as columns. Parameters ---------- params : dictionary Keys are strings of model component names. Values are numeric or pandas Series. Nu...
[ "Simulate", "the", "model", "s", "behavior", "over", "time", ".", "Return", "a", "pandas", "dataframe", "with", "timestamps", "as", "rows", "model", "elements", "as", "columns", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L615-L690
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model._default_return_columns
def _default_return_columns(self): """ Return a list of the model elements that does not include lookup functions or other functions that take parameters. """ return_columns = [] parsed_expr = [] for key, value in self.components._namespace.items(): i...
python
def _default_return_columns(self): """ Return a list of the model elements that does not include lookup functions or other functions that take parameters. """ return_columns = [] parsed_expr = [] for key, value in self.components._namespace.items(): i...
[ "def", "_default_return_columns", "(", "self", ")", ":", "return_columns", "=", "[", "]", "parsed_expr", "=", "[", "]", "for", "key", ",", "value", "in", "self", ".", "components", ".", "_namespace", ".", "items", "(", ")", ":", "if", "hasattr", "(", "...
Return a list of the model elements that does not include lookup functions or other functions that take parameters.
[ "Return", "a", "list", "of", "the", "model", "elements", "that", "does", "not", "include", "lookup", "functions", "or", "other", "functions", "that", "take", "parameters", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L698-L716
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model.set_initial_condition
def set_initial_condition(self, initial_condition): """ Set the initial conditions of the integration. Parameters ---------- initial_condition : <string> or <tuple> Takes on one of the following sets of values: * 'original'/'o' : Reset to the model-file specifie...
python
def set_initial_condition(self, initial_condition): """ Set the initial conditions of the integration. Parameters ---------- initial_condition : <string> or <tuple> Takes on one of the following sets of values: * 'original'/'o' : Reset to the model-file specifie...
[ "def", "set_initial_condition", "(", "self", ",", "initial_condition", ")", ":", "if", "isinstance", "(", "initial_condition", ",", "tuple", ")", ":", "# Todo: check the values more than just seeing if they are a tuple.", "self", ".", "set_state", "(", "*", "initial_condi...
Set the initial conditions of the integration. Parameters ---------- initial_condition : <string> or <tuple> Takes on one of the following sets of values: * 'original'/'o' : Reset to the model-file specified initial condition. * 'current'/'c' : Use the curre...
[ "Set", "the", "initial", "conditions", "of", "the", "integration", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L718-L755
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model._euler_step
def _euler_step(self, dt): """ Performs a single step in the euler integration, updating stateful components Parameters ---------- dt : float This is the amount to increase time by this step """ self.state = self.state + self.ddt() * dt
python
def _euler_step(self, dt): """ Performs a single step in the euler integration, updating stateful components Parameters ---------- dt : float This is the amount to increase time by this step """ self.state = self.state + self.ddt() * dt
[ "def", "_euler_step", "(", "self", ",", "dt", ")", ":", "self", ".", "state", "=", "self", ".", "state", "+", "self", ".", "ddt", "(", ")", "*", "dt" ]
Performs a single step in the euler integration, updating stateful components Parameters ---------- dt : float This is the amount to increase time by this step
[ "Performs", "a", "single", "step", "in", "the", "euler", "integration", "updating", "stateful", "components" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L757-L766
train
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model._integrate
def _integrate(self, time_steps, capture_elements, return_timestamps): """ Performs euler integration Parameters ---------- time_steps: iterable the time steps that the integrator progresses over capture_elements: list which model elements to capt...
python
def _integrate(self, time_steps, capture_elements, return_timestamps): """ Performs euler integration Parameters ---------- time_steps: iterable the time steps that the integrator progresses over capture_elements: list which model elements to capt...
[ "def", "_integrate", "(", "self", ",", "time_steps", ",", "capture_elements", ",", "return_timestamps", ")", ":", "# Todo: consider adding the timestamp to the return elements, and using that as the index", "outputs", "=", "[", "]", "for", "t2", "in", "time_steps", "[", "...
Performs euler integration Parameters ---------- time_steps: iterable the time steps that the integrator progresses over capture_elements: list which model elements to capture - uses pysafe names return_timestamps: which subset of 'timesteps' ...
[ "Performs", "euler", "integration" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L768-L800
train
JamesPHoughton/pysd
pysd/py_backend/builder.py
merge_partial_elements
def merge_partial_elements(element_list): """ merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list Returns ------- """ outs = dict() # output data structure for element in element...
python
def merge_partial_elements(element_list): """ merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list Returns ------- """ outs = dict() # output data structure for element in element...
[ "def", "merge_partial_elements", "(", "element_list", ")", ":", "outs", "=", "dict", "(", ")", "# output data structure", "for", "element", "in", "element_list", ":", "if", "element", "[", "'py_expr'", "]", "!=", "\"None\"", ":", "# for", "name", "=", "element...
merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list Returns -------
[ "merges", "model", "elements", "which", "collectively", "all", "define", "the", "model", "component", "mostly", "for", "multidimensional", "subscripts" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L187-L229
train
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_n_delay
def add_n_delay(delay_input, delay_time, initial_value, order, subs, subscript_dict): """ Creates code to instantiate a stateful 'Delay' object, and provides reference to that object's output. The name of the stateful object is based upon the passed in parameters, so if there are multiple places wh...
python
def add_n_delay(delay_input, delay_time, initial_value, order, subs, subscript_dict): """ Creates code to instantiate a stateful 'Delay' object, and provides reference to that object's output. The name of the stateful object is based upon the passed in parameters, so if there are multiple places wh...
[ "def", "add_n_delay", "(", "delay_input", ",", "delay_time", ",", "initial_value", ",", "order", ",", "subs", ",", "subscript_dict", ")", ":", "# the py name has to be unique to all the passed parameters, or if there are two things", "# that delay the output by different amounts, t...
Creates code to instantiate a stateful 'Delay' object, and provides reference to that object's output. The name of the stateful object is based upon the passed in parameters, so if there are multiple places where identical delay functions are referenced, the translated python file will only maintain on...
[ "Creates", "code", "to", "instantiate", "a", "stateful", "Delay", "object", "and", "provides", "reference", "to", "that", "object", "s", "output", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L340-L401
train
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_n_smooth
def add_n_smooth(smooth_input, smooth_time, initial_value, order, subs, subscript_dict): """Constructs stock and flow chains that implement the calculation of a smoothing function. Parameters ---------- smooth_input: <string> Reference to the model component that is the ...
python
def add_n_smooth(smooth_input, smooth_time, initial_value, order, subs, subscript_dict): """Constructs stock and flow chains that implement the calculation of a smoothing function. Parameters ---------- smooth_input: <string> Reference to the model component that is the ...
[ "def", "add_n_smooth", "(", "smooth_input", ",", "smooth_time", ",", "initial_value", ",", "order", ",", "subs", ",", "subscript_dict", ")", ":", "stateful", "=", "{", "'py_name'", ":", "utils", ".", "make_python_identifier", "(", "'_smooth_%s_%s_%s_%s'", "%", "...
Constructs stock and flow chains that implement the calculation of a smoothing function. Parameters ---------- smooth_input: <string> Reference to the model component that is the input to the smoothing function smooth_time: <string> Can be a number (in s...
[ "Constructs", "stock", "and", "flow", "chains", "that", "implement", "the", "calculation", "of", "a", "smoothing", "function", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L404-L461
train
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_initial
def add_initial(initial_input): """ Constructs a stateful object for handling vensim's 'Initial' functionality Parameters ---------- initial_input: basestring The expression which will be evaluated, and the first value of which returned Returns ------- reference: basestring ...
python
def add_initial(initial_input): """ Constructs a stateful object for handling vensim's 'Initial' functionality Parameters ---------- initial_input: basestring The expression which will be evaluated, and the first value of which returned Returns ------- reference: basestring ...
[ "def", "add_initial", "(", "initial_input", ")", ":", "stateful", "=", "{", "'py_name'", ":", "utils", ".", "make_python_identifier", "(", "'_initial_%s'", "%", "initial_input", ")", "[", "0", "]", ",", "'real_name'", ":", "'Smooth of %s'", "%", "initial_input",...
Constructs a stateful object for handling vensim's 'Initial' functionality Parameters ---------- initial_input: basestring The expression which will be evaluated, and the first value of which returned Returns ------- reference: basestring reference to the Initial object `__call...
[ "Constructs", "a", "stateful", "object", "for", "handling", "vensim", "s", "Initial", "functionality" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L511-L544
train
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_macro
def add_macro(macro_name, filename, arg_names, arg_vals): """ Constructs a stateful object instantiating a 'Macro' Parameters ---------- macro_name: basestring python safe name for macro filename: basestring filepath to macro definition func_args: dict dictionary of ...
python
def add_macro(macro_name, filename, arg_names, arg_vals): """ Constructs a stateful object instantiating a 'Macro' Parameters ---------- macro_name: basestring python safe name for macro filename: basestring filepath to macro definition func_args: dict dictionary of ...
[ "def", "add_macro", "(", "macro_name", ",", "filename", ",", "arg_names", ",", "arg_vals", ")", ":", "func_args", "=", "'{ %s }'", "%", "', '", ".", "join", "(", "[", "\"'%s': lambda: %s\"", "%", "(", "key", ",", "val", ")", "for", "key", ",", "val", "...
Constructs a stateful object instantiating a 'Macro' Parameters ---------- macro_name: basestring python safe name for macro filename: basestring filepath to macro definition func_args: dict dictionary of values to be passed to macro {key: function} Returns ...
[ "Constructs", "a", "stateful", "object", "instantiating", "a", "Macro" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L547-L588
train
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_incomplete
def add_incomplete(var_name, dependencies): """ Incomplete functions don't really need to be 'builders' as they add no new real structure, but it's helpful to have a function in which we can raise a warning about the incomplete equation at translate time. """ warnings.warn('%s has no equa...
python
def add_incomplete(var_name, dependencies): """ Incomplete functions don't really need to be 'builders' as they add no new real structure, but it's helpful to have a function in which we can raise a warning about the incomplete equation at translate time. """ warnings.warn('%s has no equa...
[ "def", "add_incomplete", "(", "var_name", ",", "dependencies", ")", ":", "warnings", ".", "warn", "(", "'%s has no equation specified'", "%", "var_name", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "# first arg is `self` reference", "return", "\"functions....
Incomplete functions don't really need to be 'builders' as they add no new real structure, but it's helpful to have a function in which we can raise a warning about the incomplete equation at translate time.
[ "Incomplete", "functions", "don", "t", "really", "need", "to", "be", "builders", "as", "they", "add", "no", "new", "real", "structure", "but", "it", "s", "helpful", "to", "have", "a", "function", "in", "which", "we", "can", "raise", "a", "warning", "abou...
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L591-L602
train
JamesPHoughton/pysd
pysd/py_backend/vensim/vensim2py.py
get_model_elements
def get_model_elements(model_str): """ Takes in a string representing model text and splits it into elements I think we're making the assumption that all newline characters are removed... Parameters ---------- model_str : string Returns ------- entries : array of dictionaries ...
python
def get_model_elements(model_str): """ Takes in a string representing model text and splits it into elements I think we're making the assumption that all newline characters are removed... Parameters ---------- model_str : string Returns ------- entries : array of dictionaries ...
[ "def", "get_model_elements", "(", "model_str", ")", ":", "model_structure_grammar", "=", "_include_common_grammar", "(", "r\"\"\"\n model = (entry / section)+ sketch?\n entry = element \"~\" element \"~\" element (\"~\" element)? \"|\"\n section = element \"~\" element \"|\"\n sketch...
Takes in a string representing model text and splits it into elements I think we're making the assumption that all newline characters are removed... Parameters ---------- model_str : string Returns ------- entries : array of dictionaries Each dictionary contains the components of...
[ "Takes", "in", "a", "string", "representing", "model", "text", "and", "splits", "it", "into", "elements" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L87-L181
train
JamesPHoughton/pysd
pysd/py_backend/vensim/vensim2py.py
get_equation_components
def get_equation_components(equation_str): """ Breaks down a string representing only the equation part of a model element. Recognizes the various types of model elements that may exist, and identifies them. Parameters ---------- equation_str : basestring the first section in each model...
python
def get_equation_components(equation_str): """ Breaks down a string representing only the equation part of a model element. Recognizes the various types of model elements that may exist, and identifies them. Parameters ---------- equation_str : basestring the first section in each model...
[ "def", "get_equation_components", "(", "equation_str", ")", ":", "component_structure_grammar", "=", "_include_common_grammar", "(", "r\"\"\"\n entry = component / subscript_definition / lookup_definition\n component = name _ subscriptlist? _ \"=\" _ expression\n subscript_definition = ...
Breaks down a string representing only the equation part of a model element. Recognizes the various types of model elements that may exist, and identifies them. Parameters ---------- equation_str : basestring the first section in each model element - the full equation. Returns ------- ...
[ "Breaks", "down", "a", "string", "representing", "only", "the", "equation", "part", "of", "a", "model", "element", ".", "Recognizes", "the", "various", "types", "of", "model", "elements", "that", "may", "exist", "and", "identifies", "them", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L206-L305
train
JamesPHoughton/pysd
pysd/py_backend/vensim/vensim2py.py
parse_units
def parse_units(units_str): """ Extract and parse the units Extract the bounds over which the expression is assumed to apply. Parameters ---------- units_str Returns ------- Examples -------- >>> parse_units('Widgets/Month [-10,10,1]') ('Widgets/Month', (-10,10,1)) ...
python
def parse_units(units_str): """ Extract and parse the units Extract the bounds over which the expression is assumed to apply. Parameters ---------- units_str Returns ------- Examples -------- >>> parse_units('Widgets/Month [-10,10,1]') ('Widgets/Month', (-10,10,1)) ...
[ "def", "parse_units", "(", "units_str", ")", ":", "if", "not", "len", "(", "units_str", ")", ":", "return", "units_str", ",", "(", "None", ",", "None", ")", "if", "units_str", "[", "-", "1", "]", "==", "']'", ":", "units", ",", "lims", "=", "units_...
Extract and parse the units Extract the bounds over which the expression is assumed to apply. Parameters ---------- units_str Returns ------- Examples -------- >>> parse_units('Widgets/Month [-10,10,1]') ('Widgets/Month', (-10,10,1)) >>> parse_units('Month [0,?]') ('M...
[ "Extract", "and", "parse", "the", "units", "Extract", "the", "bounds", "over", "which", "the", "expression", "is", "assumed", "to", "apply", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L308-L349
train
JamesPHoughton/pysd
pysd/py_backend/vensim/vensim2py.py
parse_lookup_expression
def parse_lookup_expression(element): """ This syntax parses lookups that are defined with their own element """ lookup_grammar = r""" lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")" number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?" _ = ~r"[\s\\]*" # whitespace character ra...
python
def parse_lookup_expression(element): """ This syntax parses lookups that are defined with their own element """ lookup_grammar = r""" lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")" number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?" _ = ~r"[\s\\]*" # whitespace character ra...
[ "def", "parse_lookup_expression", "(", "element", ")", ":", "lookup_grammar", "=", "r\"\"\"\n lookup = _ \"(\" range? _ ( \"(\" _ number _ \",\" _ number _ \")\" _ \",\"? _ )+ \")\"\n number = (\"+\"/\"-\")? ~r\"\\d+\\.?\\d*(e[+-]\\d+)?\"\n _ = ~r\"[\\s\\\\]*\" # whitespace character\n\tra...
This syntax parses lookups that are defined with their own element
[ "This", "syntax", "parses", "lookups", "that", "are", "defined", "with", "their", "own", "element" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L807-L845
train
JamesPHoughton/pysd
pysd/py_backend/utils.py
dict_find
def dict_find(in_dict, value): """ Helper function for looking up directory keys by their values. This isn't robust to repeated values Parameters ---------- in_dict : dictionary A dictionary containing `value` value : any type What we wish to find in the dictionary Return...
python
def dict_find(in_dict, value): """ Helper function for looking up directory keys by their values. This isn't robust to repeated values Parameters ---------- in_dict : dictionary A dictionary containing `value` value : any type What we wish to find in the dictionary Return...
[ "def", "dict_find", "(", "in_dict", ",", "value", ")", ":", "# Todo: make this robust to repeated values", "# Todo: make this robust to missing values", "return", "list", "(", "in_dict", ".", "keys", "(", ")", ")", "[", "list", "(", "in_dict", ".", "values", "(", ...
Helper function for looking up directory keys by their values. This isn't robust to repeated values Parameters ---------- in_dict : dictionary A dictionary containing `value` value : any type What we wish to find in the dictionary Returns ------- key: basestring ...
[ "Helper", "function", "for", "looking", "up", "directory", "keys", "by", "their", "values", ".", "This", "isn", "t", "robust", "to", "repeated", "values" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L9-L34
train
JamesPHoughton/pysd
pysd/py_backend/utils.py
find_subscript_name
def find_subscript_name(subscript_dict, element): """ Given a subscript dictionary, and a member of a subscript family, return the first key of which the member is within the value list. If element is already a subscript name, return that Parameters ---------- subscript_dict: dictionary ...
python
def find_subscript_name(subscript_dict, element): """ Given a subscript dictionary, and a member of a subscript family, return the first key of which the member is within the value list. If element is already a subscript name, return that Parameters ---------- subscript_dict: dictionary ...
[ "def", "find_subscript_name", "(", "subscript_dict", ",", "element", ")", ":", "if", "element", "in", "subscript_dict", ".", "keys", "(", ")", ":", "return", "element", "for", "name", ",", "elements", "in", "subscript_dict", ".", "items", "(", ")", ":", "i...
Given a subscript dictionary, and a member of a subscript family, return the first key of which the member is within the value list. If element is already a subscript name, return that Parameters ---------- subscript_dict: dictionary Follows the {'subscript name':['list','of','subscript','e...
[ "Given", "a", "subscript", "dictionary", "and", "a", "member", "of", "a", "subscript", "family", "return", "the", "first", "key", "of", "which", "the", "member", "is", "within", "the", "value", "list", ".", "If", "element", "is", "already", "a", "subscript...
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L65-L93
train
JamesPHoughton/pysd
pysd/py_backend/utils.py
make_coord_dict
def make_coord_dict(subs, subscript_dict, terse=True): """ This is for assisting with the lookup of a particular element, such that the output of this function would take the place of %s in this expression `variable.loc[%s]` Parameters ---------- subs: list of strings coordinates, ...
python
def make_coord_dict(subs, subscript_dict, terse=True): """ This is for assisting with the lookup of a particular element, such that the output of this function would take the place of %s in this expression `variable.loc[%s]` Parameters ---------- subs: list of strings coordinates, ...
[ "def", "make_coord_dict", "(", "subs", ",", "subscript_dict", ",", "terse", "=", "True", ")", ":", "sub_elems_list", "=", "[", "y", "for", "x", "in", "subscript_dict", ".", "values", "(", ")", "for", "y", "in", "x", "]", "coordinates", "=", "{", "}", ...
This is for assisting with the lookup of a particular element, such that the output of this function would take the place of %s in this expression `variable.loc[%s]` Parameters ---------- subs: list of strings coordinates, either as names of dimensions, or positions within a dimension ...
[ "This", "is", "for", "assisting", "with", "the", "lookup", "of", "a", "particular", "element", "such", "that", "the", "output", "of", "this", "function", "would", "take", "the", "place", "of", "%s", "in", "this", "expression" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L96-L135
train
JamesPHoughton/pysd
pysd/py_backend/utils.py
make_python_identifier
def make_python_identifier(string, namespace=None, reserved_words=None, convert='drop', handle='force'): """ Takes an arbitrary string and creates a valid Python identifier. If the input string is in the namespace, return its value. If the python identifier created is alread...
python
def make_python_identifier(string, namespace=None, reserved_words=None, convert='drop', handle='force'): """ Takes an arbitrary string and creates a valid Python identifier. If the input string is in the namespace, return its value. If the python identifier created is alread...
[ "def", "make_python_identifier", "(", "string", ",", "namespace", "=", "None", ",", "reserved_words", "=", "None", ",", "convert", "=", "'drop'", ",", "handle", "=", "'force'", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "dict", "(", ...
Takes an arbitrary string and creates a valid Python identifier. If the input string is in the namespace, return its value. If the python identifier created is already in the namespace, but the input string is not (ie, two similar strings resolve to the same python identifier) or if the identifie...
[ "Takes", "an", "arbitrary", "string", "and", "creates", "a", "valid", "Python", "identifier", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L138-L291
train
JamesPHoughton/pysd
pysd/py_backend/utils.py
make_flat_df
def make_flat_df(frames, return_addresses): """ Takes a list of dictionaries, each representing what is returned from the model at a particular time, and creates a dataframe whose columns correspond to the keys of `return addresses` Parameters ---------- frames: list of dictionaries ...
python
def make_flat_df(frames, return_addresses): """ Takes a list of dictionaries, each representing what is returned from the model at a particular time, and creates a dataframe whose columns correspond to the keys of `return addresses` Parameters ---------- frames: list of dictionaries ...
[ "def", "make_flat_df", "(", "frames", ",", "return_addresses", ")", ":", "# Todo: could also try a list comprehension here, or parallel apply", "visited", "=", "list", "(", "map", "(", "lambda", "x", ":", "visit_addresses", "(", "x", ",", "return_addresses", ")", ",",...
Takes a list of dictionaries, each representing what is returned from the model at a particular time, and creates a dataframe whose columns correspond to the keys of `return addresses` Parameters ---------- frames: list of dictionaries each dictionary represents the result of a prticular ti...
[ "Takes", "a", "list", "of", "dictionaries", "each", "representing", "what", "is", "returned", "from", "the", "model", "at", "a", "particular", "time", "and", "creates", "a", "dataframe", "whose", "columns", "correspond", "to", "the", "keys", "of", "return", ...
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L344-L367
train
JamesPHoughton/pysd
pysd/py_backend/utils.py
visit_addresses
def visit_addresses(frame, return_addresses): """ Visits all of the addresses, returns a new dict which contains just the addressed elements Parameters ---------- frame return_addresses: a dictionary, keys will be column names of the resulting dataframe, and are what the us...
python
def visit_addresses(frame, return_addresses): """ Visits all of the addresses, returns a new dict which contains just the addressed elements Parameters ---------- frame return_addresses: a dictionary, keys will be column names of the resulting dataframe, and are what the us...
[ "def", "visit_addresses", "(", "frame", ",", "return_addresses", ")", ":", "outdict", "=", "dict", "(", ")", "for", "real_name", ",", "(", "pyname", ",", "address", ")", "in", "return_addresses", ".", "items", "(", ")", ":", "if", "address", ":", "xrval"...
Visits all of the addresses, returns a new dict which contains just the addressed elements Parameters ---------- frame return_addresses: a dictionary, keys will be column names of the resulting dataframe, and are what the user passed in as 'return_columns'. Values are a tuple: ...
[ "Visits", "all", "of", "the", "addresses", "returns", "a", "new", "dict", "which", "contains", "just", "the", "addressed", "elements" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L370-L401
train
hirokiky/django-basicauth
basicauth/basicauthutils.py
validate_request
def validate_request(request): """Check an incoming request. Returns: - True if authentication passed - Adding request['REMOTE_USER'] as authenticated username. """ if getattr(settings, 'BASICAUTH_DISABLE', False): # Not to use this env return True if 'HTTP_AUTHORIZ...
python
def validate_request(request): """Check an incoming request. Returns: - True if authentication passed - Adding request['REMOTE_USER'] as authenticated username. """ if getattr(settings, 'BASICAUTH_DISABLE', False): # Not to use this env return True if 'HTTP_AUTHORIZ...
[ "def", "validate_request", "(", "request", ")", ":", "if", "getattr", "(", "settings", ",", "'BASICAUTH_DISABLE'", ",", "False", ")", ":", "# Not to use this env", "return", "True", "if", "'HTTP_AUTHORIZATION'", "not", "in", "request", ".", "META", ":", "return"...
Check an incoming request. Returns: - True if authentication passed - Adding request['REMOTE_USER'] as authenticated username.
[ "Check", "an", "incoming", "request", "." ]
dcc956ef1507f289bb50dce770e13c114ebd9a9b
https://github.com/hirokiky/django-basicauth/blob/dcc956ef1507f289bb50dce770e13c114ebd9a9b/basicauth/basicauthutils.py#L38-L69
train
google/ipaddr-py
ipaddr.py
_find_address_range
def _find_address_range(addresses): """Find a sequence of addresses. Args: addresses: a list of IPv4 or IPv6 addresses. Returns: A tuple containing the first and last IP addresses in the sequence, and the index of the last IP address in the sequence. """ first = last = add...
python
def _find_address_range(addresses): """Find a sequence of addresses. Args: addresses: a list of IPv4 or IPv6 addresses. Returns: A tuple containing the first and last IP addresses in the sequence, and the index of the last IP address in the sequence. """ first = last = add...
[ "def", "_find_address_range", "(", "addresses", ")", ":", "first", "=", "last", "=", "addresses", "[", "0", "]", "last_index", "=", "0", "for", "ip", "in", "addresses", "[", "1", ":", "]", ":", "if", "ip", ".", "_ip", "==", "last", ".", "_ip", "+",...
Find a sequence of addresses. Args: addresses: a list of IPv4 or IPv6 addresses. Returns: A tuple containing the first and last IP addresses in the sequence, and the index of the last IP address in the sequence.
[ "Find", "a", "sequence", "of", "addresses", "." ]
99e55513666db1276596d74f24863e056ca50851
https://github.com/google/ipaddr-py/blob/99e55513666db1276596d74f24863e056ca50851/ipaddr.py#L157-L176
train
google/ipaddr-py
ipaddr.py
_BaseNet._prefix_from_prefix_int
def _prefix_from_prefix_int(self, prefixlen): """Validate and return a prefix length integer. Args: prefixlen: An integer containing the prefix length. Returns: The input, possibly converted from long to int. Raises: NetmaskValueError: If the input ...
python
def _prefix_from_prefix_int(self, prefixlen): """Validate and return a prefix length integer. Args: prefixlen: An integer containing the prefix length. Returns: The input, possibly converted from long to int. Raises: NetmaskValueError: If the input ...
[ "def", "_prefix_from_prefix_int", "(", "self", ",", "prefixlen", ")", ":", "if", "not", "isinstance", "(", "prefixlen", ",", "(", "int", ",", "long", ")", ")", ":", "raise", "NetmaskValueError", "(", "'%r is not an integer'", "%", "prefixlen", ")", "prefixlen"...
Validate and return a prefix length integer. Args: prefixlen: An integer containing the prefix length. Returns: The input, possibly converted from long to int. Raises: NetmaskValueError: If the input is not an integer, or out of range.
[ "Validate", "and", "return", "a", "prefix", "length", "integer", "." ]
99e55513666db1276596d74f24863e056ca50851
https://github.com/google/ipaddr-py/blob/99e55513666db1276596d74f24863e056ca50851/ipaddr.py#L887-L905
train
raimon49/pip-licenses
piplicenses.py
output_colored
def output_colored(code, text, is_bold=False): """ Create function to output with color sequence """ if is_bold: code = '1;%s' % code return '\033[%sm%s\033[0m' % (code, text)
python
def output_colored(code, text, is_bold=False): """ Create function to output with color sequence """ if is_bold: code = '1;%s' % code return '\033[%sm%s\033[0m' % (code, text)
[ "def", "output_colored", "(", "code", ",", "text", ",", "is_bold", "=", "False", ")", ":", "if", "is_bold", ":", "code", "=", "'1;%s'", "%", "code", "return", "'\\033[%sm%s\\033[0m'", "%", "(", "code", ",", "text", ")" ]
Create function to output with color sequence
[ "Create", "function", "to", "output", "with", "color", "sequence" ]
879eddd9d75228ba7d6529bd3050d11ae6bf1712
https://github.com/raimon49/pip-licenses/blob/879eddd9d75228ba7d6529bd3050d11ae6bf1712/piplicenses.py#L504-L511
train
nickjj/flask-webpack
flask_webpack/__init__.py
Webpack._set_asset_paths
def _set_asset_paths(self, app): """ Read in the manifest json file which acts as a manifest for assets. This allows us to get the asset path as well as hashed names. :param app: Flask application :return: None """ webpack_stats = app.config['WEBPACK_MANIFEST_PAT...
python
def _set_asset_paths(self, app): """ Read in the manifest json file which acts as a manifest for assets. This allows us to get the asset path as well as hashed names. :param app: Flask application :return: None """ webpack_stats = app.config['WEBPACK_MANIFEST_PAT...
[ "def", "_set_asset_paths", "(", "self", ",", "app", ")", ":", "webpack_stats", "=", "app", ".", "config", "[", "'WEBPACK_MANIFEST_PATH'", "]", "try", ":", "with", "app", ".", "open_resource", "(", "webpack_stats", ",", "'r'", ")", "as", "stats_json", ":", ...
Read in the manifest json file which acts as a manifest for assets. This allows us to get the asset path as well as hashed names. :param app: Flask application :return: None
[ "Read", "in", "the", "manifest", "json", "file", "which", "acts", "as", "a", "manifest", "for", "assets", ".", "This", "allows", "us", "to", "get", "the", "asset", "path", "as", "well", "as", "hashed", "names", "." ]
241617c6ce0fd9ec11f507204958ddd0ec467634
https://github.com/nickjj/flask-webpack/blob/241617c6ce0fd9ec11f507204958ddd0ec467634/flask_webpack/__init__.py#L47-L70
train
nickjj/flask-webpack
flask_webpack/__init__.py
Webpack.javascript_tag
def javascript_tag(self, *args): """ Convenience tag to output 1 or more javascript tags. :param args: 1 or more javascript file names :return: Script tag(s) containing the asset """ tags = [] for arg in args: asset_path = self.asset_url_for('{0}.js'...
python
def javascript_tag(self, *args): """ Convenience tag to output 1 or more javascript tags. :param args: 1 or more javascript file names :return: Script tag(s) containing the asset """ tags = [] for arg in args: asset_path = self.asset_url_for('{0}.js'...
[ "def", "javascript_tag", "(", "self", ",", "*", "args", ")", ":", "tags", "=", "[", "]", "for", "arg", "in", "args", ":", "asset_path", "=", "self", ".", "asset_url_for", "(", "'{0}.js'", ".", "format", "(", "arg", ")", ")", "if", "asset_path", ":", ...
Convenience tag to output 1 or more javascript tags. :param args: 1 or more javascript file names :return: Script tag(s) containing the asset
[ "Convenience", "tag", "to", "output", "1", "or", "more", "javascript", "tags", "." ]
241617c6ce0fd9ec11f507204958ddd0ec467634
https://github.com/nickjj/flask-webpack/blob/241617c6ce0fd9ec11f507204958ddd0ec467634/flask_webpack/__init__.py#L81-L95
train
nickjj/flask-webpack
flask_webpack/__init__.py
Webpack.asset_url_for
def asset_url_for(self, asset): """ Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not found ""...
python
def asset_url_for(self, asset): """ Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not found ""...
[ "def", "asset_url_for", "(", "self", ",", "asset", ")", ":", "if", "'//'", "in", "asset", ":", "return", "asset", "if", "asset", "not", "in", "self", ".", "assets", ":", "return", "None", "return", "'{0}{1}'", ".", "format", "(", "self", ".", "assets_u...
Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not found
[ "Lookup", "the", "hashed", "asset", "path", "of", "a", "file", "name", "unless", "it", "starts", "with", "something", "that", "resembles", "a", "web", "address", "then", "take", "it", "as", "is", "." ]
241617c6ce0fd9ec11f507204958ddd0ec467634
https://github.com/nickjj/flask-webpack/blob/241617c6ce0fd9ec11f507204958ddd0ec467634/flask_webpack/__init__.py#L114-L129
train
hishnash/djangochannelsrestframework
djangochannelsrestframework/observer/observer.py
ModelObserver.pre_change_receiver
def pre_change_receiver(self, instance: Model, action: Action): """ Entry point for triggering the old_binding from save signals. """ if action == Action.CREATE: group_names = set() else: group_names = set(self.group_names(instance)) # use a threa...
python
def pre_change_receiver(self, instance: Model, action: Action): """ Entry point for triggering the old_binding from save signals. """ if action == Action.CREATE: group_names = set() else: group_names = set(self.group_names(instance)) # use a threa...
[ "def", "pre_change_receiver", "(", "self", ",", "instance", ":", "Model", ",", "action", ":", "Action", ")", ":", "if", "action", "==", "Action", ".", "CREATE", ":", "group_names", "=", "set", "(", ")", "else", ":", "group_names", "=", "set", "(", "sel...
Entry point for triggering the old_binding from save signals.
[ "Entry", "point", "for", "triggering", "the", "old_binding", "from", "save", "signals", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/observer/observer.py#L171-L187
train
hishnash/djangochannelsrestframework
djangochannelsrestframework/observer/observer.py
ModelObserver.post_change_receiver
def post_change_receiver(self, instance: Model, action: Action, **kwargs): """ Triggers the old_binding to possibly send to its group. """ try: old_group_names = instance.__instance_groups.observers[self] except (ValueError, KeyError): old_group_names = se...
python
def post_change_receiver(self, instance: Model, action: Action, **kwargs): """ Triggers the old_binding to possibly send to its group. """ try: old_group_names = instance.__instance_groups.observers[self] except (ValueError, KeyError): old_group_names = se...
[ "def", "post_change_receiver", "(", "self", ",", "instance", ":", "Model", ",", "action", ":", "Action", ",", "*", "*", "kwargs", ")", ":", "try", ":", "old_group_names", "=", "instance", ".", "__instance_groups", ".", "observers", "[", "self", "]", "excep...
Triggers the old_binding to possibly send to its group.
[ "Triggers", "the", "old_binding", "to", "possibly", "send", "to", "its", "group", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/observer/observer.py#L189-L226
train
hishnash/djangochannelsrestframework
djangochannelsrestframework/generics.py
GenericAsyncAPIConsumer.get_queryset
def get_queryset(self, **kwargs) -> QuerySet: """ Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset`...
python
def get_queryset(self, **kwargs) -> QuerySet: """ Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset`...
[ "def", "get_queryset", "(", "self", ",", "*", "*", "kwargs", ")", "->", "QuerySet", ":", "assert", "self", ".", "queryset", "is", "not", "None", ",", "(", "\"'%s' should either include a `queryset` attribute, \"", "\"or override the `get_queryset()` method.\"", "%", "...
Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached fo...
[ "Get", "the", "list", "of", "items", "for", "this", "view", ".", "This", "must", "be", "an", "iterable", "and", "may", "be", "a", "queryset", ".", "Defaults", "to", "using", "self", ".", "queryset", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/generics.py#L34-L59
train
hishnash/djangochannelsrestframework
djangochannelsrestframework/generics.py
GenericAsyncAPIConsumer.get_serializer_class
def get_serializer_class(self, **kwargs) -> Type[Serializer]: """ Return the class to use for the serializer. Defaults to using `self.serializer_class`. You may want to override this if you need to provide different serializations depending on the incoming request. (Eg....
python
def get_serializer_class(self, **kwargs) -> Type[Serializer]: """ Return the class to use for the serializer. Defaults to using `self.serializer_class`. You may want to override this if you need to provide different serializations depending on the incoming request. (Eg....
[ "def", "get_serializer_class", "(", "self", ",", "*", "*", "kwargs", ")", "->", "Type", "[", "Serializer", "]", ":", "assert", "self", ".", "serializer_class", "is", "not", "None", ",", "(", "\"'%s' should either include a `serializer_class` attribute, \"", "\"or ov...
Return the class to use for the serializer. Defaults to using `self.serializer_class`. You may want to override this if you need to provide different serializations depending on the incoming request. (Eg. admins get full serialization, others get basic serialization)
[ "Return", "the", "class", "to", "use", "for", "the", "serializer", ".", "Defaults", "to", "using", "self", ".", "serializer_class", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/generics.py#L109-L125
train
hishnash/djangochannelsrestframework
djangochannelsrestframework/consumers.py
view_as_consumer
def view_as_consumer( wrapped_view: typing.Callable[[HttpRequest], HttpResponse], mapped_actions: typing.Optional[ typing.Dict[str, str] ]=None) -> Type[AsyncConsumer]: """ Wrap a django View so that it will be triggered by actions over this json websocket consumer. ...
python
def view_as_consumer( wrapped_view: typing.Callable[[HttpRequest], HttpResponse], mapped_actions: typing.Optional[ typing.Dict[str, str] ]=None) -> Type[AsyncConsumer]: """ Wrap a django View so that it will be triggered by actions over this json websocket consumer. ...
[ "def", "view_as_consumer", "(", "wrapped_view", ":", "typing", ".", "Callable", "[", "[", "HttpRequest", "]", ",", "HttpResponse", "]", ",", "mapped_actions", ":", "typing", ".", "Optional", "[", "typing", ".", "Dict", "[", "str", ",", "str", "]", "]", "...
Wrap a django View so that it will be triggered by actions over this json websocket consumer.
[ "Wrap", "a", "django", "View", "so", "that", "it", "will", "be", "triggered", "by", "actions", "over", "this", "json", "websocket", "consumer", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L303-L324
train