id
int32
0
252k
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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
1,900
edx/XBlock
xblock/runtime.py
Runtime.render_asides
def render_asides(self, block, view_name, frag, context): """ Collect all of the asides' add ons and format them into the frag. The frag already has the given block's rendering. """ aside_frag_fns = [] for aside in self.get_asides(block): aside_view_fn = aside.aside_view_declaration(view_name) if aside_view_fn is not None: aside_frag_fns.append((aside, aside_view_fn)) if aside_frag_fns: # layout (overideable by other runtimes) return self.layout_asides(block, context, frag, view_name, aside_frag_fns) return frag
python
def render_asides(self, block, view_name, frag, context): """ Collect all of the asides' add ons and format them into the frag. The frag already has the given block's rendering. """ aside_frag_fns = [] for aside in self.get_asides(block): aside_view_fn = aside.aside_view_declaration(view_name) if aside_view_fn is not None: aside_frag_fns.append((aside, aside_view_fn)) if aside_frag_fns: # layout (overideable by other runtimes) return self.layout_asides(block, context, frag, view_name, aside_frag_fns) return frag
[ "def", "render_asides", "(", "self", ",", "block", ",", "view_name", ",", "frag", ",", "context", ")", ":", "aside_frag_fns", "=", "[", "]", "for", "aside", "in", "self", ".", "get_asides", "(", "block", ")", ":", "aside_view_fn", "=", "aside", ".", "aside_view_declaration", "(", "view_name", ")", "if", "aside_view_fn", "is", "not", "None", ":", "aside_frag_fns", ".", "append", "(", "(", "aside", ",", "aside_view_fn", ")", ")", "if", "aside_frag_fns", ":", "# layout (overideable by other runtimes)", "return", "self", ".", "layout_asides", "(", "block", ",", "context", ",", "frag", ",", "view_name", ",", "aside_frag_fns", ")", "return", "frag" ]
Collect all of the asides' add ons and format them into the frag. The frag already has the given block's rendering.
[ "Collect", "all", "of", "the", "asides", "add", "ons", "and", "format", "them", "into", "the", "frag", ".", "The", "frag", "already", "has", "the", "given", "block", "s", "rendering", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L982-L995
1,901
edx/XBlock
xblock/runtime.py
Runtime.layout_asides
def layout_asides(self, block, context, frag, view_name, aside_frag_fns): """ Execute and layout the aside_frags wrt the block's frag. Runtimes should feel free to override this method to control execution, place, and style the asides appropriately for their application This default method appends the aside_frags after frag. If you override this, you must call wrap_aside around each aside as per this function. Args: block (XBlock): the block being rendered frag (html): The result from rendering the block aside_frag_fns list((aside, aside_fn)): The asides and closures for rendering to call """ result = Fragment(frag.content) result.add_fragment_resources(frag) for aside, aside_fn in aside_frag_fns: aside_frag = self.wrap_aside(block, aside, view_name, aside_fn(block, context), context) aside.save() result.add_content(aside_frag.content) result.add_fragment_resources(aside_frag) return result
python
def layout_asides(self, block, context, frag, view_name, aside_frag_fns): """ Execute and layout the aside_frags wrt the block's frag. Runtimes should feel free to override this method to control execution, place, and style the asides appropriately for their application This default method appends the aside_frags after frag. If you override this, you must call wrap_aside around each aside as per this function. Args: block (XBlock): the block being rendered frag (html): The result from rendering the block aside_frag_fns list((aside, aside_fn)): The asides and closures for rendering to call """ result = Fragment(frag.content) result.add_fragment_resources(frag) for aside, aside_fn in aside_frag_fns: aside_frag = self.wrap_aside(block, aside, view_name, aside_fn(block, context), context) aside.save() result.add_content(aside_frag.content) result.add_fragment_resources(aside_frag) return result
[ "def", "layout_asides", "(", "self", ",", "block", ",", "context", ",", "frag", ",", "view_name", ",", "aside_frag_fns", ")", ":", "result", "=", "Fragment", "(", "frag", ".", "content", ")", "result", ".", "add_fragment_resources", "(", "frag", ")", "for", "aside", ",", "aside_fn", "in", "aside_frag_fns", ":", "aside_frag", "=", "self", ".", "wrap_aside", "(", "block", ",", "aside", ",", "view_name", ",", "aside_fn", "(", "block", ",", "context", ")", ",", "context", ")", "aside", ".", "save", "(", ")", "result", ".", "add_content", "(", "aside_frag", ".", "content", ")", "result", ".", "add_fragment_resources", "(", "aside_frag", ")", "return", "result" ]
Execute and layout the aside_frags wrt the block's frag. Runtimes should feel free to override this method to control execution, place, and style the asides appropriately for their application This default method appends the aside_frags after frag. If you override this, you must call wrap_aside around each aside as per this function. Args: block (XBlock): the block being rendered frag (html): The result from rendering the block aside_frag_fns list((aside, aside_fn)): The asides and closures for rendering to call
[ "Execute", "and", "layout", "the", "aside_frags", "wrt", "the", "block", "s", "frag", ".", "Runtimes", "should", "feel", "free", "to", "override", "this", "method", "to", "control", "execution", "place", "and", "style", "the", "asides", "appropriately", "for", "their", "application" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L997-L1019
1,902
edx/XBlock
xblock/runtime.py
Runtime.handle
def handle(self, block, handler_name, request, suffix=''): """ Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available """ handler = getattr(block, handler_name, None) if handler and getattr(handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = handler(request, suffix) else: fallback_handler = getattr(block, "fallback_handler", None) if fallback_handler and getattr(fallback_handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = fallback_handler(handler_name, request, suffix) else: raise NoSuchHandlerError("Couldn't find handler %r for %r" % (handler_name, block)) # Write out dirty fields block.save() return results
python
def handle(self, block, handler_name, request, suffix=''): """ Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available """ handler = getattr(block, handler_name, None) if handler and getattr(handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = handler(request, suffix) else: fallback_handler = getattr(block, "fallback_handler", None) if fallback_handler and getattr(fallback_handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = fallback_handler(handler_name, request, suffix) else: raise NoSuchHandlerError("Couldn't find handler %r for %r" % (handler_name, block)) # Write out dirty fields block.save() return results
[ "def", "handle", "(", "self", ",", "block", ",", "handler_name", ",", "request", ",", "suffix", "=", "''", ")", ":", "handler", "=", "getattr", "(", "block", ",", "handler_name", ",", "None", ")", "if", "handler", "and", "getattr", "(", "handler", ",", "'_is_xblock_handler'", ",", "False", ")", ":", "# Cache results of the handler call for later saving", "results", "=", "handler", "(", "request", ",", "suffix", ")", "else", ":", "fallback_handler", "=", "getattr", "(", "block", ",", "\"fallback_handler\"", ",", "None", ")", "if", "fallback_handler", "and", "getattr", "(", "fallback_handler", ",", "'_is_xblock_handler'", ",", "False", ")", ":", "# Cache results of the handler call for later saving", "results", "=", "fallback_handler", "(", "handler_name", ",", "request", ",", "suffix", ")", "else", ":", "raise", "NoSuchHandlerError", "(", "\"Couldn't find handler %r for %r\"", "%", "(", "handler_name", ",", "block", ")", ")", "# Write out dirty fields", "block", ".", "save", "(", ")", "return", "results" ]
Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available
[ "Handles", "any", "calls", "to", "the", "specified", "handler_name", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1023-L1048
1,903
edx/XBlock
xblock/runtime.py
Runtime.service
def service(self, block, service_name): """Return a service, or None. Services are objects implementing arbitrary other interfaces. They are requested by agreed-upon names, see [XXX TODO] for a list of possible services. The object returned depends on the service requested. XBlocks must announce their intention to request services with the `XBlock.needs` or `XBlock.wants` decorators. Use `needs` if you assume that the service is available, or `wants` if your code is flexible and can accept a None from this method. Runtimes can override this method if they have different techniques for finding and delivering services. Arguments: block (XBlock): this block's class will be examined for service decorators. service_name (str): the name of the service requested. Returns: An object implementing the requested service, or None. """ declaration = block.service_declaration(service_name) if declaration is None: raise NoSuchServiceError("Service {!r} was not requested.".format(service_name)) service = self._services.get(service_name) if service is None and declaration == "need": raise NoSuchServiceError("Service {!r} is not available.".format(service_name)) return service
python
def service(self, block, service_name): """Return a service, or None. Services are objects implementing arbitrary other interfaces. They are requested by agreed-upon names, see [XXX TODO] for a list of possible services. The object returned depends on the service requested. XBlocks must announce their intention to request services with the `XBlock.needs` or `XBlock.wants` decorators. Use `needs` if you assume that the service is available, or `wants` if your code is flexible and can accept a None from this method. Runtimes can override this method if they have different techniques for finding and delivering services. Arguments: block (XBlock): this block's class will be examined for service decorators. service_name (str): the name of the service requested. Returns: An object implementing the requested service, or None. """ declaration = block.service_declaration(service_name) if declaration is None: raise NoSuchServiceError("Service {!r} was not requested.".format(service_name)) service = self._services.get(service_name) if service is None and declaration == "need": raise NoSuchServiceError("Service {!r} is not available.".format(service_name)) return service
[ "def", "service", "(", "self", ",", "block", ",", "service_name", ")", ":", "declaration", "=", "block", ".", "service_declaration", "(", "service_name", ")", "if", "declaration", "is", "None", ":", "raise", "NoSuchServiceError", "(", "\"Service {!r} was not requested.\"", ".", "format", "(", "service_name", ")", ")", "service", "=", "self", ".", "_services", ".", "get", "(", "service_name", ")", "if", "service", "is", "None", "and", "declaration", "==", "\"need\"", ":", "raise", "NoSuchServiceError", "(", "\"Service {!r} is not available.\"", ".", "format", "(", "service_name", ")", ")", "return", "service" ]
Return a service, or None. Services are objects implementing arbitrary other interfaces. They are requested by agreed-upon names, see [XXX TODO] for a list of possible services. The object returned depends on the service requested. XBlocks must announce their intention to request services with the `XBlock.needs` or `XBlock.wants` decorators. Use `needs` if you assume that the service is available, or `wants` if your code is flexible and can accept a None from this method. Runtimes can override this method if they have different techniques for finding and delivering services. Arguments: block (XBlock): this block's class will be examined for service decorators. service_name (str): the name of the service requested. Returns: An object implementing the requested service, or None.
[ "Return", "a", "service", "or", "None", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1052-L1082
1,904
edx/XBlock
xblock/runtime.py
Runtime.querypath
def querypath(self, block, path): """An XPath-like interface to `query`.""" class BadPath(Exception): """Bad path exception thrown when path cannot be found.""" pass results = self.query(block) ROOT, SEP, WORD, FINAL = six.moves.range(4) # pylint: disable=C0103 state = ROOT lexer = RegexLexer( ("dotdot", r"\.\."), ("dot", r"\."), ("slashslash", r"//"), ("slash", r"/"), ("atword", r"@\w+"), ("word", r"\w+"), ("err", r"."), ) for tokname, toktext in lexer.lex(path): if state == FINAL: # Shouldn't be any tokens after a last token. raise BadPath() if tokname == "dotdot": # .. (parent) if state == WORD: raise BadPath() results = results.parent() state = WORD elif tokname == "dot": # . (current node) if state == WORD: raise BadPath() state = WORD elif tokname == "slashslash": # // (descendants) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() results = results.descendants() state = SEP elif tokname == "slash": # / (here) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() state = SEP elif tokname == "atword": # @xxx (attribute access) if state != SEP: raise BadPath() results = results.attr(toktext[1:]) state = FINAL elif tokname == "word": # xxx (tag selection) if state != SEP: raise BadPath() results = results.children().tagged(toktext) state = WORD else: raise BadPath("Invalid thing: %r" % toktext) return results
python
def querypath(self, block, path): """An XPath-like interface to `query`.""" class BadPath(Exception): """Bad path exception thrown when path cannot be found.""" pass results = self.query(block) ROOT, SEP, WORD, FINAL = six.moves.range(4) # pylint: disable=C0103 state = ROOT lexer = RegexLexer( ("dotdot", r"\.\."), ("dot", r"\."), ("slashslash", r"//"), ("slash", r"/"), ("atword", r"@\w+"), ("word", r"\w+"), ("err", r"."), ) for tokname, toktext in lexer.lex(path): if state == FINAL: # Shouldn't be any tokens after a last token. raise BadPath() if tokname == "dotdot": # .. (parent) if state == WORD: raise BadPath() results = results.parent() state = WORD elif tokname == "dot": # . (current node) if state == WORD: raise BadPath() state = WORD elif tokname == "slashslash": # // (descendants) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() results = results.descendants() state = SEP elif tokname == "slash": # / (here) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() state = SEP elif tokname == "atword": # @xxx (attribute access) if state != SEP: raise BadPath() results = results.attr(toktext[1:]) state = FINAL elif tokname == "word": # xxx (tag selection) if state != SEP: raise BadPath() results = results.children().tagged(toktext) state = WORD else: raise BadPath("Invalid thing: %r" % toktext) return results
[ "def", "querypath", "(", "self", ",", "block", ",", "path", ")", ":", "class", "BadPath", "(", "Exception", ")", ":", "\"\"\"Bad path exception thrown when path cannot be found.\"\"\"", "pass", "results", "=", "self", ".", "query", "(", "block", ")", "ROOT", ",", "SEP", ",", "WORD", ",", "FINAL", "=", "six", ".", "moves", ".", "range", "(", "4", ")", "# pylint: disable=C0103", "state", "=", "ROOT", "lexer", "=", "RegexLexer", "(", "(", "\"dotdot\"", ",", "r\"\\.\\.\"", ")", ",", "(", "\"dot\"", ",", "r\"\\.\"", ")", ",", "(", "\"slashslash\"", ",", "r\"//\"", ")", ",", "(", "\"slash\"", ",", "r\"/\"", ")", ",", "(", "\"atword\"", ",", "r\"@\\w+\"", ")", ",", "(", "\"word\"", ",", "r\"\\w+\"", ")", ",", "(", "\"err\"", ",", "r\".\"", ")", ",", ")", "for", "tokname", ",", "toktext", "in", "lexer", ".", "lex", "(", "path", ")", ":", "if", "state", "==", "FINAL", ":", "# Shouldn't be any tokens after a last token.", "raise", "BadPath", "(", ")", "if", "tokname", "==", "\"dotdot\"", ":", "# .. (parent)", "if", "state", "==", "WORD", ":", "raise", "BadPath", "(", ")", "results", "=", "results", ".", "parent", "(", ")", "state", "=", "WORD", "elif", "tokname", "==", "\"dot\"", ":", "# . (current node)", "if", "state", "==", "WORD", ":", "raise", "BadPath", "(", ")", "state", "=", "WORD", "elif", "tokname", "==", "\"slashslash\"", ":", "# // (descendants)", "if", "state", "==", "SEP", ":", "raise", "BadPath", "(", ")", "if", "state", "==", "ROOT", ":", "raise", "NotImplementedError", "(", ")", "results", "=", "results", ".", "descendants", "(", ")", "state", "=", "SEP", "elif", "tokname", "==", "\"slash\"", ":", "# / (here)", "if", "state", "==", "SEP", ":", "raise", "BadPath", "(", ")", "if", "state", "==", "ROOT", ":", "raise", "NotImplementedError", "(", ")", "state", "=", "SEP", "elif", "tokname", "==", "\"atword\"", ":", "# @xxx (attribute access)", "if", "state", "!=", "SEP", ":", "raise", "BadPath", "(", ")", "results", "=", "results", ".", "attr", "(", "toktext", "[", "1", ":", "]", ")", "state", "=", "FINAL", "elif", "tokname", "==", "\"word\"", ":", "# xxx (tag selection)", "if", "state", "!=", "SEP", ":", "raise", "BadPath", "(", ")", "results", "=", "results", ".", "children", "(", ")", ".", "tagged", "(", "toktext", ")", "state", "=", "WORD", "else", ":", "raise", "BadPath", "(", "\"Invalid thing: %r\"", "%", "toktext", ")", "return", "results" ]
An XPath-like interface to `query`.
[ "An", "XPath", "-", "like", "interface", "to", "query", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1095-L1156
1,905
edx/XBlock
xblock/runtime.py
ObjectAggregator._object_with_attr
def _object_with_attr(self, name): """ Returns the first object that has the attribute `name` :param name: the attribute to filter by :type name: `str` :raises AttributeError: when no object has the named attribute """ for obj in self._objects: if hasattr(obj, name): return obj raise AttributeError("No object has attribute {!r}".format(name))
python
def _object_with_attr(self, name): """ Returns the first object that has the attribute `name` :param name: the attribute to filter by :type name: `str` :raises AttributeError: when no object has the named attribute """ for obj in self._objects: if hasattr(obj, name): return obj raise AttributeError("No object has attribute {!r}".format(name))
[ "def", "_object_with_attr", "(", "self", ",", "name", ")", ":", "for", "obj", "in", "self", ".", "_objects", ":", "if", "hasattr", "(", "obj", ",", "name", ")", ":", "return", "obj", "raise", "AttributeError", "(", "\"No object has attribute {!r}\"", ".", "format", "(", "name", ")", ")" ]
Returns the first object that has the attribute `name` :param name: the attribute to filter by :type name: `str` :raises AttributeError: when no object has the named attribute
[ "Returns", "the", "first", "object", "that", "has", "the", "attribute", "name" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1179-L1191
1,906
edx/XBlock
xblock/runtime.py
Mixologist.mix
def mix(self, cls): """ Returns a subclass of `cls` mixed with `self.mixins`. :param cls: The base class to mix into :type cls: `class` """ if hasattr(cls, 'unmixed_class'): base_class = cls.unmixed_class old_mixins = cls.__bases__[1:] # Skip the original unmixed class mixins = old_mixins + tuple( mixin for mixin in self._mixins if mixin not in old_mixins ) else: base_class = cls mixins = self._mixins mixin_key = (base_class, mixins) if mixin_key not in _CLASS_CACHE: # Only lock if we're about to make a new class with _CLASS_CACHE_LOCK: # Use setdefault so that if someone else has already # created a class before we got the lock, we don't # overwrite it return _CLASS_CACHE.setdefault(mixin_key, type( base_class.__name__ + str('WithMixins'), # type() requires native str (base_class, ) + mixins, {'unmixed_class': base_class} )) else: return _CLASS_CACHE[mixin_key]
python
def mix(self, cls): """ Returns a subclass of `cls` mixed with `self.mixins`. :param cls: The base class to mix into :type cls: `class` """ if hasattr(cls, 'unmixed_class'): base_class = cls.unmixed_class old_mixins = cls.__bases__[1:] # Skip the original unmixed class mixins = old_mixins + tuple( mixin for mixin in self._mixins if mixin not in old_mixins ) else: base_class = cls mixins = self._mixins mixin_key = (base_class, mixins) if mixin_key not in _CLASS_CACHE: # Only lock if we're about to make a new class with _CLASS_CACHE_LOCK: # Use setdefault so that if someone else has already # created a class before we got the lock, we don't # overwrite it return _CLASS_CACHE.setdefault(mixin_key, type( base_class.__name__ + str('WithMixins'), # type() requires native str (base_class, ) + mixins, {'unmixed_class': base_class} )) else: return _CLASS_CACHE[mixin_key]
[ "def", "mix", "(", "self", ",", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'unmixed_class'", ")", ":", "base_class", "=", "cls", ".", "unmixed_class", "old_mixins", "=", "cls", ".", "__bases__", "[", "1", ":", "]", "# Skip the original unmixed class", "mixins", "=", "old_mixins", "+", "tuple", "(", "mixin", "for", "mixin", "in", "self", ".", "_mixins", "if", "mixin", "not", "in", "old_mixins", ")", "else", ":", "base_class", "=", "cls", "mixins", "=", "self", ".", "_mixins", "mixin_key", "=", "(", "base_class", ",", "mixins", ")", "if", "mixin_key", "not", "in", "_CLASS_CACHE", ":", "# Only lock if we're about to make a new class", "with", "_CLASS_CACHE_LOCK", ":", "# Use setdefault so that if someone else has already", "# created a class before we got the lock, we don't", "# overwrite it", "return", "_CLASS_CACHE", ".", "setdefault", "(", "mixin_key", ",", "type", "(", "base_class", ".", "__name__", "+", "str", "(", "'WithMixins'", ")", ",", "# type() requires native str", "(", "base_class", ",", ")", "+", "mixins", ",", "{", "'unmixed_class'", ":", "base_class", "}", ")", ")", "else", ":", "return", "_CLASS_CACHE", "[", "mixin_key", "]" ]
Returns a subclass of `cls` mixed with `self.mixins`. :param cls: The base class to mix into :type cls: `class`
[ "Returns", "a", "subclass", "of", "cls", "mixed", "with", "self", ".", "mixins", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1219-L1253
1,907
edx/XBlock
xblock/runtime.py
RegexLexer.lex
def lex(self, text): """Iterator that tokenizes `text` and yields up tokens as they are found""" for match in self.regex.finditer(text): name = match.lastgroup yield (name, match.group(name))
python
def lex(self, text): """Iterator that tokenizes `text` and yields up tokens as they are found""" for match in self.regex.finditer(text): name = match.lastgroup yield (name, match.group(name))
[ "def", "lex", "(", "self", ",", "text", ")", ":", "for", "match", "in", "self", ".", "regex", ".", "finditer", "(", "text", ")", ":", "name", "=", "match", ".", "lastgroup", "yield", "(", "name", ",", "match", ".", "group", "(", "name", ")", ")" ]
Iterator that tokenizes `text` and yields up tokens as they are found
[ "Iterator", "that", "tokenizes", "text", "and", "yields", "up", "tokens", "as", "they", "are", "found" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1264-L1268
1,908
edx/XBlock
xblock/runtime.py
NullI18nService.strftime
def strftime(self, dtime, format): # pylint: disable=redefined-builtin """ Locale-aware strftime, with format short-cuts. """ format = self.STRFTIME_FORMATS.get(format + "_FORMAT", format) if six.PY2 and isinstance(format, six.text_type): format = format.encode("utf8") timestring = dtime.strftime(format) if six.PY2: timestring = timestring.decode("utf8") return timestring
python
def strftime(self, dtime, format): # pylint: disable=redefined-builtin """ Locale-aware strftime, with format short-cuts. """ format = self.STRFTIME_FORMATS.get(format + "_FORMAT", format) if six.PY2 and isinstance(format, six.text_type): format = format.encode("utf8") timestring = dtime.strftime(format) if six.PY2: timestring = timestring.decode("utf8") return timestring
[ "def", "strftime", "(", "self", ",", "dtime", ",", "format", ")", ":", "# pylint: disable=redefined-builtin", "format", "=", "self", ".", "STRFTIME_FORMATS", ".", "get", "(", "format", "+", "\"_FORMAT\"", ",", "format", ")", "if", "six", ".", "PY2", "and", "isinstance", "(", "format", ",", "six", ".", "text_type", ")", ":", "format", "=", "format", ".", "encode", "(", "\"utf8\"", ")", "timestring", "=", "dtime", ".", "strftime", "(", "format", ")", "if", "six", ".", "PY2", ":", "timestring", "=", "timestring", ".", "decode", "(", "\"utf8\"", ")", "return", "timestring" ]
Locale-aware strftime, with format short-cuts.
[ "Locale", "-", "aware", "strftime", "with", "format", "short", "-", "cuts", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1288-L1298
1,909
edx/XBlock
xblock/runtime.py
NullI18nService.ugettext
def ugettext(self): """ Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if six.PY2: return self._translations.ugettext else: return self._translations.gettext
python
def ugettext(self): """ Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if six.PY2: return self._translations.ugettext else: return self._translations.gettext
[ "def", "ugettext", "(", "self", ")", ":", "# pylint: disable=no-member", "if", "six", ".", "PY2", ":", "return", "self", ".", "_translations", ".", "ugettext", "else", ":", "return", "self", ".", "_translations", ".", "gettext" ]
Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings.
[ "Dispatch", "to", "the", "appropriate", "gettext", "method", "to", "handle", "text", "objects", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1301-L1312
1,910
edx/XBlock
xblock/runtime.py
NullI18nService.ungettext
def ungettext(self): """ Dispatch to the appropriate ngettext method to handle text objects. Note that under python 3, this uses `ngettext()`, while under python 2, it uses `ungettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if six.PY2: return self._translations.ungettext else: return self._translations.ngettext
python
def ungettext(self): """ Dispatch to the appropriate ngettext method to handle text objects. Note that under python 3, this uses `ngettext()`, while under python 2, it uses `ungettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if six.PY2: return self._translations.ungettext else: return self._translations.ngettext
[ "def", "ungettext", "(", "self", ")", ":", "# pylint: disable=no-member", "if", "six", ".", "PY2", ":", "return", "self", ".", "_translations", ".", "ungettext", "else", ":", "return", "self", ".", "_translations", ".", "ngettext" ]
Dispatch to the appropriate ngettext method to handle text objects. Note that under python 3, this uses `ngettext()`, while under python 2, it uses `ungettext()`. This should not be used with bytestrings.
[ "Dispatch", "to", "the", "appropriate", "ngettext", "method", "to", "handle", "text", "objects", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1315-L1326
1,911
edx/XBlock
xblock/reference/plugins.py
FSService.load
def load(self, instance, xblock): """ Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped. """ # TODO: Get xblock from context, once the plumbing is piped through if djpyfs: return djpyfs.get_filesystem(scope_key(instance, xblock)) else: # The reference implementation relies on djpyfs # https://github.com/edx/django-pyfs # For Django runtimes, you may use this reference # implementation. Otherwise, you will need to # patch pyfilesystem yourself to implement get_url. raise NotImplementedError("djpyfs not available")
python
def load(self, instance, xblock): """ Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped. """ # TODO: Get xblock from context, once the plumbing is piped through if djpyfs: return djpyfs.get_filesystem(scope_key(instance, xblock)) else: # The reference implementation relies on djpyfs # https://github.com/edx/django-pyfs # For Django runtimes, you may use this reference # implementation. Otherwise, you will need to # patch pyfilesystem yourself to implement get_url. raise NotImplementedError("djpyfs not available")
[ "def", "load", "(", "self", ",", "instance", ",", "xblock", ")", ":", "# TODO: Get xblock from context, once the plumbing is piped through", "if", "djpyfs", ":", "return", "djpyfs", ".", "get_filesystem", "(", "scope_key", "(", "instance", ",", "xblock", ")", ")", "else", ":", "# The reference implementation relies on djpyfs", "# https://github.com/edx/django-pyfs", "# For Django runtimes, you may use this reference", "# implementation. Otherwise, you will need to", "# patch pyfilesystem yourself to implement get_url.", "raise", "NotImplementedError", "(", "\"djpyfs not available\"", ")" ]
Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped.
[ "Get", "the", "filesystem", "for", "the", "field", "specified", "in", "instance", "and", "the", "xblock", "in", "xblock", "It", "is", "locally", "scoped", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/reference/plugins.py#L190-L205
1,912
edx/XBlock
xblock/completable.py
CompletableXBlockMixin.emit_completion
def emit_completion(self, completion_percent): """ Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. Arguments: completion_percent (float): Completion in range [0.0; 1.0] (inclusive), where 0.0 means the block is not completed, 1.0 means the block is fully completed. Returns: None """ completion_mode = XBlockCompletionMode.get_mode(self) if not self.has_custom_completion or completion_mode != XBlockCompletionMode.COMPLETABLE: raise AttributeError( "Using `emit_completion` requires `has_custom_completion == True` (was {}) " "and `completion_mode == 'completable'` (was {})".format( self.has_custom_completion, completion_mode, ) ) if completion_percent is None or not 0.0 <= completion_percent <= 1.0: raise ValueError("Completion percent must be in [0.0; 1.0] interval, {} given".format(completion_percent)) self.runtime.publish( self, 'completion', {'completion': completion_percent}, )
python
def emit_completion(self, completion_percent): """ Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. Arguments: completion_percent (float): Completion in range [0.0; 1.0] (inclusive), where 0.0 means the block is not completed, 1.0 means the block is fully completed. Returns: None """ completion_mode = XBlockCompletionMode.get_mode(self) if not self.has_custom_completion or completion_mode != XBlockCompletionMode.COMPLETABLE: raise AttributeError( "Using `emit_completion` requires `has_custom_completion == True` (was {}) " "and `completion_mode == 'completable'` (was {})".format( self.has_custom_completion, completion_mode, ) ) if completion_percent is None or not 0.0 <= completion_percent <= 1.0: raise ValueError("Completion percent must be in [0.0; 1.0] interval, {} given".format(completion_percent)) self.runtime.publish( self, 'completion', {'completion': completion_percent}, )
[ "def", "emit_completion", "(", "self", ",", "completion_percent", ")", ":", "completion_mode", "=", "XBlockCompletionMode", ".", "get_mode", "(", "self", ")", "if", "not", "self", ".", "has_custom_completion", "or", "completion_mode", "!=", "XBlockCompletionMode", ".", "COMPLETABLE", ":", "raise", "AttributeError", "(", "\"Using `emit_completion` requires `has_custom_completion == True` (was {}) \"", "\"and `completion_mode == 'completable'` (was {})\"", ".", "format", "(", "self", ".", "has_custom_completion", ",", "completion_mode", ",", ")", ")", "if", "completion_percent", "is", "None", "or", "not", "0.0", "<=", "completion_percent", "<=", "1.0", ":", "raise", "ValueError", "(", "\"Completion percent must be in [0.0; 1.0] interval, {} given\"", ".", "format", "(", "completion_percent", ")", ")", "self", ".", "runtime", ".", "publish", "(", "self", ",", "'completion'", ",", "{", "'completion'", ":", "completion_percent", "}", ",", ")" ]
Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. Arguments: completion_percent (float): Completion in range [0.0; 1.0] (inclusive), where 0.0 means the block is not completed, 1.0 means the block is fully completed. Returns: None
[ "Emits", "completion", "event", "through", "Completion", "API", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/completable.py#L35-L65
1,913
edx/XBlock
xblock/field_data.py
FieldData.has
def has(self, block, name): """ Return whether or not the field named `name` has a non-default value for the XBlock `block`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str """ try: self.get(block, name) return True except KeyError: return False
python
def has(self, block, name): """ Return whether or not the field named `name` has a non-default value for the XBlock `block`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str """ try: self.get(block, name) return True except KeyError: return False
[ "def", "has", "(", "self", ",", "block", ",", "name", ")", ":", "try", ":", "self", ".", "get", "(", "block", ",", "name", ")", "return", "True", "except", "KeyError", ":", "return", "False" ]
Return whether or not the field named `name` has a non-default value for the XBlock `block`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str
[ "Return", "whether", "or", "not", "the", "field", "named", "name", "has", "a", "non", "-", "default", "value", "for", "the", "XBlock", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/field_data.py#L69-L82
1,914
edx/XBlock
xblock/field_data.py
FieldData.set_many
def set_many(self, block, update_dict): """ Update many fields on an XBlock simultaneously. :param block: the block to update :type block: :class:`~xblock.core.XBlock` :param update_dict: A map of field names to their new values :type update_dict: dict """ for key, value in six.iteritems(update_dict): self.set(block, key, value)
python
def set_many(self, block, update_dict): """ Update many fields on an XBlock simultaneously. :param block: the block to update :type block: :class:`~xblock.core.XBlock` :param update_dict: A map of field names to their new values :type update_dict: dict """ for key, value in six.iteritems(update_dict): self.set(block, key, value)
[ "def", "set_many", "(", "self", ",", "block", ",", "update_dict", ")", ":", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "update_dict", ")", ":", "self", ".", "set", "(", "block", ",", "key", ",", "value", ")" ]
Update many fields on an XBlock simultaneously. :param block: the block to update :type block: :class:`~xblock.core.XBlock` :param update_dict: A map of field names to their new values :type update_dict: dict
[ "Update", "many", "fields", "on", "an", "XBlock", "simultaneously", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/field_data.py#L84-L94
1,915
edx/XBlock
xblock/exceptions.py
JsonHandlerError.get_response
def get_response(self, **kwargs): """ Returns a Response object containing this object's status code and a JSON object containing the key "error" with the value of this object's error message in the body. Keyword args are passed through to the Response. """ return Response( json.dumps({"error": self.message}), # pylint: disable=exception-message-attribute status_code=self.status_code, content_type="application/json", charset="utf-8", **kwargs )
python
def get_response(self, **kwargs): """ Returns a Response object containing this object's status code and a JSON object containing the key "error" with the value of this object's error message in the body. Keyword args are passed through to the Response. """ return Response( json.dumps({"error": self.message}), # pylint: disable=exception-message-attribute status_code=self.status_code, content_type="application/json", charset="utf-8", **kwargs )
[ "def", "get_response", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "Response", "(", "json", ".", "dumps", "(", "{", "\"error\"", ":", "self", ".", "message", "}", ")", ",", "# pylint: disable=exception-message-attribute", "status_code", "=", "self", ".", "status_code", ",", "content_type", "=", "\"application/json\"", ",", "charset", "=", "\"utf-8\"", ",", "*", "*", "kwargs", ")" ]
Returns a Response object containing this object's status code and a JSON object containing the key "error" with the value of this object's error message in the body. Keyword args are passed through to the Response.
[ "Returns", "a", "Response", "object", "containing", "this", "object", "s", "status", "code", "and", "a", "JSON", "object", "containing", "the", "key", "error", "with", "the", "value", "of", "this", "object", "s", "error", "message", "in", "the", "body", ".", "Keyword", "args", "are", "passed", "through", "to", "the", "Response", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/exceptions.py#L126-L139
1,916
edx/XBlock
xblock/mixins.py
HandlersMixin.json_handler
def json_handler(cls, func): """ Wrap a handler to consume and produce JSON. Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function will be JSON-encoded and returned as the response. The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code. This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON. """ @cls.handler @functools.wraps(func) def wrapper(self, request, suffix=''): """The wrapper function `json_handler` returns.""" if request.method != "POST": return JsonHandlerError(405, "Method must be POST").get_response(allow=["POST"]) try: request_json = json.loads(request.body) except ValueError: return JsonHandlerError(400, "Invalid JSON").get_response() try: response = func(self, request_json, suffix) except JsonHandlerError as err: return err.get_response() if isinstance(response, Response): return response else: return Response(json.dumps(response), content_type='application/json', charset='utf8') return wrapper
python
def json_handler(cls, func): """ Wrap a handler to consume and produce JSON. Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function will be JSON-encoded and returned as the response. The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code. This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON. """ @cls.handler @functools.wraps(func) def wrapper(self, request, suffix=''): """The wrapper function `json_handler` returns.""" if request.method != "POST": return JsonHandlerError(405, "Method must be POST").get_response(allow=["POST"]) try: request_json = json.loads(request.body) except ValueError: return JsonHandlerError(400, "Invalid JSON").get_response() try: response = func(self, request_json, suffix) except JsonHandlerError as err: return err.get_response() if isinstance(response, Response): return response else: return Response(json.dumps(response), content_type='application/json', charset='utf8') return wrapper
[ "def", "json_handler", "(", "cls", ",", "func", ")", ":", "@", "cls", ".", "handler", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "request", ",", "suffix", "=", "''", ")", ":", "\"\"\"The wrapper function `json_handler` returns.\"\"\"", "if", "request", ".", "method", "!=", "\"POST\"", ":", "return", "JsonHandlerError", "(", "405", ",", "\"Method must be POST\"", ")", ".", "get_response", "(", "allow", "=", "[", "\"POST\"", "]", ")", "try", ":", "request_json", "=", "json", ".", "loads", "(", "request", ".", "body", ")", "except", "ValueError", ":", "return", "JsonHandlerError", "(", "400", ",", "\"Invalid JSON\"", ")", ".", "get_response", "(", ")", "try", ":", "response", "=", "func", "(", "self", ",", "request_json", ",", "suffix", ")", "except", "JsonHandlerError", "as", "err", ":", "return", "err", ".", "get_response", "(", ")", "if", "isinstance", "(", "response", ",", "Response", ")", ":", "return", "response", "else", ":", "return", "Response", "(", "json", ".", "dumps", "(", "response", ")", ",", "content_type", "=", "'application/json'", ",", "charset", "=", "'utf8'", ")", "return", "wrapper" ]
Wrap a handler to consume and produce JSON. Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function will be JSON-encoded and returned as the response. The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code. This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON.
[ "Wrap", "a", "handler", "to", "consume", "and", "produce", "JSON", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L40-L75
1,917
edx/XBlock
xblock/mixins.py
HandlersMixin.handle
def handle(self, handler_name, request, suffix=''): """Handle `request` with this block's runtime.""" return self.runtime.handle(self, handler_name, request, suffix)
python
def handle(self, handler_name, request, suffix=''): """Handle `request` with this block's runtime.""" return self.runtime.handle(self, handler_name, request, suffix)
[ "def", "handle", "(", "self", ",", "handler_name", ",", "request", ",", "suffix", "=", "''", ")", ":", "return", "self", ".", "runtime", ".", "handle", "(", "self", ",", "handler_name", ",", "request", ",", "suffix", ")" ]
Handle `request` with this block's runtime.
[ "Handle", "request", "with", "this", "block", "s", "runtime", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L87-L89
1,918
edx/XBlock
xblock/mixins.py
RuntimeServicesMixin._combined_services
def _combined_services(cls): # pylint: disable=no-self-argument """ A dictionary that collects all _services_requested by all ancestors of this XBlock class. """ # The class declares what services it desires. To deal with subclasses, # especially mixins, properly, we have to walk up the inheritance # hierarchy, and combine all the declared services into one dictionary. combined = {} for parent in reversed(cls.mro()): combined.update(getattr(parent, "_services_requested", {})) return combined
python
def _combined_services(cls): # pylint: disable=no-self-argument """ A dictionary that collects all _services_requested by all ancestors of this XBlock class. """ # The class declares what services it desires. To deal with subclasses, # especially mixins, properly, we have to walk up the inheritance # hierarchy, and combine all the declared services into one dictionary. combined = {} for parent in reversed(cls.mro()): combined.update(getattr(parent, "_services_requested", {})) return combined
[ "def", "_combined_services", "(", "cls", ")", ":", "# pylint: disable=no-self-argument", "# The class declares what services it desires. To deal with subclasses,", "# especially mixins, properly, we have to walk up the inheritance", "# hierarchy, and combine all the declared services into one dictionary.", "combined", "=", "{", "}", "for", "parent", "in", "reversed", "(", "cls", ".", "mro", "(", ")", ")", ":", "combined", ".", "update", "(", "getattr", "(", "parent", ",", "\"_services_requested\"", ",", "{", "}", ")", ")", "return", "combined" ]
A dictionary that collects all _services_requested by all ancestors of this XBlock class.
[ "A", "dictionary", "that", "collects", "all", "_services_requested", "by", "all", "ancestors", "of", "this", "XBlock", "class", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L104-L114
1,919
edx/XBlock
xblock/mixins.py
RuntimeServicesMixin.needs
def needs(cls, *service_names): """A class decorator to indicate that an XBlock class needs particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_name] = "need" # pylint: disable=protected-access return cls_ return _decorator
python
def needs(cls, *service_names): """A class decorator to indicate that an XBlock class needs particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_name] = "need" # pylint: disable=protected-access return cls_ return _decorator
[ "def", "needs", "(", "cls", ",", "*", "service_names", ")", ":", "def", "_decorator", "(", "cls_", ")", ":", "# pylint: disable=missing-docstring", "for", "service_name", "in", "service_names", ":", "cls_", ".", "_services_requested", "[", "service_name", "]", "=", "\"need\"", "# pylint: disable=protected-access", "return", "cls_", "return", "_decorator" ]
A class decorator to indicate that an XBlock class needs particular services.
[ "A", "class", "decorator", "to", "indicate", "that", "an", "XBlock", "class", "needs", "particular", "services", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L127-L133
1,920
edx/XBlock
xblock/mixins.py
RuntimeServicesMixin.wants
def wants(cls, *service_names): """A class decorator to indicate that an XBlock class wants particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_name] = "want" # pylint: disable=protected-access return cls_ return _decorator
python
def wants(cls, *service_names): """A class decorator to indicate that an XBlock class wants particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_name] = "want" # pylint: disable=protected-access return cls_ return _decorator
[ "def", "wants", "(", "cls", ",", "*", "service_names", ")", ":", "def", "_decorator", "(", "cls_", ")", ":", "# pylint: disable=missing-docstring", "for", "service_name", "in", "service_names", ":", "cls_", ".", "_services_requested", "[", "service_name", "]", "=", "\"want\"", "# pylint: disable=protected-access", "return", "cls_", "return", "_decorator" ]
A class decorator to indicate that an XBlock class wants particular services.
[ "A", "class", "decorator", "to", "indicate", "that", "an", "XBlock", "class", "wants", "particular", "services", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L136-L142
1,921
edx/XBlock
xblock/mixins.py
HierarchyMixin.get_parent
def get_parent(self): """Return the parent block of this block, or None if there isn't one.""" if not self.has_cached_parent: if self.parent is not None: self._parent_block = self.runtime.get_block(self.parent) else: self._parent_block = None self._parent_block_id = self.parent return self._parent_block
python
def get_parent(self): """Return the parent block of this block, or None if there isn't one.""" if not self.has_cached_parent: if self.parent is not None: self._parent_block = self.runtime.get_block(self.parent) else: self._parent_block = None self._parent_block_id = self.parent return self._parent_block
[ "def", "get_parent", "(", "self", ")", ":", "if", "not", "self", ".", "has_cached_parent", ":", "if", "self", ".", "parent", "is", "not", "None", ":", "self", ".", "_parent_block", "=", "self", ".", "runtime", ".", "get_block", "(", "self", ".", "parent", ")", "else", ":", "self", ".", "_parent_block", "=", "None", "self", ".", "_parent_block_id", "=", "self", ".", "parent", "return", "self", ".", "_parent_block" ]
Return the parent block of this block, or None if there isn't one.
[ "Return", "the", "parent", "block", "of", "this", "block", "or", "None", "if", "there", "isn", "t", "one", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L373-L381
1,922
edx/XBlock
xblock/mixins.py
HierarchyMixin.get_child
def get_child(self, usage_id): """Return the child identified by ``usage_id``.""" if usage_id in self._child_cache: return self._child_cache[usage_id] child_block = self.runtime.get_block(usage_id, for_parent=self) self._child_cache[usage_id] = child_block return child_block
python
def get_child(self, usage_id): """Return the child identified by ``usage_id``.""" if usage_id in self._child_cache: return self._child_cache[usage_id] child_block = self.runtime.get_block(usage_id, for_parent=self) self._child_cache[usage_id] = child_block return child_block
[ "def", "get_child", "(", "self", ",", "usage_id", ")", ":", "if", "usage_id", "in", "self", ".", "_child_cache", ":", "return", "self", ".", "_child_cache", "[", "usage_id", "]", "child_block", "=", "self", ".", "runtime", ".", "get_block", "(", "usage_id", ",", "for_parent", "=", "self", ")", "self", ".", "_child_cache", "[", "usage_id", "]", "=", "child_block", "return", "child_block" ]
Return the child identified by ``usage_id``.
[ "Return", "the", "child", "identified", "by", "usage_id", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L388-L395
1,923
edx/XBlock
xblock/mixins.py
HierarchyMixin.get_children
def get_children(self, usage_id_filter=None): """ Return instantiated XBlocks for each of this blocks ``children``. """ if not self.has_children: return [] return [ self.get_child(usage_id) for usage_id in self.children if usage_id_filter is None or usage_id_filter(usage_id) ]
python
def get_children(self, usage_id_filter=None): """ Return instantiated XBlocks for each of this blocks ``children``. """ if not self.has_children: return [] return [ self.get_child(usage_id) for usage_id in self.children if usage_id_filter is None or usage_id_filter(usage_id) ]
[ "def", "get_children", "(", "self", ",", "usage_id_filter", "=", "None", ")", ":", "if", "not", "self", ".", "has_children", ":", "return", "[", "]", "return", "[", "self", ".", "get_child", "(", "usage_id", ")", "for", "usage_id", "in", "self", ".", "children", "if", "usage_id_filter", "is", "None", "or", "usage_id_filter", "(", "usage_id", ")", "]" ]
Return instantiated XBlocks for each of this blocks ``children``.
[ "Return", "instantiated", "XBlocks", "for", "each", "of", "this", "blocks", "children", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L397-L408
1,924
edx/XBlock
xblock/mixins.py
HierarchyMixin.add_children_to_node
def add_children_to_node(self, node): """ Add children to etree.Element `node`. """ if self.has_children: for child_id in self.children: child = self.runtime.get_block(child_id) self.runtime.add_block_as_child_node(child, node)
python
def add_children_to_node(self, node): """ Add children to etree.Element `node`. """ if self.has_children: for child_id in self.children: child = self.runtime.get_block(child_id) self.runtime.add_block_as_child_node(child, node)
[ "def", "add_children_to_node", "(", "self", ",", "node", ")", ":", "if", "self", ".", "has_children", ":", "for", "child_id", "in", "self", ".", "children", ":", "child", "=", "self", ".", "runtime", ".", "get_block", "(", "child_id", ")", "self", ".", "runtime", ".", "add_block_as_child_node", "(", "child", ",", "node", ")" ]
Add children to etree.Element `node`.
[ "Add", "children", "to", "etree", ".", "Element", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L416-L423
1,925
edx/XBlock
xblock/mixins.py
XmlSerializationMixin.parse_xml
def parse_xml(cls, node, runtime, keys, id_generator): """ Use `node` to construct a new block. Arguments: node (:class:`~xml.etree.ElementTree.Element`): The xml node to parse into an xblock. runtime (:class:`.Runtime`): The runtime to use while parsing. keys (:class:`.ScopeIds`): The keys identifying where this block will store its data. id_generator (:class:`.IdGenerator`): An object that will allow the runtime to generate correct definition and usage ids for children of this block. """ block = runtime.construct_xblock_from_class(cls, keys) # The base implementation: child nodes become child blocks. # Or fields, if they belong to the right namespace. for child in node: if child.tag is etree.Comment: continue qname = etree.QName(child) tag = qname.localname namespace = qname.namespace if namespace == XML_NAMESPACES["option"]: cls._set_field_if_present(block, tag, child.text, child.attrib) else: block.runtime.add_node_as_child(block, child, id_generator) # Attributes become fields. for name, value in node.items(): # lxml has no iteritems cls._set_field_if_present(block, name, value, {}) # Text content becomes "content", if such a field exists. if "content" in block.fields and block.fields["content"].scope == Scope.content: text = node.text if text: text = text.strip() if text: block.content = text return block
python
def parse_xml(cls, node, runtime, keys, id_generator): """ Use `node` to construct a new block. Arguments: node (:class:`~xml.etree.ElementTree.Element`): The xml node to parse into an xblock. runtime (:class:`.Runtime`): The runtime to use while parsing. keys (:class:`.ScopeIds`): The keys identifying where this block will store its data. id_generator (:class:`.IdGenerator`): An object that will allow the runtime to generate correct definition and usage ids for children of this block. """ block = runtime.construct_xblock_from_class(cls, keys) # The base implementation: child nodes become child blocks. # Or fields, if they belong to the right namespace. for child in node: if child.tag is etree.Comment: continue qname = etree.QName(child) tag = qname.localname namespace = qname.namespace if namespace == XML_NAMESPACES["option"]: cls._set_field_if_present(block, tag, child.text, child.attrib) else: block.runtime.add_node_as_child(block, child, id_generator) # Attributes become fields. for name, value in node.items(): # lxml has no iteritems cls._set_field_if_present(block, name, value, {}) # Text content becomes "content", if such a field exists. if "content" in block.fields and block.fields["content"].scope == Scope.content: text = node.text if text: text = text.strip() if text: block.content = text return block
[ "def", "parse_xml", "(", "cls", ",", "node", ",", "runtime", ",", "keys", ",", "id_generator", ")", ":", "block", "=", "runtime", ".", "construct_xblock_from_class", "(", "cls", ",", "keys", ")", "# The base implementation: child nodes become child blocks.", "# Or fields, if they belong to the right namespace.", "for", "child", "in", "node", ":", "if", "child", ".", "tag", "is", "etree", ".", "Comment", ":", "continue", "qname", "=", "etree", ".", "QName", "(", "child", ")", "tag", "=", "qname", ".", "localname", "namespace", "=", "qname", ".", "namespace", "if", "namespace", "==", "XML_NAMESPACES", "[", "\"option\"", "]", ":", "cls", ".", "_set_field_if_present", "(", "block", ",", "tag", ",", "child", ".", "text", ",", "child", ".", "attrib", ")", "else", ":", "block", ".", "runtime", ".", "add_node_as_child", "(", "block", ",", "child", ",", "id_generator", ")", "# Attributes become fields.", "for", "name", ",", "value", "in", "node", ".", "items", "(", ")", ":", "# lxml has no iteritems", "cls", ".", "_set_field_if_present", "(", "block", ",", "name", ",", "value", ",", "{", "}", ")", "# Text content becomes \"content\", if such a field exists.", "if", "\"content\"", "in", "block", ".", "fields", "and", "block", ".", "fields", "[", "\"content\"", "]", ".", "scope", "==", "Scope", ".", "content", ":", "text", "=", "node", ".", "text", "if", "text", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "text", ":", "block", ".", "content", "=", "text", "return", "block" ]
Use `node` to construct a new block. Arguments: node (:class:`~xml.etree.ElementTree.Element`): The xml node to parse into an xblock. runtime (:class:`.Runtime`): The runtime to use while parsing. keys (:class:`.ScopeIds`): The keys identifying where this block will store its data. id_generator (:class:`.IdGenerator`): An object that will allow the runtime to generate correct definition and usage ids for children of this block.
[ "Use", "node", "to", "construct", "a", "new", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L432-L477
1,926
edx/XBlock
xblock/mixins.py
XmlSerializationMixin.add_xml_to_node
def add_xml_to_node(self, node): """ For exporting, set data on `node` from ourselves. """ # pylint: disable=E1101 # Set node.tag based on our class name. node.tag = self.xml_element_name() node.set('xblock-family', self.entry_point) # Set node attributes based on our fields. for field_name, field in self.fields.items(): if field_name in ('children', 'parent', 'content'): continue if field.is_set_on(self) or field.force_export: self._add_field(node, field_name, field) # A content field becomes text content. text = self.xml_text_content() if text is not None: node.text = text
python
def add_xml_to_node(self, node): """ For exporting, set data on `node` from ourselves. """ # pylint: disable=E1101 # Set node.tag based on our class name. node.tag = self.xml_element_name() node.set('xblock-family', self.entry_point) # Set node attributes based on our fields. for field_name, field in self.fields.items(): if field_name in ('children', 'parent', 'content'): continue if field.is_set_on(self) or field.force_export: self._add_field(node, field_name, field) # A content field becomes text content. text = self.xml_text_content() if text is not None: node.text = text
[ "def", "add_xml_to_node", "(", "self", ",", "node", ")", ":", "# pylint: disable=E1101", "# Set node.tag based on our class name.", "node", ".", "tag", "=", "self", ".", "xml_element_name", "(", ")", "node", ".", "set", "(", "'xblock-family'", ",", "self", ".", "entry_point", ")", "# Set node attributes based on our fields.", "for", "field_name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", ":", "if", "field_name", "in", "(", "'children'", ",", "'parent'", ",", "'content'", ")", ":", "continue", "if", "field", ".", "is_set_on", "(", "self", ")", "or", "field", ".", "force_export", ":", "self", ".", "_add_field", "(", "node", ",", "field_name", ",", "field", ")", "# A content field becomes text content.", "text", "=", "self", ".", "xml_text_content", "(", ")", "if", "text", "is", "not", "None", ":", "node", ".", "text", "=", "text" ]
For exporting, set data on `node` from ourselves.
[ "For", "exporting", "set", "data", "on", "node", "from", "ourselves", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L479-L498
1,927
edx/XBlock
xblock/mixins.py
XmlSerializationMixin._set_field_if_present
def _set_field_if_present(cls, block, name, value, attrs): """Sets the field block.name, if block have such a field.""" if name in block.fields: value = (block.fields[name]).from_string(value) if "none" in attrs and attrs["none"] == "true": setattr(block, name, None) else: setattr(block, name, value) else: logging.warning("XBlock %s does not contain field %s", type(block), name)
python
def _set_field_if_present(cls, block, name, value, attrs): """Sets the field block.name, if block have such a field.""" if name in block.fields: value = (block.fields[name]).from_string(value) if "none" in attrs and attrs["none"] == "true": setattr(block, name, None) else: setattr(block, name, value) else: logging.warning("XBlock %s does not contain field %s", type(block), name)
[ "def", "_set_field_if_present", "(", "cls", ",", "block", ",", "name", ",", "value", ",", "attrs", ")", ":", "if", "name", "in", "block", ".", "fields", ":", "value", "=", "(", "block", ".", "fields", "[", "name", "]", ")", ".", "from_string", "(", "value", ")", "if", "\"none\"", "in", "attrs", "and", "attrs", "[", "\"none\"", "]", "==", "\"true\"", ":", "setattr", "(", "block", ",", "name", ",", "None", ")", "else", ":", "setattr", "(", "block", ",", "name", ",", "value", ")", "else", ":", "logging", ".", "warning", "(", "\"XBlock %s does not contain field %s\"", ",", "type", "(", "block", ")", ",", "name", ")" ]
Sets the field block.name, if block have such a field.
[ "Sets", "the", "field", "block", ".", "name", "if", "block", "have", "such", "a", "field", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L513-L522
1,928
edx/XBlock
xblock/mixins.py
XmlSerializationMixin._add_field
def _add_field(self, node, field_name, field): """ Add xml representation of field to node. Depending on settings, it either stores the value of field as an xml attribute or creates a separate child node. """ value = field.to_string(field.read_from(self)) text_value = "" if value is None else value # Is the field type supposed to serialize the fact that the value is None to XML? save_none_as_xml_attr = field.none_to_xml and value is None field_attrs = {"none": "true"} if save_none_as_xml_attr else {} if save_none_as_xml_attr or field.xml_node: # Field will be output to XML as an separate element. tag = etree.QName(XML_NAMESPACES["option"], field_name) elem = etree.SubElement(node, tag, field_attrs) if field.xml_node: # Only set the value if forced via xml_node; # in all other cases, the value is None. # Avoids an unnecessary XML end tag. elem.text = text_value else: # Field will be output to XML as an attribute on the node. node.set(field_name, text_value)
python
def _add_field(self, node, field_name, field): """ Add xml representation of field to node. Depending on settings, it either stores the value of field as an xml attribute or creates a separate child node. """ value = field.to_string(field.read_from(self)) text_value = "" if value is None else value # Is the field type supposed to serialize the fact that the value is None to XML? save_none_as_xml_attr = field.none_to_xml and value is None field_attrs = {"none": "true"} if save_none_as_xml_attr else {} if save_none_as_xml_attr or field.xml_node: # Field will be output to XML as an separate element. tag = etree.QName(XML_NAMESPACES["option"], field_name) elem = etree.SubElement(node, tag, field_attrs) if field.xml_node: # Only set the value if forced via xml_node; # in all other cases, the value is None. # Avoids an unnecessary XML end tag. elem.text = text_value else: # Field will be output to XML as an attribute on the node. node.set(field_name, text_value)
[ "def", "_add_field", "(", "self", ",", "node", ",", "field_name", ",", "field", ")", ":", "value", "=", "field", ".", "to_string", "(", "field", ".", "read_from", "(", "self", ")", ")", "text_value", "=", "\"\"", "if", "value", "is", "None", "else", "value", "# Is the field type supposed to serialize the fact that the value is None to XML?", "save_none_as_xml_attr", "=", "field", ".", "none_to_xml", "and", "value", "is", "None", "field_attrs", "=", "{", "\"none\"", ":", "\"true\"", "}", "if", "save_none_as_xml_attr", "else", "{", "}", "if", "save_none_as_xml_attr", "or", "field", ".", "xml_node", ":", "# Field will be output to XML as an separate element.", "tag", "=", "etree", ".", "QName", "(", "XML_NAMESPACES", "[", "\"option\"", "]", ",", "field_name", ")", "elem", "=", "etree", ".", "SubElement", "(", "node", ",", "tag", ",", "field_attrs", ")", "if", "field", ".", "xml_node", ":", "# Only set the value if forced via xml_node;", "# in all other cases, the value is None.", "# Avoids an unnecessary XML end tag.", "elem", ".", "text", "=", "text_value", "else", ":", "# Field will be output to XML as an attribute on the node.", "node", ".", "set", "(", "field_name", ",", "text_value", ")" ]
Add xml representation of field to node. Depending on settings, it either stores the value of field as an xml attribute or creates a separate child node.
[ "Add", "xml", "representation", "of", "field", "to", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L524-L549
1,929
edx/XBlock
xblock/mixins.py
ViewsMixin.supports
def supports(cls, *functionalities): """ A view decorator to indicate that an xBlock view has support for the given functionalities. Arguments: functionalities: String identifiers for the functionalities of the view. For example: "multi_device". """ def _decorator(view): """ Internal decorator that updates the given view's list of supported functionalities. """ # pylint: disable=protected-access if not hasattr(view, "_supports"): view._supports = set() for functionality in functionalities: view._supports.add(functionality) return view return _decorator
python
def supports(cls, *functionalities): """ A view decorator to indicate that an xBlock view has support for the given functionalities. Arguments: functionalities: String identifiers for the functionalities of the view. For example: "multi_device". """ def _decorator(view): """ Internal decorator that updates the given view's list of supported functionalities. """ # pylint: disable=protected-access if not hasattr(view, "_supports"): view._supports = set() for functionality in functionalities: view._supports.add(functionality) return view return _decorator
[ "def", "supports", "(", "cls", ",", "*", "functionalities", ")", ":", "def", "_decorator", "(", "view", ")", ":", "\"\"\"\n Internal decorator that updates the given view's list of supported\n functionalities.\n \"\"\"", "# pylint: disable=protected-access", "if", "not", "hasattr", "(", "view", ",", "\"_supports\"", ")", ":", "view", ".", "_supports", "=", "set", "(", ")", "for", "functionality", "in", "functionalities", ":", "view", ".", "_supports", ".", "add", "(", "functionality", ")", "return", "view", "return", "_decorator" ]
A view decorator to indicate that an xBlock view has support for the given functionalities. Arguments: functionalities: String identifiers for the functionalities of the view. For example: "multi_device".
[ "A", "view", "decorator", "to", "indicate", "that", "an", "xBlock", "view", "has", "support", "for", "the", "given", "functionalities", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L572-L592
1,930
edx/XBlock
xblock/scorable.py
ScorableXBlockMixin.rescore
def rescore(self, only_if_higher): """ Calculate a new raw score and save it to the block. If only_if_higher is True and the score didn't improve, keep the existing score. Raises a TypeError if the block cannot be scored. Raises a ValueError if the user has not yet completed the problem. May also raise other errors in self.calculate_score(). Currently unconstrained. """ _ = self.runtime.service(self, 'i18n').ugettext if not self.allows_rescore(): raise TypeError(_('Problem does not support rescoring: {}').format(self.location)) if not self.has_submitted_answer(): raise ValueError(_('Cannot rescore unanswered problem: {}').format(self.location)) new_score = self.calculate_score() self._publish_grade(new_score, only_if_higher)
python
def rescore(self, only_if_higher): """ Calculate a new raw score and save it to the block. If only_if_higher is True and the score didn't improve, keep the existing score. Raises a TypeError if the block cannot be scored. Raises a ValueError if the user has not yet completed the problem. May also raise other errors in self.calculate_score(). Currently unconstrained. """ _ = self.runtime.service(self, 'i18n').ugettext if not self.allows_rescore(): raise TypeError(_('Problem does not support rescoring: {}').format(self.location)) if not self.has_submitted_answer(): raise ValueError(_('Cannot rescore unanswered problem: {}').format(self.location)) new_score = self.calculate_score() self._publish_grade(new_score, only_if_higher)
[ "def", "rescore", "(", "self", ",", "only_if_higher", ")", ":", "_", "=", "self", ".", "runtime", ".", "service", "(", "self", ",", "'i18n'", ")", ".", "ugettext", "if", "not", "self", ".", "allows_rescore", "(", ")", ":", "raise", "TypeError", "(", "_", "(", "'Problem does not support rescoring: {}'", ")", ".", "format", "(", "self", ".", "location", ")", ")", "if", "not", "self", ".", "has_submitted_answer", "(", ")", ":", "raise", "ValueError", "(", "_", "(", "'Cannot rescore unanswered problem: {}'", ")", ".", "format", "(", "self", ".", "location", ")", ")", "new_score", "=", "self", ".", "calculate_score", "(", ")", "self", ".", "_publish_grade", "(", "new_score", ",", "only_if_higher", ")" ]
Calculate a new raw score and save it to the block. If only_if_higher is True and the score didn't improve, keep the existing score. Raises a TypeError if the block cannot be scored. Raises a ValueError if the user has not yet completed the problem. May also raise other errors in self.calculate_score(). Currently unconstrained.
[ "Calculate", "a", "new", "raw", "score", "and", "save", "it", "to", "the", "block", ".", "If", "only_if_higher", "is", "True", "and", "the", "score", "didn", "t", "improve", "keep", "the", "existing", "score", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/scorable.py#L34-L55
1,931
edx/XBlock
xblock/scorable.py
ScorableXBlockMixin._publish_grade
def _publish_grade(self, score, only_if_higher=None): """ Publish a grade to the runtime. """ grade_dict = { 'value': score.raw_earned, 'max_value': score.raw_possible, 'only_if_higher': only_if_higher, } self.runtime.publish(self, 'grade', grade_dict)
python
def _publish_grade(self, score, only_if_higher=None): """ Publish a grade to the runtime. """ grade_dict = { 'value': score.raw_earned, 'max_value': score.raw_possible, 'only_if_higher': only_if_higher, } self.runtime.publish(self, 'grade', grade_dict)
[ "def", "_publish_grade", "(", "self", ",", "score", ",", "only_if_higher", "=", "None", ")", ":", "grade_dict", "=", "{", "'value'", ":", "score", ".", "raw_earned", ",", "'max_value'", ":", "score", ".", "raw_possible", ",", "'only_if_higher'", ":", "only_if_higher", ",", "}", "self", ".", "runtime", ".", "publish", "(", "self", ",", "'grade'", ",", "grade_dict", ")" ]
Publish a grade to the runtime.
[ "Publish", "a", "grade", "to", "the", "runtime", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/scorable.py#L108-L117
1,932
edx/XBlock
xblock/fields.py
scope_key
def scope_key(instance, xblock): """Generate a unique key for a scope that can be used as a filename, in a URL, or in a KVS. Our goal is to have a pretty, human-readable 1:1 encoding. This encoding is as good as we can do. It's reversible, but not trivial to reverse. Encoding scheme: Posix allows [A-Z][a-z][0-9]._- We'd like to have a _concise_ representation for common punctuation We're okay with a _non-concise_ representation for repeated or uncommon characters We keep [A-z][a-z][0-9] as is. We encode other common punctuation as pairs of ._-. This gives a total of 3*3=9 combinations. We're pretty careful to keep this nice. Where possible, we double characters. The most common other character (' ' and ':') are encoded as _- and -_ We separate field portions with /. This gives a natural directory tree. This is nice in URLs and filenames (although not so nice in urls.py) If a field starts with punctuatation, we prefix a _. This prevents hidden files. Uncommon characters, we encode as their ordinal value, surrounded by -. For example, tilde would be -126-. If a field is not used, we call it NONE.NONE. This does not conflict with fields with the same name, since they are escaped to NONE..NONE. Sample keys: Settings scope: animationxblock..animation..d0..u0/settings__fs/NONE.NONE User summary scope: animationxblock..animation..d0..u0/uss__fs/NONE.NONE User preferences, username is Aan.!a animation/pref__fs/Aan.._33_a """ scope_key_dict = {} scope_key_dict['name'] = instance.name if instance.scope.user == UserScope.NONE or instance.scope.user == UserScope.ALL: pass elif instance.scope.user == UserScope.ONE: scope_key_dict['user'] = six.text_type(xblock.scope_ids.user_id) else: raise NotImplementedError() if instance.scope.block == BlockScope.TYPE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.block_type) elif instance.scope.block == BlockScope.USAGE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.usage_id) elif instance.scope.block == BlockScope.DEFINITION: scope_key_dict['block'] = six.text_type(xblock.scope_ids.def_id) elif instance.scope.block == BlockScope.ALL: pass else: raise NotImplementedError() replacements = itertools.product("._-", "._-") substitution_list = dict(six.moves.zip("./\\,_ +:-", ("".join(x) for x in replacements))) # Above runs in 4.7us, and generates a list of common substitutions: # {' ': '_-', '+': '-.', '-': '--', ',': '_.', '/': '._', '.': '..', ':': '-_', '\\': '.-', '_': '__'} key_list = [] def encode(char): """ Replace all non-alphanumeric characters with -n- where n is their Unicode codepoint. TODO: Test for UTF8 which is not ASCII """ if char.isalnum(): return char elif char in substitution_list: return substitution_list[char] else: return "_{}_".format(ord(char)) for item in ['block', 'name', 'user']: if item in scope_key_dict: field = scope_key_dict[item] # Prevent injection of "..", hidden files, or similar. # First part adds a prefix. Second part guarantees # continued uniqueness. if field.startswith(".") or field.startswith("_"): field = "_" + field field = "".join(encode(char) for char in field) else: field = "NONE.NONE" key_list.append(field) key = "/".join(key_list) return key
python
def scope_key(instance, xblock): """Generate a unique key for a scope that can be used as a filename, in a URL, or in a KVS. Our goal is to have a pretty, human-readable 1:1 encoding. This encoding is as good as we can do. It's reversible, but not trivial to reverse. Encoding scheme: Posix allows [A-Z][a-z][0-9]._- We'd like to have a _concise_ representation for common punctuation We're okay with a _non-concise_ representation for repeated or uncommon characters We keep [A-z][a-z][0-9] as is. We encode other common punctuation as pairs of ._-. This gives a total of 3*3=9 combinations. We're pretty careful to keep this nice. Where possible, we double characters. The most common other character (' ' and ':') are encoded as _- and -_ We separate field portions with /. This gives a natural directory tree. This is nice in URLs and filenames (although not so nice in urls.py) If a field starts with punctuatation, we prefix a _. This prevents hidden files. Uncommon characters, we encode as their ordinal value, surrounded by -. For example, tilde would be -126-. If a field is not used, we call it NONE.NONE. This does not conflict with fields with the same name, since they are escaped to NONE..NONE. Sample keys: Settings scope: animationxblock..animation..d0..u0/settings__fs/NONE.NONE User summary scope: animationxblock..animation..d0..u0/uss__fs/NONE.NONE User preferences, username is Aan.!a animation/pref__fs/Aan.._33_a """ scope_key_dict = {} scope_key_dict['name'] = instance.name if instance.scope.user == UserScope.NONE or instance.scope.user == UserScope.ALL: pass elif instance.scope.user == UserScope.ONE: scope_key_dict['user'] = six.text_type(xblock.scope_ids.user_id) else: raise NotImplementedError() if instance.scope.block == BlockScope.TYPE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.block_type) elif instance.scope.block == BlockScope.USAGE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.usage_id) elif instance.scope.block == BlockScope.DEFINITION: scope_key_dict['block'] = six.text_type(xblock.scope_ids.def_id) elif instance.scope.block == BlockScope.ALL: pass else: raise NotImplementedError() replacements = itertools.product("._-", "._-") substitution_list = dict(six.moves.zip("./\\,_ +:-", ("".join(x) for x in replacements))) # Above runs in 4.7us, and generates a list of common substitutions: # {' ': '_-', '+': '-.', '-': '--', ',': '_.', '/': '._', '.': '..', ':': '-_', '\\': '.-', '_': '__'} key_list = [] def encode(char): """ Replace all non-alphanumeric characters with -n- where n is their Unicode codepoint. TODO: Test for UTF8 which is not ASCII """ if char.isalnum(): return char elif char in substitution_list: return substitution_list[char] else: return "_{}_".format(ord(char)) for item in ['block', 'name', 'user']: if item in scope_key_dict: field = scope_key_dict[item] # Prevent injection of "..", hidden files, or similar. # First part adds a prefix. Second part guarantees # continued uniqueness. if field.startswith(".") or field.startswith("_"): field = "_" + field field = "".join(encode(char) for char in field) else: field = "NONE.NONE" key_list.append(field) key = "/".join(key_list) return key
[ "def", "scope_key", "(", "instance", ",", "xblock", ")", ":", "scope_key_dict", "=", "{", "}", "scope_key_dict", "[", "'name'", "]", "=", "instance", ".", "name", "if", "instance", ".", "scope", ".", "user", "==", "UserScope", ".", "NONE", "or", "instance", ".", "scope", ".", "user", "==", "UserScope", ".", "ALL", ":", "pass", "elif", "instance", ".", "scope", ".", "user", "==", "UserScope", ".", "ONE", ":", "scope_key_dict", "[", "'user'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "user_id", ")", "else", ":", "raise", "NotImplementedError", "(", ")", "if", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "TYPE", ":", "scope_key_dict", "[", "'block'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "block_type", ")", "elif", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "USAGE", ":", "scope_key_dict", "[", "'block'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "usage_id", ")", "elif", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "DEFINITION", ":", "scope_key_dict", "[", "'block'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "def_id", ")", "elif", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "ALL", ":", "pass", "else", ":", "raise", "NotImplementedError", "(", ")", "replacements", "=", "itertools", ".", "product", "(", "\"._-\"", ",", "\"._-\"", ")", "substitution_list", "=", "dict", "(", "six", ".", "moves", ".", "zip", "(", "\"./\\\\,_ +:-\"", ",", "(", "\"\"", ".", "join", "(", "x", ")", "for", "x", "in", "replacements", ")", ")", ")", "# Above runs in 4.7us, and generates a list of common substitutions:", "# {' ': '_-', '+': '-.', '-': '--', ',': '_.', '/': '._', '.': '..', ':': '-_', '\\\\': '.-', '_': '__'}", "key_list", "=", "[", "]", "def", "encode", "(", "char", ")", ":", "\"\"\"\n Replace all non-alphanumeric characters with -n- where n\n is their Unicode codepoint.\n TODO: Test for UTF8 which is not ASCII\n \"\"\"", "if", "char", ".", "isalnum", "(", ")", ":", "return", "char", "elif", "char", "in", "substitution_list", ":", "return", "substitution_list", "[", "char", "]", "else", ":", "return", "\"_{}_\"", ".", "format", "(", "ord", "(", "char", ")", ")", "for", "item", "in", "[", "'block'", ",", "'name'", ",", "'user'", "]", ":", "if", "item", "in", "scope_key_dict", ":", "field", "=", "scope_key_dict", "[", "item", "]", "# Prevent injection of \"..\", hidden files, or similar.", "# First part adds a prefix. Second part guarantees", "# continued uniqueness.", "if", "field", ".", "startswith", "(", "\".\"", ")", "or", "field", ".", "startswith", "(", "\"_\"", ")", ":", "field", "=", "\"_\"", "+", "field", "field", "=", "\"\"", ".", "join", "(", "encode", "(", "char", ")", "for", "char", "in", "field", ")", "else", ":", "field", "=", "\"NONE.NONE\"", "key_list", ".", "append", "(", "field", ")", "key", "=", "\"/\"", ".", "join", "(", "key_list", ")", "return", "key" ]
Generate a unique key for a scope that can be used as a filename, in a URL, or in a KVS. Our goal is to have a pretty, human-readable 1:1 encoding. This encoding is as good as we can do. It's reversible, but not trivial to reverse. Encoding scheme: Posix allows [A-Z][a-z][0-9]._- We'd like to have a _concise_ representation for common punctuation We're okay with a _non-concise_ representation for repeated or uncommon characters We keep [A-z][a-z][0-9] as is. We encode other common punctuation as pairs of ._-. This gives a total of 3*3=9 combinations. We're pretty careful to keep this nice. Where possible, we double characters. The most common other character (' ' and ':') are encoded as _- and -_ We separate field portions with /. This gives a natural directory tree. This is nice in URLs and filenames (although not so nice in urls.py) If a field starts with punctuatation, we prefix a _. This prevents hidden files. Uncommon characters, we encode as their ordinal value, surrounded by -. For example, tilde would be -126-. If a field is not used, we call it NONE.NONE. This does not conflict with fields with the same name, since they are escaped to NONE..NONE. Sample keys: Settings scope: animationxblock..animation..d0..u0/settings__fs/NONE.NONE User summary scope: animationxblock..animation..d0..u0/uss__fs/NONE.NONE User preferences, username is Aan.!a animation/pref__fs/Aan.._33_a
[ "Generate", "a", "unique", "key", "for", "a", "scope", "that", "can", "be", "used", "as", "a", "filename", "in", "a", "URL", "or", "in", "a", "KVS", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L1045-L1138
1,933
edx/XBlock
xblock/fields.py
Field.default
def default(self): """Returns the static value that this defaults to.""" if self.MUTABLE: return copy.deepcopy(self._default) else: return self._default
python
def default(self): """Returns the static value that this defaults to.""" if self.MUTABLE: return copy.deepcopy(self._default) else: return self._default
[ "def", "default", "(", "self", ")", ":", "if", "self", ".", "MUTABLE", ":", "return", "copy", ".", "deepcopy", "(", "self", ".", "_default", ")", "else", ":", "return", "self", ".", "_default" ]
Returns the static value that this defaults to.
[ "Returns", "the", "static", "value", "that", "this", "defaults", "to", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L342-L347
1,934
edx/XBlock
xblock/fields.py
Field._set_cached_value
def _set_cached_value(self, xblock, value): """Store a value in the xblock's cache, creating the cache if necessary.""" # pylint: disable=protected-access if not hasattr(xblock, '_field_data_cache'): xblock._field_data_cache = {} xblock._field_data_cache[self.name] = value
python
def _set_cached_value(self, xblock, value): """Store a value in the xblock's cache, creating the cache if necessary.""" # pylint: disable=protected-access if not hasattr(xblock, '_field_data_cache'): xblock._field_data_cache = {} xblock._field_data_cache[self.name] = value
[ "def", "_set_cached_value", "(", "self", ",", "xblock", ",", "value", ")", ":", "# pylint: disable=protected-access", "if", "not", "hasattr", "(", "xblock", ",", "'_field_data_cache'", ")", ":", "xblock", ".", "_field_data_cache", "=", "{", "}", "xblock", ".", "_field_data_cache", "[", "self", ".", "name", "]", "=", "value" ]
Store a value in the xblock's cache, creating the cache if necessary.
[ "Store", "a", "value", "in", "the", "xblock", "s", "cache", "creating", "the", "cache", "if", "necessary", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L404-L409
1,935
edx/XBlock
xblock/fields.py
Field._del_cached_value
def _del_cached_value(self, xblock): """Remove a value from the xblock's cache, if the cache exists.""" # pylint: disable=protected-access if hasattr(xblock, '_field_data_cache') and self.name in xblock._field_data_cache: del xblock._field_data_cache[self.name]
python
def _del_cached_value(self, xblock): """Remove a value from the xblock's cache, if the cache exists.""" # pylint: disable=protected-access if hasattr(xblock, '_field_data_cache') and self.name in xblock._field_data_cache: del xblock._field_data_cache[self.name]
[ "def", "_del_cached_value", "(", "self", ",", "xblock", ")", ":", "# pylint: disable=protected-access", "if", "hasattr", "(", "xblock", ",", "'_field_data_cache'", ")", "and", "self", ".", "name", "in", "xblock", ".", "_field_data_cache", ":", "del", "xblock", ".", "_field_data_cache", "[", "self", ".", "name", "]" ]
Remove a value from the xblock's cache, if the cache exists.
[ "Remove", "a", "value", "from", "the", "xblock", "s", "cache", "if", "the", "cache", "exists", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L411-L415
1,936
edx/XBlock
xblock/fields.py
Field._mark_dirty
def _mark_dirty(self, xblock, value): """Set this field to dirty on the xblock.""" # pylint: disable=protected-access # Deep copy the value being marked as dirty, so that there # is a baseline to check against when saving later if self not in xblock._dirty_fields: xblock._dirty_fields[self] = copy.deepcopy(value)
python
def _mark_dirty(self, xblock, value): """Set this field to dirty on the xblock.""" # pylint: disable=protected-access # Deep copy the value being marked as dirty, so that there # is a baseline to check against when saving later if self not in xblock._dirty_fields: xblock._dirty_fields[self] = copy.deepcopy(value)
[ "def", "_mark_dirty", "(", "self", ",", "xblock", ",", "value", ")", ":", "# pylint: disable=protected-access", "# Deep copy the value being marked as dirty, so that there", "# is a baseline to check against when saving later", "if", "self", "not", "in", "xblock", ".", "_dirty_fields", ":", "xblock", ".", "_dirty_fields", "[", "self", "]", "=", "copy", ".", "deepcopy", "(", "value", ")" ]
Set this field to dirty on the xblock.
[ "Set", "this", "field", "to", "dirty", "on", "the", "xblock", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L417-L424
1,937
edx/XBlock
xblock/fields.py
Field._check_or_enforce_type
def _check_or_enforce_type(self, value): """ Depending on whether enforce_type is enabled call self.enforce_type and return the result or call it and trigger a silent warning if the result is different or a Traceback To aid with migration, enable the warnings with: warnings.simplefilter("always", FailingEnforceTypeWarning) warnings.simplefilter("always", ModifyingEnforceTypeWarning) """ if self._enable_enforce_type: return self.enforce_type(value) try: new_value = self.enforce_type(value) except: # pylint: disable=bare-except message = "The value {!r} could not be enforced ({})".format( value, traceback.format_exc().splitlines()[-1]) warnings.warn(message, FailingEnforceTypeWarning, stacklevel=3) else: try: equal = value == new_value except TypeError: equal = False if not equal: message = "The value {!r} would be enforced to {!r}".format( value, new_value) warnings.warn(message, ModifyingEnforceTypeWarning, stacklevel=3) return value
python
def _check_or_enforce_type(self, value): """ Depending on whether enforce_type is enabled call self.enforce_type and return the result or call it and trigger a silent warning if the result is different or a Traceback To aid with migration, enable the warnings with: warnings.simplefilter("always", FailingEnforceTypeWarning) warnings.simplefilter("always", ModifyingEnforceTypeWarning) """ if self._enable_enforce_type: return self.enforce_type(value) try: new_value = self.enforce_type(value) except: # pylint: disable=bare-except message = "The value {!r} could not be enforced ({})".format( value, traceback.format_exc().splitlines()[-1]) warnings.warn(message, FailingEnforceTypeWarning, stacklevel=3) else: try: equal = value == new_value except TypeError: equal = False if not equal: message = "The value {!r} would be enforced to {!r}".format( value, new_value) warnings.warn(message, ModifyingEnforceTypeWarning, stacklevel=3) return value
[ "def", "_check_or_enforce_type", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_enable_enforce_type", ":", "return", "self", ".", "enforce_type", "(", "value", ")", "try", ":", "new_value", "=", "self", ".", "enforce_type", "(", "value", ")", "except", ":", "# pylint: disable=bare-except", "message", "=", "\"The value {!r} could not be enforced ({})\"", ".", "format", "(", "value", ",", "traceback", ".", "format_exc", "(", ")", ".", "splitlines", "(", ")", "[", "-", "1", "]", ")", "warnings", ".", "warn", "(", "message", ",", "FailingEnforceTypeWarning", ",", "stacklevel", "=", "3", ")", "else", ":", "try", ":", "equal", "=", "value", "==", "new_value", "except", "TypeError", ":", "equal", "=", "False", "if", "not", "equal", ":", "message", "=", "\"The value {!r} would be enforced to {!r}\"", ".", "format", "(", "value", ",", "new_value", ")", "warnings", ".", "warn", "(", "message", ",", "ModifyingEnforceTypeWarning", ",", "stacklevel", "=", "3", ")", "return", "value" ]
Depending on whether enforce_type is enabled call self.enforce_type and return the result or call it and trigger a silent warning if the result is different or a Traceback To aid with migration, enable the warnings with: warnings.simplefilter("always", FailingEnforceTypeWarning) warnings.simplefilter("always", ModifyingEnforceTypeWarning)
[ "Depending", "on", "whether", "enforce_type", "is", "enabled", "call", "self", ".", "enforce_type", "and", "return", "the", "result", "or", "call", "it", "and", "trigger", "a", "silent", "warning", "if", "the", "result", "is", "different", "or", "a", "Traceback" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L443-L472
1,938
edx/XBlock
xblock/fields.py
Field._calculate_unique_id
def _calculate_unique_id(self, xblock): """ Provide a default value for fields with `default=UNIQUE_ID`. Returned string is a SHA1 hex digest that is deterministically calculated for the field in its given scope. """ key = scope_key(self, xblock) return hashlib.sha1(key.encode('utf-8')).hexdigest()
python
def _calculate_unique_id(self, xblock): """ Provide a default value for fields with `default=UNIQUE_ID`. Returned string is a SHA1 hex digest that is deterministically calculated for the field in its given scope. """ key = scope_key(self, xblock) return hashlib.sha1(key.encode('utf-8')).hexdigest()
[ "def", "_calculate_unique_id", "(", "self", ",", "xblock", ")", ":", "key", "=", "scope_key", "(", "self", ",", "xblock", ")", "return", "hashlib", ".", "sha1", "(", "key", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")" ]
Provide a default value for fields with `default=UNIQUE_ID`. Returned string is a SHA1 hex digest that is deterministically calculated for the field in its given scope.
[ "Provide", "a", "default", "value", "for", "fields", "with", "default", "=", "UNIQUE_ID", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L474-L482
1,939
edx/XBlock
xblock/fields.py
Field._get_default_value_to_cache
def _get_default_value_to_cache(self, xblock): """ Perform special logic to provide a field's default value for caching. """ try: # pylint: disable=protected-access return self.from_json(xblock._field_data.default(xblock, self.name)) except KeyError: if self._default is UNIQUE_ID: return self._check_or_enforce_type(self._calculate_unique_id(xblock)) else: return self.default
python
def _get_default_value_to_cache(self, xblock): """ Perform special logic to provide a field's default value for caching. """ try: # pylint: disable=protected-access return self.from_json(xblock._field_data.default(xblock, self.name)) except KeyError: if self._default is UNIQUE_ID: return self._check_or_enforce_type(self._calculate_unique_id(xblock)) else: return self.default
[ "def", "_get_default_value_to_cache", "(", "self", ",", "xblock", ")", ":", "try", ":", "# pylint: disable=protected-access", "return", "self", ".", "from_json", "(", "xblock", ".", "_field_data", ".", "default", "(", "xblock", ",", "self", ".", "name", ")", ")", "except", "KeyError", ":", "if", "self", ".", "_default", "is", "UNIQUE_ID", ":", "return", "self", ".", "_check_or_enforce_type", "(", "self", ".", "_calculate_unique_id", "(", "xblock", ")", ")", "else", ":", "return", "self", ".", "default" ]
Perform special logic to provide a field's default value for caching.
[ "Perform", "special", "logic", "to", "provide", "a", "field", "s", "default", "value", "for", "caching", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L484-L495
1,940
edx/XBlock
xblock/fields.py
Field._warn_deprecated_outside_JSONField
def _warn_deprecated_outside_JSONField(self): # pylint: disable=invalid-name """Certain methods will be moved to JSONField. This warning marks calls when the object is not derived from that class. """ if not isinstance(self, JSONField) and not self.warned: warnings.warn( "Deprecated. JSONifiable fields should derive from JSONField ({name})".format(name=self.name), DeprecationWarning, stacklevel=3 ) self.warned = True
python
def _warn_deprecated_outside_JSONField(self): # pylint: disable=invalid-name """Certain methods will be moved to JSONField. This warning marks calls when the object is not derived from that class. """ if not isinstance(self, JSONField) and not self.warned: warnings.warn( "Deprecated. JSONifiable fields should derive from JSONField ({name})".format(name=self.name), DeprecationWarning, stacklevel=3 ) self.warned = True
[ "def", "_warn_deprecated_outside_JSONField", "(", "self", ")", ":", "# pylint: disable=invalid-name", "if", "not", "isinstance", "(", "self", ",", "JSONField", ")", "and", "not", "self", ".", "warned", ":", "warnings", ".", "warn", "(", "\"Deprecated. JSONifiable fields should derive from JSONField ({name})\"", ".", "format", "(", "name", "=", "self", ".", "name", ")", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ")", "self", ".", "warned", "=", "True" ]
Certain methods will be moved to JSONField. This warning marks calls when the object is not derived from that class.
[ "Certain", "methods", "will", "be", "moved", "to", "JSONField", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L589-L601
1,941
edx/XBlock
xblock/fields.py
Field.to_string
def to_string(self, value): """ Return a JSON serialized string representation of the value. """ self._warn_deprecated_outside_JSONField() value = json.dumps( self.to_json(value), indent=2, sort_keys=True, separators=(',', ': '), ) return value
python
def to_string(self, value): """ Return a JSON serialized string representation of the value. """ self._warn_deprecated_outside_JSONField() value = json.dumps( self.to_json(value), indent=2, sort_keys=True, separators=(',', ': '), ) return value
[ "def", "to_string", "(", "self", ",", "value", ")", ":", "self", ".", "_warn_deprecated_outside_JSONField", "(", ")", "value", "=", "json", ".", "dumps", "(", "self", ".", "to_json", "(", "value", ")", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "','", ",", "': '", ")", ",", ")", "return", "value" ]
Return a JSON serialized string representation of the value.
[ "Return", "a", "JSON", "serialized", "string", "representation", "of", "the", "value", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L624-L635
1,942
edx/XBlock
xblock/fields.py
Field.from_string
def from_string(self, serialized): """ Returns a native value from a YAML serialized string representation. Since YAML is a superset of JSON, this is the inverse of to_string.) """ self._warn_deprecated_outside_JSONField() value = yaml.safe_load(serialized) return self.enforce_type(value)
python
def from_string(self, serialized): """ Returns a native value from a YAML serialized string representation. Since YAML is a superset of JSON, this is the inverse of to_string.) """ self._warn_deprecated_outside_JSONField() value = yaml.safe_load(serialized) return self.enforce_type(value)
[ "def", "from_string", "(", "self", ",", "serialized", ")", ":", "self", ".", "_warn_deprecated_outside_JSONField", "(", ")", "value", "=", "yaml", ".", "safe_load", "(", "serialized", ")", "return", "self", ".", "enforce_type", "(", "value", ")" ]
Returns a native value from a YAML serialized string representation. Since YAML is a superset of JSON, this is the inverse of to_string.)
[ "Returns", "a", "native", "value", "from", "a", "YAML", "serialized", "string", "representation", ".", "Since", "YAML", "is", "a", "superset", "of", "JSON", "this", "is", "the", "inverse", "of", "to_string", ".", ")" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L637-L644
1,943
edx/XBlock
xblock/fields.py
Field.read_json
def read_json(self, xblock): """ Retrieve the serialized value for this field from the specified xblock """ self._warn_deprecated_outside_JSONField() return self.to_json(self.read_from(xblock))
python
def read_json(self, xblock): """ Retrieve the serialized value for this field from the specified xblock """ self._warn_deprecated_outside_JSONField() return self.to_json(self.read_from(xblock))
[ "def", "read_json", "(", "self", ",", "xblock", ")", ":", "self", ".", "_warn_deprecated_outside_JSONField", "(", ")", "return", "self", ".", "to_json", "(", "self", ".", "read_from", "(", "xblock", ")", ")" ]
Retrieve the serialized value for this field from the specified xblock
[ "Retrieve", "the", "serialized", "value", "for", "this", "field", "from", "the", "specified", "xblock" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L664-L669
1,944
edx/XBlock
xblock/fields.py
Field.is_set_on
def is_set_on(self, xblock): """ Return whether this field has a non-default value on the supplied xblock """ # pylint: disable=protected-access return self._is_dirty(xblock) or xblock._field_data.has(xblock, self.name)
python
def is_set_on(self, xblock): """ Return whether this field has a non-default value on the supplied xblock """ # pylint: disable=protected-access return self._is_dirty(xblock) or xblock._field_data.has(xblock, self.name)
[ "def", "is_set_on", "(", "self", ",", "xblock", ")", ":", "# pylint: disable=protected-access", "return", "self", ".", "_is_dirty", "(", "xblock", ")", "or", "xblock", ".", "_field_data", ".", "has", "(", "xblock", ",", "self", ".", "name", ")" ]
Return whether this field has a non-default value on the supplied xblock
[ "Return", "whether", "this", "field", "has", "a", "non", "-", "default", "value", "on", "the", "supplied", "xblock" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L683-L688
1,945
edx/XBlock
xblock/fields.py
String.to_string
def to_string(self, value): """String gets serialized and deserialized without quote marks.""" if isinstance(value, six.binary_type): value = value.decode('utf-8') return self.to_json(value)
python
def to_string(self, value): """String gets serialized and deserialized without quote marks.""" if isinstance(value, six.binary_type): value = value.decode('utf-8') return self.to_json(value)
[ "def", "to_string", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "decode", "(", "'utf-8'", ")", "return", "self", ".", "to_json", "(", "value", ")" ]
String gets serialized and deserialized without quote marks.
[ "String", "gets", "serialized", "and", "deserialized", "without", "quote", "marks", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L904-L908
1,946
edx/XBlock
xblock/fields.py
DateTime.from_json
def from_json(self, value): """ Parse the date from an ISO-formatted date string, or None. """ if value is None: return None if isinstance(value, six.binary_type): value = value.decode('utf-8') if isinstance(value, six.text_type): # Parser interprets empty string as now by default if value == "": return None try: value = dateutil.parser.parse(value) except (TypeError, ValueError): raise ValueError("Could not parse {} as a date".format(value)) if not isinstance(value, datetime.datetime): raise TypeError( "Value should be loaded from a string, a datetime object or None, not {}".format(type(value)) ) if value.tzinfo is not None: # pylint: disable=maybe-no-member return value.astimezone(pytz.utc) # pylint: disable=maybe-no-member else: return value.replace(tzinfo=pytz.utc)
python
def from_json(self, value): """ Parse the date from an ISO-formatted date string, or None. """ if value is None: return None if isinstance(value, six.binary_type): value = value.decode('utf-8') if isinstance(value, six.text_type): # Parser interprets empty string as now by default if value == "": return None try: value = dateutil.parser.parse(value) except (TypeError, ValueError): raise ValueError("Could not parse {} as a date".format(value)) if not isinstance(value, datetime.datetime): raise TypeError( "Value should be loaded from a string, a datetime object or None, not {}".format(type(value)) ) if value.tzinfo is not None: # pylint: disable=maybe-no-member return value.astimezone(pytz.utc) # pylint: disable=maybe-no-member else: return value.replace(tzinfo=pytz.utc)
[ "def", "from_json", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", ":", "# Parser interprets empty string as now by default", "if", "value", "==", "\"\"", ":", "return", "None", "try", ":", "value", "=", "dateutil", ".", "parser", ".", "parse", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "\"Could not parse {} as a date\"", ".", "format", "(", "value", ")", ")", "if", "not", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "\"Value should be loaded from a string, a datetime object or None, not {}\"", ".", "format", "(", "type", "(", "value", ")", ")", ")", "if", "value", ".", "tzinfo", "is", "not", "None", ":", "# pylint: disable=maybe-no-member", "return", "value", ".", "astimezone", "(", "pytz", ".", "utc", ")", "# pylint: disable=maybe-no-member", "else", ":", "return", "value", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")" ]
Parse the date from an ISO-formatted date string, or None.
[ "Parse", "the", "date", "from", "an", "ISO", "-", "formatted", "date", "string", "or", "None", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L954-L981
1,947
edx/XBlock
xblock/fields.py
DateTime.to_json
def to_json(self, value): """ Serialize the date as an ISO-formatted date string, or None. """ if isinstance(value, datetime.datetime): return value.strftime(self.DATETIME_FORMAT) if value is None: return None raise TypeError("Value stored must be a datetime object, not {}".format(type(value)))
python
def to_json(self, value): """ Serialize the date as an ISO-formatted date string, or None. """ if isinstance(value, datetime.datetime): return value.strftime(self.DATETIME_FORMAT) if value is None: return None raise TypeError("Value stored must be a datetime object, not {}".format(type(value)))
[ "def", "to_json", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", ".", "strftime", "(", "self", ".", "DATETIME_FORMAT", ")", "if", "value", "is", "None", ":", "return", "None", "raise", "TypeError", "(", "\"Value stored must be a datetime object, not {}\"", ".", "format", "(", "type", "(", "value", ")", ")", ")" ]
Serialize the date as an ISO-formatted date string, or None.
[ "Serialize", "the", "date", "as", "an", "ISO", "-", "formatted", "date", "string", "or", "None", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L983-L991
1,948
edx/XBlock
xblock/run_script.py
run_script
def run_script(pycode): """Run the Python in `pycode`, and return a dict of the resulting globals.""" # Fix up the whitespace in pycode. if pycode[0] == "\n": pycode = pycode[1:] pycode.rstrip() pycode = textwrap.dedent(pycode) # execute it. globs = {} six.exec_(pycode, globs, globs) # pylint: disable=W0122 return globs
python
def run_script(pycode): """Run the Python in `pycode`, and return a dict of the resulting globals.""" # Fix up the whitespace in pycode. if pycode[0] == "\n": pycode = pycode[1:] pycode.rstrip() pycode = textwrap.dedent(pycode) # execute it. globs = {} six.exec_(pycode, globs, globs) # pylint: disable=W0122 return globs
[ "def", "run_script", "(", "pycode", ")", ":", "# Fix up the whitespace in pycode.", "if", "pycode", "[", "0", "]", "==", "\"\\n\"", ":", "pycode", "=", "pycode", "[", "1", ":", "]", "pycode", ".", "rstrip", "(", ")", "pycode", "=", "textwrap", ".", "dedent", "(", "pycode", ")", "# execute it.", "globs", "=", "{", "}", "six", ".", "exec_", "(", "pycode", ",", "globs", ",", "globs", ")", "# pylint: disable=W0122", "return", "globs" ]
Run the Python in `pycode`, and return a dict of the resulting globals.
[ "Run", "the", "Python", "in", "pycode", "and", "return", "a", "dict", "of", "the", "resulting", "globals", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/run_script.py#L12-L24
1,949
edx/XBlock
xblock/core.py
SharedBlockBase.open_local_resource
def open_local_resource(cls, uri): """ Open a local resource. The container calls this method when it receives a request for a resource on a URL which was generated by Runtime.local_resource_url(). It will pass the URI from the original call to local_resource_url() back to this method. The XBlock must parse this URI and return an open file-like object for the resource. For security reasons, the default implementation will return only a very restricted set of file types, which must be located in a folder that defaults to "public". The location used for public resources can be changed on a per-XBlock basis. XBlock authors who want to override this behavior will need to take care to ensure that the method only serves legitimate public resources. At the least, the URI should be matched against a whitelist regex to ensure that you do not serve an unauthorized resource. """ if isinstance(uri, six.binary_type): uri = uri.decode('utf-8') # If no resources_dir is set, then this XBlock cannot serve local resources. if cls.resources_dir is None: raise DisallowedFileError("This XBlock is not configured to serve local resources") # Make sure the path starts with whatever public_dir is set to. if not uri.startswith(cls.public_dir + '/'): raise DisallowedFileError("Only files from %r/ are allowed: %r" % (cls.public_dir, uri)) # Disalow paths that have a '/.' component, as `/./` is a no-op and `/../` # can be used to recurse back past the entry point of this XBlock. if "/." in uri: raise DisallowedFileError("Only safe file names are allowed: %r" % uri) return pkg_resources.resource_stream(cls.__module__, os.path.join(cls.resources_dir, uri))
python
def open_local_resource(cls, uri): """ Open a local resource. The container calls this method when it receives a request for a resource on a URL which was generated by Runtime.local_resource_url(). It will pass the URI from the original call to local_resource_url() back to this method. The XBlock must parse this URI and return an open file-like object for the resource. For security reasons, the default implementation will return only a very restricted set of file types, which must be located in a folder that defaults to "public". The location used for public resources can be changed on a per-XBlock basis. XBlock authors who want to override this behavior will need to take care to ensure that the method only serves legitimate public resources. At the least, the URI should be matched against a whitelist regex to ensure that you do not serve an unauthorized resource. """ if isinstance(uri, six.binary_type): uri = uri.decode('utf-8') # If no resources_dir is set, then this XBlock cannot serve local resources. if cls.resources_dir is None: raise DisallowedFileError("This XBlock is not configured to serve local resources") # Make sure the path starts with whatever public_dir is set to. if not uri.startswith(cls.public_dir + '/'): raise DisallowedFileError("Only files from %r/ are allowed: %r" % (cls.public_dir, uri)) # Disalow paths that have a '/.' component, as `/./` is a no-op and `/../` # can be used to recurse back past the entry point of this XBlock. if "/." in uri: raise DisallowedFileError("Only safe file names are allowed: %r" % uri) return pkg_resources.resource_stream(cls.__module__, os.path.join(cls.resources_dir, uri))
[ "def", "open_local_resource", "(", "cls", ",", "uri", ")", ":", "if", "isinstance", "(", "uri", ",", "six", ".", "binary_type", ")", ":", "uri", "=", "uri", ".", "decode", "(", "'utf-8'", ")", "# If no resources_dir is set, then this XBlock cannot serve local resources.", "if", "cls", ".", "resources_dir", "is", "None", ":", "raise", "DisallowedFileError", "(", "\"This XBlock is not configured to serve local resources\"", ")", "# Make sure the path starts with whatever public_dir is set to.", "if", "not", "uri", ".", "startswith", "(", "cls", ".", "public_dir", "+", "'/'", ")", ":", "raise", "DisallowedFileError", "(", "\"Only files from %r/ are allowed: %r\"", "%", "(", "cls", ".", "public_dir", ",", "uri", ")", ")", "# Disalow paths that have a '/.' component, as `/./` is a no-op and `/../`", "# can be used to recurse back past the entry point of this XBlock.", "if", "\"/.\"", "in", "uri", ":", "raise", "DisallowedFileError", "(", "\"Only safe file names are allowed: %r\"", "%", "uri", ")", "return", "pkg_resources", ".", "resource_stream", "(", "cls", ".", "__module__", ",", "os", ".", "path", ".", "join", "(", "cls", ".", "resources_dir", ",", "uri", ")", ")" ]
Open a local resource. The container calls this method when it receives a request for a resource on a URL which was generated by Runtime.local_resource_url(). It will pass the URI from the original call to local_resource_url() back to this method. The XBlock must parse this URI and return an open file-like object for the resource. For security reasons, the default implementation will return only a very restricted set of file types, which must be located in a folder that defaults to "public". The location used for public resources can be changed on a per-XBlock basis. XBlock authors who want to override this behavior will need to take care to ensure that the method only serves legitimate public resources. At the least, the URI should be matched against a whitelist regex to ensure that you do not serve an unauthorized resource.
[ "Open", "a", "local", "resource", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L79-L115
1,950
edx/XBlock
xblock/core.py
XBlock._class_tags
def _class_tags(cls): # pylint: disable=no-self-argument """ Collect the tags from all base classes. """ class_tags = set() for base in cls.mro()[1:]: # pylint: disable=no-member class_tags.update(getattr(base, '_class_tags', set())) return class_tags
python
def _class_tags(cls): # pylint: disable=no-self-argument """ Collect the tags from all base classes. """ class_tags = set() for base in cls.mro()[1:]: # pylint: disable=no-member class_tags.update(getattr(base, '_class_tags', set())) return class_tags
[ "def", "_class_tags", "(", "cls", ")", ":", "# pylint: disable=no-self-argument", "class_tags", "=", "set", "(", ")", "for", "base", "in", "cls", ".", "mro", "(", ")", "[", "1", ":", "]", ":", "# pylint: disable=no-member", "class_tags", ".", "update", "(", "getattr", "(", "base", ",", "'_class_tags'", ",", "set", "(", ")", ")", ")", "return", "class_tags" ]
Collect the tags from all base classes.
[ "Collect", "the", "tags", "from", "all", "base", "classes", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L135-L144
1,951
edx/XBlock
xblock/core.py
XBlock.tag
def tag(tags): """Returns a function that adds the words in `tags` as class tags to this class.""" def dec(cls): """Add the words in `tags` as class tags to this class.""" # Add in this class's tags cls._class_tags.update(tags.replace(",", " ").split()) # pylint: disable=protected-access return cls return dec
python
def tag(tags): """Returns a function that adds the words in `tags` as class tags to this class.""" def dec(cls): """Add the words in `tags` as class tags to this class.""" # Add in this class's tags cls._class_tags.update(tags.replace(",", " ").split()) # pylint: disable=protected-access return cls return dec
[ "def", "tag", "(", "tags", ")", ":", "def", "dec", "(", "cls", ")", ":", "\"\"\"Add the words in `tags` as class tags to this class.\"\"\"", "# Add in this class's tags", "cls", ".", "_class_tags", ".", "update", "(", "tags", ".", "replace", "(", "\",\"", ",", "\" \"", ")", ".", "split", "(", ")", ")", "# pylint: disable=protected-access", "return", "cls", "return", "dec" ]
Returns a function that adds the words in `tags` as class tags to this class.
[ "Returns", "a", "function", "that", "adds", "the", "words", "in", "tags", "as", "class", "tags", "to", "this", "class", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L147-L154
1,952
edx/XBlock
xblock/core.py
XBlock.load_tagged_classes
def load_tagged_classes(cls, tag, fail_silently=True): """ Produce a sequence of all XBlock classes tagged with `tag`. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is diagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag. """ # Allow this method to access the `_class_tags` # pylint: disable=W0212 for name, class_ in cls.load_classes(fail_silently): if tag in class_._class_tags: yield name, class_
python
def load_tagged_classes(cls, tag, fail_silently=True): """ Produce a sequence of all XBlock classes tagged with `tag`. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is diagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag. """ # Allow this method to access the `_class_tags` # pylint: disable=W0212 for name, class_ in cls.load_classes(fail_silently): if tag in class_._class_tags: yield name, class_
[ "def", "load_tagged_classes", "(", "cls", ",", "tag", ",", "fail_silently", "=", "True", ")", ":", "# Allow this method to access the `_class_tags`", "# pylint: disable=W0212", "for", "name", ",", "class_", "in", "cls", ".", "load_classes", "(", "fail_silently", ")", ":", "if", "tag", "in", "class_", ".", "_class_tags", ":", "yield", "name", ",", "class_" ]
Produce a sequence of all XBlock classes tagged with `tag`. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is diagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag.
[ "Produce", "a", "sequence", "of", "all", "XBlock", "classes", "tagged", "with", "tag", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L157-L174
1,953
edx/XBlock
xblock/core.py
XBlock.render
def render(self, view, context=None): """Render `view` with this block's runtime and the supplied `context`""" return self.runtime.render(self, view, context)
python
def render(self, view, context=None): """Render `view` with this block's runtime and the supplied `context`""" return self.runtime.render(self, view, context)
[ "def", "render", "(", "self", ",", "view", ",", "context", "=", "None", ")", ":", "return", "self", ".", "runtime", ".", "render", "(", "self", ",", "view", ",", "context", ")" ]
Render `view` with this block's runtime and the supplied `context`
[ "Render", "view", "with", "this", "block", "s", "runtime", "and", "the", "supplied", "context" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L200-L202
1,954
edx/XBlock
xblock/core.py
XBlock.add_xml_to_node
def add_xml_to_node(self, node): """ For exporting, set data on etree.Element `node`. """ super(XBlock, self).add_xml_to_node(node) # Add children for each of our children. self.add_children_to_node(node)
python
def add_xml_to_node(self, node): """ For exporting, set data on etree.Element `node`. """ super(XBlock, self).add_xml_to_node(node) # Add children for each of our children. self.add_children_to_node(node)
[ "def", "add_xml_to_node", "(", "self", ",", "node", ")", ":", "super", "(", "XBlock", ",", "self", ")", ".", "add_xml_to_node", "(", "node", ")", "# Add children for each of our children.", "self", ".", "add_children_to_node", "(", "node", ")" ]
For exporting, set data on etree.Element `node`.
[ "For", "exporting", "set", "data", "on", "etree", ".", "Element", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L222-L228
1,955
edx/XBlock
xblock/core.py
XBlockAside.aside_for
def aside_for(cls, view_name): """ A decorator to indicate a function is the aside view for the given view_name. Aside views should have a signature like: @XBlockAside.aside_for('student_view') def student_aside(self, block, context=None): ... return Fragment(...) """ # pylint: disable=protected-access def _decorator(func): # pylint: disable=missing-docstring if not hasattr(func, '_aside_for'): func._aside_for = [] func._aside_for.append(view_name) # pylint: disable=protected-access return func return _decorator
python
def aside_for(cls, view_name): """ A decorator to indicate a function is the aside view for the given view_name. Aside views should have a signature like: @XBlockAside.aside_for('student_view') def student_aside(self, block, context=None): ... return Fragment(...) """ # pylint: disable=protected-access def _decorator(func): # pylint: disable=missing-docstring if not hasattr(func, '_aside_for'): func._aside_for = [] func._aside_for.append(view_name) # pylint: disable=protected-access return func return _decorator
[ "def", "aside_for", "(", "cls", ",", "view_name", ")", ":", "# pylint: disable=protected-access", "def", "_decorator", "(", "func", ")", ":", "# pylint: disable=missing-docstring", "if", "not", "hasattr", "(", "func", ",", "'_aside_for'", ")", ":", "func", ".", "_aside_for", "=", "[", "]", "func", ".", "_aside_for", ".", "append", "(", "view_name", ")", "# pylint: disable=protected-access", "return", "func", "return", "_decorator" ]
A decorator to indicate a function is the aside view for the given view_name. Aside views should have a signature like: @XBlockAside.aside_for('student_view') def student_aside(self, block, context=None): ... return Fragment(...)
[ "A", "decorator", "to", "indicate", "a", "function", "is", "the", "aside", "view", "for", "the", "given", "view_name", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L239-L257
1,956
edx/XBlock
xblock/core.py
XBlockAside.aside_view_declaration
def aside_view_declaration(self, view_name): """ Find and return a function object if one is an aside_view for the given view_name Aside methods declare their view provision via @XBlockAside.aside_for(view_name) This function finds those declarations for a block. Arguments: view_name (string): the name of the view requested. Returns: either the function or None """ if view_name in self._combined_asides: # pylint: disable=unsupported-membership-test return getattr(self, self._combined_asides[view_name]) # pylint: disable=unsubscriptable-object else: return None
python
def aside_view_declaration(self, view_name): """ Find and return a function object if one is an aside_view for the given view_name Aside methods declare their view provision via @XBlockAside.aside_for(view_name) This function finds those declarations for a block. Arguments: view_name (string): the name of the view requested. Returns: either the function or None """ if view_name in self._combined_asides: # pylint: disable=unsupported-membership-test return getattr(self, self._combined_asides[view_name]) # pylint: disable=unsubscriptable-object else: return None
[ "def", "aside_view_declaration", "(", "self", ",", "view_name", ")", ":", "if", "view_name", "in", "self", ".", "_combined_asides", ":", "# pylint: disable=unsupported-membership-test", "return", "getattr", "(", "self", ",", "self", ".", "_combined_asides", "[", "view_name", "]", ")", "# pylint: disable=unsubscriptable-object", "else", ":", "return", "None" ]
Find and return a function object if one is an aside_view for the given view_name Aside methods declare their view provision via @XBlockAside.aside_for(view_name) This function finds those declarations for a block. Arguments: view_name (string): the name of the view requested. Returns: either the function or None
[ "Find", "and", "return", "a", "function", "object", "if", "one", "is", "an", "aside_view", "for", "the", "given", "view_name" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L282-L298
1,957
edx/XBlock
xblock/core.py
XBlockAside.needs_serialization
def needs_serialization(self): """ Return True if the aside has any data to serialize to XML. If all of the aside's data is empty or a default value, then the aside shouldn't be serialized as XML at all. """ return any(field.is_set_on(self) for field in six.itervalues(self.fields))
python
def needs_serialization(self): """ Return True if the aside has any data to serialize to XML. If all of the aside's data is empty or a default value, then the aside shouldn't be serialized as XML at all. """ return any(field.is_set_on(self) for field in six.itervalues(self.fields))
[ "def", "needs_serialization", "(", "self", ")", ":", "return", "any", "(", "field", ".", "is_set_on", "(", "self", ")", "for", "field", "in", "six", ".", "itervalues", "(", "self", ".", "fields", ")", ")" ]
Return True if the aside has any data to serialize to XML. If all of the aside's data is empty or a default value, then the aside shouldn't be serialized as XML at all.
[ "Return", "True", "if", "the", "aside", "has", "any", "data", "to", "serialize", "to", "XML", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L300-L307
1,958
edx/XBlock
xblock/validation.py
Validation.add
def add(self, message): """ Add a new validation message to this instance. Args: message (ValidationMessage): A validation message to add to this instance's list of messages. """ if not isinstance(message, ValidationMessage): raise TypeError("Argument must of type ValidationMessage") self.messages.append(message)
python
def add(self, message): """ Add a new validation message to this instance. Args: message (ValidationMessage): A validation message to add to this instance's list of messages. """ if not isinstance(message, ValidationMessage): raise TypeError("Argument must of type ValidationMessage") self.messages.append(message)
[ "def", "add", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "ValidationMessage", ")", ":", "raise", "TypeError", "(", "\"Argument must of type ValidationMessage\"", ")", "self", ".", "messages", ".", "append", "(", "message", ")" ]
Add a new validation message to this instance. Args: message (ValidationMessage): A validation message to add to this instance's list of messages.
[ "Add", "a", "new", "validation", "message", "to", "this", "instance", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L87-L96
1,959
edx/XBlock
xblock/validation.py
Validation.add_messages
def add_messages(self, validation): """ Adds all the messages in the specified `Validation` object to this instance's messages array. Args: validation (Validation): An object containing the messages to add to this instance's messages. """ if not isinstance(validation, Validation): raise TypeError("Argument must be of type Validation") self.messages.extend(validation.messages)
python
def add_messages(self, validation): """ Adds all the messages in the specified `Validation` object to this instance's messages array. Args: validation (Validation): An object containing the messages to add to this instance's messages. """ if not isinstance(validation, Validation): raise TypeError("Argument must be of type Validation") self.messages.extend(validation.messages)
[ "def", "add_messages", "(", "self", ",", "validation", ")", ":", "if", "not", "isinstance", "(", "validation", ",", "Validation", ")", ":", "raise", "TypeError", "(", "\"Argument must be of type Validation\"", ")", "self", ".", "messages", ".", "extend", "(", "validation", ".", "messages", ")" ]
Adds all the messages in the specified `Validation` object to this instance's messages array. Args: validation (Validation): An object containing the messages to add to this instance's messages.
[ "Adds", "all", "the", "messages", "in", "the", "specified", "Validation", "object", "to", "this", "instance", "s", "messages", "array", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L98-L109
1,960
edx/XBlock
xblock/validation.py
Validation.to_json
def to_json(self): """ Convert to a json-serializable representation. Returns: dict: A dict representation that is json-serializable. """ return { "xblock_id": six.text_type(self.xblock_id), "messages": [message.to_json() for message in self.messages], "empty": self.empty }
python
def to_json(self): """ Convert to a json-serializable representation. Returns: dict: A dict representation that is json-serializable. """ return { "xblock_id": six.text_type(self.xblock_id), "messages": [message.to_json() for message in self.messages], "empty": self.empty }
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "\"xblock_id\"", ":", "six", ".", "text_type", "(", "self", ".", "xblock_id", ")", ",", "\"messages\"", ":", "[", "message", ".", "to_json", "(", ")", "for", "message", "in", "self", ".", "messages", "]", ",", "\"empty\"", ":", "self", ".", "empty", "}" ]
Convert to a json-serializable representation. Returns: dict: A dict representation that is json-serializable.
[ "Convert", "to", "a", "json", "-", "serializable", "representation", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L111-L122
1,961
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
recarray_view
def recarray_view(qimage): """Returns recarray_ view of a given 32-bit color QImage_'s memory. The result is a 2D array with a complex record dtype, offering the named fields 'r','g','b', and 'a' and corresponding long names. Thus, each color components can be accessed either via string indexing or via attribute lookup (through numpy.recarray_): For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. >>> from PyQt4.QtGui import QImage, qRgb >>> qimg = QImage(320, 240, QImage.Format_ARGB32) >>> qimg.fill(qRgb(12,34,56)) >>> >>> import qimage2ndarray >>> v = qimage2ndarray.recarray_view(qimg) >>> >>> red = v["r"] >>> red[10,10] 12 >>> pixel = v[10,10] >>> pixel["r"] 12 >>> (v.g == v["g"]).all() True >>> (v.alpha == 255).all() True :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ with 32-bit pixel type :rtype: numpy.ndarray_ with shape (height, width) and dtype :data:`bgra_dtype`""" raw = _qimage_or_filename_view(qimage) if raw.itemsize != 4: raise ValueError("For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)") return raw.view(bgra_dtype, _np.recarray)
python
def recarray_view(qimage): """Returns recarray_ view of a given 32-bit color QImage_'s memory. The result is a 2D array with a complex record dtype, offering the named fields 'r','g','b', and 'a' and corresponding long names. Thus, each color components can be accessed either via string indexing or via attribute lookup (through numpy.recarray_): For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. >>> from PyQt4.QtGui import QImage, qRgb >>> qimg = QImage(320, 240, QImage.Format_ARGB32) >>> qimg.fill(qRgb(12,34,56)) >>> >>> import qimage2ndarray >>> v = qimage2ndarray.recarray_view(qimg) >>> >>> red = v["r"] >>> red[10,10] 12 >>> pixel = v[10,10] >>> pixel["r"] 12 >>> (v.g == v["g"]).all() True >>> (v.alpha == 255).all() True :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ with 32-bit pixel type :rtype: numpy.ndarray_ with shape (height, width) and dtype :data:`bgra_dtype`""" raw = _qimage_or_filename_view(qimage) if raw.itemsize != 4: raise ValueError("For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)") return raw.view(bgra_dtype, _np.recarray)
[ "def", "recarray_view", "(", "qimage", ")", ":", "raw", "=", "_qimage_or_filename_view", "(", "qimage", ")", "if", "raw", ".", "itemsize", "!=", "4", ":", "raise", "ValueError", "(", "\"For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)\"", ")", "return", "raw", ".", "view", "(", "bgra_dtype", ",", "_np", ".", "recarray", ")" ]
Returns recarray_ view of a given 32-bit color QImage_'s memory. The result is a 2D array with a complex record dtype, offering the named fields 'r','g','b', and 'a' and corresponding long names. Thus, each color components can be accessed either via string indexing or via attribute lookup (through numpy.recarray_): For your convenience, `qimage` may also be a filename, see `Loading and Saving Images`_ in the documentation. >>> from PyQt4.QtGui import QImage, qRgb >>> qimg = QImage(320, 240, QImage.Format_ARGB32) >>> qimg.fill(qRgb(12,34,56)) >>> >>> import qimage2ndarray >>> v = qimage2ndarray.recarray_view(qimg) >>> >>> red = v["r"] >>> red[10,10] 12 >>> pixel = v[10,10] >>> pixel["r"] 12 >>> (v.g == v["g"]).all() True >>> (v.alpha == 255).all() True :param qimage: image whose memory shall be accessed via NumPy :type qimage: QImage_ with 32-bit pixel type :rtype: numpy.ndarray_ with shape (height, width) and dtype :data:`bgra_dtype`
[ "Returns", "recarray_", "view", "of", "a", "given", "32", "-", "bit", "color", "QImage_", "s", "memory", "." ]
023f3c67f90e646ce2fd80418fed85b9c7660bfc
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L137-L173
1,962
hmeine/qimage2ndarray
qimage2ndarray/__init__.py
gray2qimage
def gray2qimage(gray, normalize = False): """Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_ with a gray colormap. The first dimension represents the vertical image axis. The parameter `normalize` can be used to normalize an image's value range to 0..255: `normalize` = (nmin, nmax): scale & clip image values from nmin..nmax to 0..255 `normalize` = nmax: lets nmin default to zero, i.e. scale & clip the range 0..nmax to 0..255 `normalize` = True: scale image values to 0..255 (same as passing (gray.min(), gray.max())) If the source array `gray` contains masked values, the result will have only 255 shades of gray, and one color map entry will be used to make the corresponding pixels transparent. A full alpha channel cannot be supported with indexed images; instead, use `array2qimage` to convert into a 32-bit QImage. :param gray: image data which should be converted (copied) into a QImage_ :type gray: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_ :param normalize: normalization parameter (see above, default: no value changing) :type normalize: bool, scalar, or pair :rtype: QImage_ with RGB32 or ARGB32 format""" if _np.ndim(gray) != 2: raise ValueError("gray2QImage can only convert 2D arrays" + " (try using array2qimage)" if _np.ndim(gray) == 3 else "") h, w = gray.shape result = _qt.QImage(w, h, _qt.QImage.Format_Indexed8) if not _np.ma.is_masked(gray): for i in range(256): result.setColor(i, _qt.qRgb(i,i,i)) _qimageview(result)[:] = _normalize255(gray, normalize) else: # map gray value 1 to gray value 0, in order to make room for # transparent colormap entry: result.setColor(0, _qt.qRgb(0,0,0)) for i in range(2, 256): result.setColor(i-1, _qt.qRgb(i,i,i)) _qimageview(result)[:] = _normalize255(gray, normalize, clip = (1, 255)) - 1 result.setColor(255, 0) _qimageview(result)[gray.mask] = 255 return result
python
def gray2qimage(gray, normalize = False): """Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_ with a gray colormap. The first dimension represents the vertical image axis. The parameter `normalize` can be used to normalize an image's value range to 0..255: `normalize` = (nmin, nmax): scale & clip image values from nmin..nmax to 0..255 `normalize` = nmax: lets nmin default to zero, i.e. scale & clip the range 0..nmax to 0..255 `normalize` = True: scale image values to 0..255 (same as passing (gray.min(), gray.max())) If the source array `gray` contains masked values, the result will have only 255 shades of gray, and one color map entry will be used to make the corresponding pixels transparent. A full alpha channel cannot be supported with indexed images; instead, use `array2qimage` to convert into a 32-bit QImage. :param gray: image data which should be converted (copied) into a QImage_ :type gray: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_ :param normalize: normalization parameter (see above, default: no value changing) :type normalize: bool, scalar, or pair :rtype: QImage_ with RGB32 or ARGB32 format""" if _np.ndim(gray) != 2: raise ValueError("gray2QImage can only convert 2D arrays" + " (try using array2qimage)" if _np.ndim(gray) == 3 else "") h, w = gray.shape result = _qt.QImage(w, h, _qt.QImage.Format_Indexed8) if not _np.ma.is_masked(gray): for i in range(256): result.setColor(i, _qt.qRgb(i,i,i)) _qimageview(result)[:] = _normalize255(gray, normalize) else: # map gray value 1 to gray value 0, in order to make room for # transparent colormap entry: result.setColor(0, _qt.qRgb(0,0,0)) for i in range(2, 256): result.setColor(i-1, _qt.qRgb(i,i,i)) _qimageview(result)[:] = _normalize255(gray, normalize, clip = (1, 255)) - 1 result.setColor(255, 0) _qimageview(result)[gray.mask] = 255 return result
[ "def", "gray2qimage", "(", "gray", ",", "normalize", "=", "False", ")", ":", "if", "_np", ".", "ndim", "(", "gray", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"gray2QImage can only convert 2D arrays\"", "+", "\" (try using array2qimage)\"", "if", "_np", ".", "ndim", "(", "gray", ")", "==", "3", "else", "\"\"", ")", "h", ",", "w", "=", "gray", ".", "shape", "result", "=", "_qt", ".", "QImage", "(", "w", ",", "h", ",", "_qt", ".", "QImage", ".", "Format_Indexed8", ")", "if", "not", "_np", ".", "ma", ".", "is_masked", "(", "gray", ")", ":", "for", "i", "in", "range", "(", "256", ")", ":", "result", ".", "setColor", "(", "i", ",", "_qt", ".", "qRgb", "(", "i", ",", "i", ",", "i", ")", ")", "_qimageview", "(", "result", ")", "[", ":", "]", "=", "_normalize255", "(", "gray", ",", "normalize", ")", "else", ":", "# map gray value 1 to gray value 0, in order to make room for", "# transparent colormap entry:", "result", ".", "setColor", "(", "0", ",", "_qt", ".", "qRgb", "(", "0", ",", "0", ",", "0", ")", ")", "for", "i", "in", "range", "(", "2", ",", "256", ")", ":", "result", ".", "setColor", "(", "i", "-", "1", ",", "_qt", ".", "qRgb", "(", "i", ",", "i", ",", "i", ")", ")", "_qimageview", "(", "result", ")", "[", ":", "]", "=", "_normalize255", "(", "gray", ",", "normalize", ",", "clip", "=", "(", "1", ",", "255", ")", ")", "-", "1", "result", ".", "setColor", "(", "255", ",", "0", ")", "_qimageview", "(", "result", ")", "[", "gray", ".", "mask", "]", "=", "255", "return", "result" ]
Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_ with a gray colormap. The first dimension represents the vertical image axis. The parameter `normalize` can be used to normalize an image's value range to 0..255: `normalize` = (nmin, nmax): scale & clip image values from nmin..nmax to 0..255 `normalize` = nmax: lets nmin default to zero, i.e. scale & clip the range 0..nmax to 0..255 `normalize` = True: scale image values to 0..255 (same as passing (gray.min(), gray.max())) If the source array `gray` contains masked values, the result will have only 255 shades of gray, and one color map entry will be used to make the corresponding pixels transparent. A full alpha channel cannot be supported with indexed images; instead, use `array2qimage` to convert into a 32-bit QImage. :param gray: image data which should be converted (copied) into a QImage_ :type gray: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_ :param normalize: normalization parameter (see above, default: no value changing) :type normalize: bool, scalar, or pair :rtype: QImage_ with RGB32 or ARGB32 format
[ "Convert", "the", "2D", "numpy", "array", "gray", "into", "a", "8", "-", "bit", "indexed", "QImage_", "with", "a", "gray", "colormap", ".", "The", "first", "dimension", "represents", "the", "vertical", "image", "axis", "." ]
023f3c67f90e646ce2fd80418fed85b9c7660bfc
https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L203-L258
1,963
ampl/amplpy
amplpy/ampl.py
AMPL.getVariable
def getVariable(self, name): """ Get the variable with the corresponding name. Args: name: Name of the variable to be found. Raises: TypeError: if the specified variable does not exist. """ return lock_and_call( lambda: Variable(self._impl.getVariable(name)), self._lock )
python
def getVariable(self, name): """ Get the variable with the corresponding name. Args: name: Name of the variable to be found. Raises: TypeError: if the specified variable does not exist. """ return lock_and_call( lambda: Variable(self._impl.getVariable(name)), self._lock )
[ "def", "getVariable", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Variable", "(", "self", ".", "_impl", ".", "getVariable", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the variable with the corresponding name. Args: name: Name of the variable to be found. Raises: TypeError: if the specified variable does not exist.
[ "Get", "the", "variable", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L175-L188
1,964
ampl/amplpy
amplpy/ampl.py
AMPL.getConstraint
def getConstraint(self, name): """ Get the constraint with the corresponding name. Args: name: Name of the constraint to be found. Raises: TypeError: if the specified constraint does not exist. """ return lock_and_call( lambda: Constraint(self._impl.getConstraint(name)), self._lock )
python
def getConstraint(self, name): """ Get the constraint with the corresponding name. Args: name: Name of the constraint to be found. Raises: TypeError: if the specified constraint does not exist. """ return lock_and_call( lambda: Constraint(self._impl.getConstraint(name)), self._lock )
[ "def", "getConstraint", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Constraint", "(", "self", ".", "_impl", ".", "getConstraint", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the constraint with the corresponding name. Args: name: Name of the constraint to be found. Raises: TypeError: if the specified constraint does not exist.
[ "Get", "the", "constraint", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L190-L203
1,965
ampl/amplpy
amplpy/ampl.py
AMPL.getObjective
def getObjective(self, name): """ Get the objective with the corresponding name. Args: name: Name of the objective to be found. Raises: TypeError: if the specified objective does not exist. """ return lock_and_call( lambda: Objective(self._impl.getObjective(name)), self._lock )
python
def getObjective(self, name): """ Get the objective with the corresponding name. Args: name: Name of the objective to be found. Raises: TypeError: if the specified objective does not exist. """ return lock_and_call( lambda: Objective(self._impl.getObjective(name)), self._lock )
[ "def", "getObjective", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Objective", "(", "self", ".", "_impl", ".", "getObjective", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the objective with the corresponding name. Args: name: Name of the objective to be found. Raises: TypeError: if the specified objective does not exist.
[ "Get", "the", "objective", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L205-L218
1,966
ampl/amplpy
amplpy/ampl.py
AMPL.getSet
def getSet(self, name): """ Get the set with the corresponding name. Args: name: Name of the set to be found. Raises: TypeError: if the specified set does not exist. """ return lock_and_call( lambda: Set(self._impl.getSet(name)), self._lock )
python
def getSet(self, name): """ Get the set with the corresponding name. Args: name: Name of the set to be found. Raises: TypeError: if the specified set does not exist. """ return lock_and_call( lambda: Set(self._impl.getSet(name)), self._lock )
[ "def", "getSet", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Set", "(", "self", ".", "_impl", ".", "getSet", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the set with the corresponding name. Args: name: Name of the set to be found. Raises: TypeError: if the specified set does not exist.
[ "Get", "the", "set", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L220-L233
1,967
ampl/amplpy
amplpy/ampl.py
AMPL.getParameter
def getParameter(self, name): """ Get the parameter with the corresponding name. Args: name: Name of the parameter to be found. Raises: TypeError: if the specified parameter does not exist. """ return lock_and_call( lambda: Parameter(self._impl.getParameter(name)), self._lock )
python
def getParameter(self, name): """ Get the parameter with the corresponding name. Args: name: Name of the parameter to be found. Raises: TypeError: if the specified parameter does not exist. """ return lock_and_call( lambda: Parameter(self._impl.getParameter(name)), self._lock )
[ "def", "getParameter", "(", "self", ",", "name", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Parameter", "(", "self", ".", "_impl", ".", "getParameter", "(", "name", ")", ")", ",", "self", ".", "_lock", ")" ]
Get the parameter with the corresponding name. Args: name: Name of the parameter to be found. Raises: TypeError: if the specified parameter does not exist.
[ "Get", "the", "parameter", "with", "the", "corresponding", "name", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L235-L248
1,968
ampl/amplpy
amplpy/ampl.py
AMPL.eval
def eval(self, amplstatements, **kwargs): """ Parses AMPL code and evaluates it as a possibly empty sequence of AMPL declarations and statements. As a side effect, it invalidates all entities (as the passed statements can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access) The output of interpreting the statements is passed to the current OutputHandler (see getOutputHandler and setOutputHandler). By default, errors and warnings are printed on stdout. This behavior can be changed reassigning an ErrorHandler using setErrorHandler. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. Raises: RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running. """ if self._langext is not None: amplstatements = self._langext.translate(amplstatements, **kwargs) lock_and_call( lambda: self._impl.eval(amplstatements), self._lock ) self._errorhandler_wrapper.check()
python
def eval(self, amplstatements, **kwargs): """ Parses AMPL code and evaluates it as a possibly empty sequence of AMPL declarations and statements. As a side effect, it invalidates all entities (as the passed statements can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access) The output of interpreting the statements is passed to the current OutputHandler (see getOutputHandler and setOutputHandler). By default, errors and warnings are printed on stdout. This behavior can be changed reassigning an ErrorHandler using setErrorHandler. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. Raises: RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running. """ if self._langext is not None: amplstatements = self._langext.translate(amplstatements, **kwargs) lock_and_call( lambda: self._impl.eval(amplstatements), self._lock ) self._errorhandler_wrapper.check()
[ "def", "eval", "(", "self", ",", "amplstatements", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_langext", "is", "not", "None", ":", "amplstatements", "=", "self", ".", "_langext", ".", "translate", "(", "amplstatements", ",", "*", "*", "kwargs", ")", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "eval", "(", "amplstatements", ")", ",", "self", ".", "_lock", ")", "self", ".", "_errorhandler_wrapper", ".", "check", "(", ")" ]
Parses AMPL code and evaluates it as a possibly empty sequence of AMPL declarations and statements. As a side effect, it invalidates all entities (as the passed statements can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access) The output of interpreting the statements is passed to the current OutputHandler (see getOutputHandler and setOutputHandler). By default, errors and warnings are printed on stdout. This behavior can be changed reassigning an ErrorHandler using setErrorHandler. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. Raises: RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running.
[ "Parses", "AMPL", "code", "and", "evaluates", "it", "as", "a", "possibly", "empty", "sequence", "of", "AMPL", "declarations", "and", "statements", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L250-L282
1,969
ampl/amplpy
amplpy/ampl.py
AMPL.isBusy
def isBusy(self): """ Returns true if the underlying engine is doing an async operation. """ # return self._impl.isBusy() if self._lock.acquire(False): self._lock.release() return False else: return True
python
def isBusy(self): """ Returns true if the underlying engine is doing an async operation. """ # return self._impl.isBusy() if self._lock.acquire(False): self._lock.release() return False else: return True
[ "def", "isBusy", "(", "self", ")", ":", "# return self._impl.isBusy()", "if", "self", ".", "_lock", ".", "acquire", "(", "False", ")", ":", "self", ".", "_lock", ".", "release", "(", ")", "return", "False", "else", ":", "return", "True" ]
Returns true if the underlying engine is doing an async operation.
[ "Returns", "true", "if", "the", "underlying", "engine", "is", "doing", "an", "async", "operation", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L326-L335
1,970
ampl/amplpy
amplpy/ampl.py
AMPL.evalAsync
def evalAsync(self, amplstatements, callback, **kwargs): """ Interpret the given AMPL statement asynchronously. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. callback: Callback to be executed when the statement has been interpreted. Raises: RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running. """ if self._langext is not None: amplstatements = self._langext.translate(amplstatements, **kwargs) def async_call(): self._lock.acquire() try: self._impl.eval(amplstatements) self._errorhandler_wrapper.check() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
python
def evalAsync(self, amplstatements, callback, **kwargs): """ Interpret the given AMPL statement asynchronously. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. callback: Callback to be executed when the statement has been interpreted. Raises: RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running. """ if self._langext is not None: amplstatements = self._langext.translate(amplstatements, **kwargs) def async_call(): self._lock.acquire() try: self._impl.eval(amplstatements) self._errorhandler_wrapper.check() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
[ "def", "evalAsync", "(", "self", ",", "amplstatements", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_langext", "is", "not", "None", ":", "amplstatements", "=", "self", ".", "_langext", ".", "translate", "(", "amplstatements", ",", "*", "*", "kwargs", ")", "def", "async_call", "(", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_impl", ".", "eval", "(", "amplstatements", ")", "self", ".", "_errorhandler_wrapper", ".", "check", "(", ")", "except", "Exception", ":", "self", ".", "_lock", ".", "release", "(", ")", "raise", "else", ":", "self", ".", "_lock", ".", "release", "(", ")", "callback", ".", "run", "(", ")", "Thread", "(", "target", "=", "async_call", ")", ".", "start", "(", ")" ]
Interpret the given AMPL statement asynchronously. Args: amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter. callback: Callback to be executed when the statement has been interpreted. Raises: RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running.
[ "Interpret", "the", "given", "AMPL", "statement", "asynchronously", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L410-L440
1,971
ampl/amplpy
amplpy/ampl.py
AMPL.solveAsync
def solveAsync(self, callback): """ Solve the current model asynchronously. Args: callback: Callback to be executed when the solver is done. """ def async_call(): self._lock.acquire() try: self._impl.solve() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
python
def solveAsync(self, callback): """ Solve the current model asynchronously. Args: callback: Callback to be executed when the solver is done. """ def async_call(): self._lock.acquire() try: self._impl.solve() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
[ "def", "solveAsync", "(", "self", ",", "callback", ")", ":", "def", "async_call", "(", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_impl", ".", "solve", "(", ")", "except", "Exception", ":", "self", ".", "_lock", ".", "release", "(", ")", "raise", "else", ":", "self", ".", "_lock", ".", "release", "(", ")", "callback", ".", "run", "(", ")", "Thread", "(", "target", "=", "async_call", ")", ".", "start", "(", ")" ]
Solve the current model asynchronously. Args: callback: Callback to be executed when the solver is done.
[ "Solve", "the", "current", "model", "asynchronously", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L442-L459
1,972
ampl/amplpy
amplpy/ampl.py
AMPL.setOption
def setOption(self, name, value): """ Set an AMPL option to a specified value. Args: name: Name of the option to be set (alphanumeric without spaces). value: The value the option must be set to. Raises: InvalidArgumet: if the option name is not valid. TypeError: if the value has an invalid type. """ if isinstance(value, bool): lock_and_call( lambda: self._impl.setBoolOption(name, value), self._lock ) elif isinstance(value, int): lock_and_call( lambda: self._impl.setIntOption(name, value), self._lock ) elif isinstance(value, float): lock_and_call( lambda: self._impl.setDblOption(name, value), self._lock ) elif isinstance(value, basestring): lock_and_call( lambda: self._impl.setOption(name, value), self._lock ) else: raise TypeError
python
def setOption(self, name, value): """ Set an AMPL option to a specified value. Args: name: Name of the option to be set (alphanumeric without spaces). value: The value the option must be set to. Raises: InvalidArgumet: if the option name is not valid. TypeError: if the value has an invalid type. """ if isinstance(value, bool): lock_and_call( lambda: self._impl.setBoolOption(name, value), self._lock ) elif isinstance(value, int): lock_and_call( lambda: self._impl.setIntOption(name, value), self._lock ) elif isinstance(value, float): lock_and_call( lambda: self._impl.setDblOption(name, value), self._lock ) elif isinstance(value, basestring): lock_and_call( lambda: self._impl.setOption(name, value), self._lock ) else: raise TypeError
[ "def", "setOption", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setBoolOption", "(", "name", ",", "value", ")", ",", "self", ".", "_lock", ")", "elif", "isinstance", "(", "value", ",", "int", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setIntOption", "(", "name", ",", "value", ")", ",", "self", ".", "_lock", ")", "elif", "isinstance", "(", "value", ",", "float", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setDblOption", "(", "name", ",", "value", ")", ",", "self", ".", "_lock", ")", "elif", "isinstance", "(", "value", ",", "basestring", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setOption", "(", "name", ",", "value", ")", ",", "self", ".", "_lock", ")", "else", ":", "raise", "TypeError" ]
Set an AMPL option to a specified value. Args: name: Name of the option to be set (alphanumeric without spaces). value: The value the option must be set to. Raises: InvalidArgumet: if the option name is not valid. TypeError: if the value has an invalid type.
[ "Set", "an", "AMPL", "option", "to", "a", "specified", "value", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L500-L535
1,973
ampl/amplpy
amplpy/ampl.py
AMPL.getOption
def getOption(self, name): """ Get the current value of the specified option. If the option does not exist, returns None. Args: name: Option name. Returns: Value of the option. Raises: InvalidArgumet: if the option name is not valid. """ try: value = lock_and_call( lambda: self._impl.getOption(name).value(), self._lock ) except RuntimeError: return None else: try: return int(value) except ValueError: try: return float(value) except ValueError: return value
python
def getOption(self, name): """ Get the current value of the specified option. If the option does not exist, returns None. Args: name: Option name. Returns: Value of the option. Raises: InvalidArgumet: if the option name is not valid. """ try: value = lock_and_call( lambda: self._impl.getOption(name).value(), self._lock ) except RuntimeError: return None else: try: return int(value) except ValueError: try: return float(value) except ValueError: return value
[ "def", "getOption", "(", "self", ",", "name", ")", ":", "try", ":", "value", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getOption", "(", "name", ")", ".", "value", "(", ")", ",", "self", ".", "_lock", ")", "except", "RuntimeError", ":", "return", "None", "else", ":", "try", ":", "return", "int", "(", "value", ")", "except", "ValueError", ":", "try", ":", "return", "float", "(", "value", ")", "except", "ValueError", ":", "return", "value" ]
Get the current value of the specified option. If the option does not exist, returns None. Args: name: Option name. Returns: Value of the option. Raises: InvalidArgumet: if the option name is not valid.
[ "Get", "the", "current", "value", "of", "the", "specified", "option", ".", "If", "the", "option", "does", "not", "exist", "returns", "None", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L537-L565
1,974
ampl/amplpy
amplpy/ampl.py
AMPL.getValue
def getValue(self, scalarExpression): """ Get a scalar value from the underlying AMPL interpreter, as a double or a string. Args: scalarExpression: An AMPL expression which evaluates to a scalar value. Returns: The value of the expression. """ return lock_and_call( lambda: Utils.castVariant(self._impl.getValue(scalarExpression)), self._lock )
python
def getValue(self, scalarExpression): """ Get a scalar value from the underlying AMPL interpreter, as a double or a string. Args: scalarExpression: An AMPL expression which evaluates to a scalar value. Returns: The value of the expression. """ return lock_and_call( lambda: Utils.castVariant(self._impl.getValue(scalarExpression)), self._lock )
[ "def", "getValue", "(", "self", ",", "scalarExpression", ")", ":", "return", "lock_and_call", "(", "lambda", ":", "Utils", ".", "castVariant", "(", "self", ".", "_impl", ".", "getValue", "(", "scalarExpression", ")", ")", ",", "self", ".", "_lock", ")" ]
Get a scalar value from the underlying AMPL interpreter, as a double or a string. Args: scalarExpression: An AMPL expression which evaluates to a scalar value. Returns: The value of the expression.
[ "Get", "a", "scalar", "value", "from", "the", "underlying", "AMPL", "interpreter", "as", "a", "double", "or", "a", "string", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L612-L627
1,975
ampl/amplpy
amplpy/ampl.py
AMPL.setData
def setData(self, data, setName=None): """ Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. Args: data: The dataframe containing the data to be assigned. setName: The name of the set to which the indices values of the DataFrame are to be assigned. Raises: AMPLException: if the data assignment procedure was not successful. """ if not isinstance(data, DataFrame): if pd is not None and isinstance(data, pd.DataFrame): data = DataFrame.fromPandas(data) if setName is None: lock_and_call( lambda: self._impl.setData(data._impl), self._lock ) else: lock_and_call( lambda: self._impl.setData(data._impl, setName), self._lock )
python
def setData(self, data, setName=None): """ Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. Args: data: The dataframe containing the data to be assigned. setName: The name of the set to which the indices values of the DataFrame are to be assigned. Raises: AMPLException: if the data assignment procedure was not successful. """ if not isinstance(data, DataFrame): if pd is not None and isinstance(data, pd.DataFrame): data = DataFrame.fromPandas(data) if setName is None: lock_and_call( lambda: self._impl.setData(data._impl), self._lock ) else: lock_and_call( lambda: self._impl.setData(data._impl, setName), self._lock )
[ "def", "setData", "(", "self", ",", "data", ",", "setName", "=", "None", ")", ":", "if", "not", "isinstance", "(", "data", ",", "DataFrame", ")", ":", "if", "pd", "is", "not", "None", "and", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "data", "=", "DataFrame", ".", "fromPandas", "(", "data", ")", "if", "setName", "is", "None", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setData", "(", "data", ".", "_impl", ")", ",", "self", ".", "_lock", ")", "else", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setData", "(", "data", ".", "_impl", ",", "setName", ")", ",", "self", ".", "_lock", ")" ]
Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. Args: data: The dataframe containing the data to be assigned. setName: The name of the set to which the indices values of the DataFrame are to be assigned. Raises: AMPLException: if the data assignment procedure was not successful.
[ "Assign", "the", "data", "in", "the", "dataframe", "to", "the", "AMPL", "entities", "with", "the", "names", "corresponding", "to", "the", "column", "names", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L629-L655
1,976
ampl/amplpy
amplpy/ampl.py
AMPL.writeTable
def writeTable(self, tableName): """ Write the table corresponding to the specified name, equivalent to the AMPL statement .. code-block:: ampl write table tableName; Args: tableName: Name of the table to be written. """ lock_and_call( lambda: self._impl.writeTable(tableName), self._lock )
python
def writeTable(self, tableName): """ Write the table corresponding to the specified name, equivalent to the AMPL statement .. code-block:: ampl write table tableName; Args: tableName: Name of the table to be written. """ lock_and_call( lambda: self._impl.writeTable(tableName), self._lock )
[ "def", "writeTable", "(", "self", ",", "tableName", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "writeTable", "(", "tableName", ")", ",", "self", ".", "_lock", ")" ]
Write the table corresponding to the specified name, equivalent to the AMPL statement .. code-block:: ampl write table tableName; Args: tableName: Name of the table to be written.
[ "Write", "the", "table", "corresponding", "to", "the", "specified", "name", "equivalent", "to", "the", "AMPL", "statement" ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L674-L689
1,977
ampl/amplpy
amplpy/ampl.py
AMPL.display
def display(self, *amplExpressions): """ Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions to be evaluated. """ exprs = list(map(str, amplExpressions)) lock_and_call( lambda: self._impl.displayLst(exprs, len(exprs)), self._lock )
python
def display(self, *amplExpressions): """ Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions to be evaluated. """ exprs = list(map(str, amplExpressions)) lock_and_call( lambda: self._impl.displayLst(exprs, len(exprs)), self._lock )
[ "def", "display", "(", "self", ",", "*", "amplExpressions", ")", ":", "exprs", "=", "list", "(", "map", "(", "str", ",", "amplExpressions", ")", ")", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "displayLst", "(", "exprs", ",", "len", "(", "exprs", ")", ")", ",", "self", ".", "_lock", ")" ]
Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions to be evaluated.
[ "Writes", "on", "the", "current", "OutputHandler", "the", "outcome", "of", "the", "AMPL", "statement", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L691-L708
1,978
ampl/amplpy
amplpy/ampl.py
AMPL.setOutputHandler
def setOutputHandler(self, outputhandler): """ Sets a new output handler. Args: outputhandler: The function handling the AMPL output derived from interpreting user commands. """ class OutputHandlerInternal(amplpython.OutputHandler): def output(self, kind, msg): outputhandler.output(kind, msg) self._outputhandler = outputhandler self._outputhandler_internal = OutputHandlerInternal() lock_and_call( lambda: self._impl.setOutputHandler( self._outputhandler_internal ), self._lock )
python
def setOutputHandler(self, outputhandler): """ Sets a new output handler. Args: outputhandler: The function handling the AMPL output derived from interpreting user commands. """ class OutputHandlerInternal(amplpython.OutputHandler): def output(self, kind, msg): outputhandler.output(kind, msg) self._outputhandler = outputhandler self._outputhandler_internal = OutputHandlerInternal() lock_and_call( lambda: self._impl.setOutputHandler( self._outputhandler_internal ), self._lock )
[ "def", "setOutputHandler", "(", "self", ",", "outputhandler", ")", ":", "class", "OutputHandlerInternal", "(", "amplpython", ".", "OutputHandler", ")", ":", "def", "output", "(", "self", ",", "kind", ",", "msg", ")", ":", "outputhandler", ".", "output", "(", "kind", ",", "msg", ")", "self", ".", "_outputhandler", "=", "outputhandler", "self", ".", "_outputhandler_internal", "=", "OutputHandlerInternal", "(", ")", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setOutputHandler", "(", "self", ".", "_outputhandler_internal", ")", ",", "self", ".", "_lock", ")" ]
Sets a new output handler. Args: outputhandler: The function handling the AMPL output derived from interpreting user commands.
[ "Sets", "a", "new", "output", "handler", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L710-L729
1,979
ampl/amplpy
amplpy/ampl.py
AMPL.setErrorHandler
def setErrorHandler(self, errorhandler): """ Sets a new error handler. Args: errorhandler: The object handling AMPL errors and warnings. """ class ErrorHandlerWrapper(ErrorHandler): def __init__(self, errorhandler): self.errorhandler = errorhandler self.last_exception = None def error(self, exception): if isinstance(exception, amplpython.AMPLException): exception = AMPLException(exception) try: self.errorhandler.error(exception) except Exception as e: self.last_exception = e def warning(self, exception): if isinstance(exception, amplpython.AMPLException): exception = AMPLException(exception) try: self.errorhandler.warning(exception) except Exception as e: self.last_exception = e def check(self): if self.last_exception is not None: e, self.last_exception = self.last_exception, None raise e errorhandler_wrapper = ErrorHandlerWrapper(errorhandler) class InnerErrorHandler(amplpython.ErrorHandler): def error(self, exception): errorhandler_wrapper.error(exception) def warning(self, exception): errorhandler_wrapper.warning(exception) self._errorhandler = errorhandler self._errorhandler_inner = InnerErrorHandler() self._errorhandler_wrapper = errorhandler_wrapper lock_and_call( lambda: self._impl.setErrorHandler(self._errorhandler_inner), self._lock )
python
def setErrorHandler(self, errorhandler): """ Sets a new error handler. Args: errorhandler: The object handling AMPL errors and warnings. """ class ErrorHandlerWrapper(ErrorHandler): def __init__(self, errorhandler): self.errorhandler = errorhandler self.last_exception = None def error(self, exception): if isinstance(exception, amplpython.AMPLException): exception = AMPLException(exception) try: self.errorhandler.error(exception) except Exception as e: self.last_exception = e def warning(self, exception): if isinstance(exception, amplpython.AMPLException): exception = AMPLException(exception) try: self.errorhandler.warning(exception) except Exception as e: self.last_exception = e def check(self): if self.last_exception is not None: e, self.last_exception = self.last_exception, None raise e errorhandler_wrapper = ErrorHandlerWrapper(errorhandler) class InnerErrorHandler(amplpython.ErrorHandler): def error(self, exception): errorhandler_wrapper.error(exception) def warning(self, exception): errorhandler_wrapper.warning(exception) self._errorhandler = errorhandler self._errorhandler_inner = InnerErrorHandler() self._errorhandler_wrapper = errorhandler_wrapper lock_and_call( lambda: self._impl.setErrorHandler(self._errorhandler_inner), self._lock )
[ "def", "setErrorHandler", "(", "self", ",", "errorhandler", ")", ":", "class", "ErrorHandlerWrapper", "(", "ErrorHandler", ")", ":", "def", "__init__", "(", "self", ",", "errorhandler", ")", ":", "self", ".", "errorhandler", "=", "errorhandler", "self", ".", "last_exception", "=", "None", "def", "error", "(", "self", ",", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "amplpython", ".", "AMPLException", ")", ":", "exception", "=", "AMPLException", "(", "exception", ")", "try", ":", "self", ".", "errorhandler", ".", "error", "(", "exception", ")", "except", "Exception", "as", "e", ":", "self", ".", "last_exception", "=", "e", "def", "warning", "(", "self", ",", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "amplpython", ".", "AMPLException", ")", ":", "exception", "=", "AMPLException", "(", "exception", ")", "try", ":", "self", ".", "errorhandler", ".", "warning", "(", "exception", ")", "except", "Exception", "as", "e", ":", "self", ".", "last_exception", "=", "e", "def", "check", "(", "self", ")", ":", "if", "self", ".", "last_exception", "is", "not", "None", ":", "e", ",", "self", ".", "last_exception", "=", "self", ".", "last_exception", ",", "None", "raise", "e", "errorhandler_wrapper", "=", "ErrorHandlerWrapper", "(", "errorhandler", ")", "class", "InnerErrorHandler", "(", "amplpython", ".", "ErrorHandler", ")", ":", "def", "error", "(", "self", ",", "exception", ")", ":", "errorhandler_wrapper", ".", "error", "(", "exception", ")", "def", "warning", "(", "self", ",", "exception", ")", ":", "errorhandler_wrapper", ".", "warning", "(", "exception", ")", "self", ".", "_errorhandler", "=", "errorhandler", "self", ".", "_errorhandler_inner", "=", "InnerErrorHandler", "(", ")", "self", ".", "_errorhandler_wrapper", "=", "errorhandler_wrapper", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "setErrorHandler", "(", "self", ".", "_errorhandler_inner", ")", ",", "self", ".", "_lock", ")" ]
Sets a new error handler. Args: errorhandler: The object handling AMPL errors and warnings.
[ "Sets", "a", "new", "error", "handler", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L731-L779
1,980
ampl/amplpy
amplpy/ampl.py
AMPL.getVariables
def getVariables(self): """ Get all the variables declared. """ variables = lock_and_call( lambda: self._impl.getVariables(), self._lock ) return EntityMap(variables, Variable)
python
def getVariables(self): """ Get all the variables declared. """ variables = lock_and_call( lambda: self._impl.getVariables(), self._lock ) return EntityMap(variables, Variable)
[ "def", "getVariables", "(", "self", ")", ":", "variables", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getVariables", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "variables", ",", "Variable", ")" ]
Get all the variables declared.
[ "Get", "all", "the", "variables", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L799-L807
1,981
ampl/amplpy
amplpy/ampl.py
AMPL.getConstraints
def getConstraints(self): """ Get all the constraints declared. """ constraints = lock_and_call( lambda: self._impl.getConstraints(), self._lock ) return EntityMap(constraints, Constraint)
python
def getConstraints(self): """ Get all the constraints declared. """ constraints = lock_and_call( lambda: self._impl.getConstraints(), self._lock ) return EntityMap(constraints, Constraint)
[ "def", "getConstraints", "(", "self", ")", ":", "constraints", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getConstraints", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "constraints", ",", "Constraint", ")" ]
Get all the constraints declared.
[ "Get", "all", "the", "constraints", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L809-L817
1,982
ampl/amplpy
amplpy/ampl.py
AMPL.getObjectives
def getObjectives(self): """ Get all the objectives declared. """ objectives = lock_and_call( lambda: self._impl.getObjectives(), self._lock ) return EntityMap(objectives, Objective)
python
def getObjectives(self): """ Get all the objectives declared. """ objectives = lock_and_call( lambda: self._impl.getObjectives(), self._lock ) return EntityMap(objectives, Objective)
[ "def", "getObjectives", "(", "self", ")", ":", "objectives", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getObjectives", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "objectives", ",", "Objective", ")" ]
Get all the objectives declared.
[ "Get", "all", "the", "objectives", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L819-L827
1,983
ampl/amplpy
amplpy/ampl.py
AMPL.getSets
def getSets(self): """ Get all the sets declared. """ sets = lock_and_call( lambda: self._impl.getSets(), self._lock ) return EntityMap(sets, Set)
python
def getSets(self): """ Get all the sets declared. """ sets = lock_and_call( lambda: self._impl.getSets(), self._lock ) return EntityMap(sets, Set)
[ "def", "getSets", "(", "self", ")", ":", "sets", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getSets", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "sets", ",", "Set", ")" ]
Get all the sets declared.
[ "Get", "all", "the", "sets", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L829-L837
1,984
ampl/amplpy
amplpy/ampl.py
AMPL.getParameters
def getParameters(self): """ Get all the parameters declared. """ parameters = lock_and_call( lambda: self._impl.getParameters(), self._lock ) return EntityMap(parameters, Parameter)
python
def getParameters(self): """ Get all the parameters declared. """ parameters = lock_and_call( lambda: self._impl.getParameters(), self._lock ) return EntityMap(parameters, Parameter)
[ "def", "getParameters", "(", "self", ")", ":", "parameters", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getParameters", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "parameters", ",", "Parameter", ")" ]
Get all the parameters declared.
[ "Get", "all", "the", "parameters", "declared", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L839-L847
1,985
ampl/amplpy
amplpy/ampl.py
AMPL.getCurrentObjective
def getCurrentObjective(self): """ Get the the current objective. Returns `None` if no objective is set. """ name = self._impl.getCurrentObjectiveName() if name == '': return None else: return self.getObjective(name)
python
def getCurrentObjective(self): """ Get the the current objective. Returns `None` if no objective is set. """ name = self._impl.getCurrentObjectiveName() if name == '': return None else: return self.getObjective(name)
[ "def", "getCurrentObjective", "(", "self", ")", ":", "name", "=", "self", ".", "_impl", ".", "getCurrentObjectiveName", "(", ")", "if", "name", "==", "''", ":", "return", "None", "else", ":", "return", "self", ".", "getObjective", "(", "name", ")" ]
Get the the current objective. Returns `None` if no objective is set.
[ "Get", "the", "the", "current", "objective", ".", "Returns", "None", "if", "no", "objective", "is", "set", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L849-L857
1,986
ampl/amplpy
amplpy/ampl.py
AMPL._obj
def _obj(self): """ Get an objective. """ class Objectives(object): def __getitem__(_self, name): return self.getObjective(name) def __iter__(_self): return self.getObjectives() return Objectives()
python
def _obj(self): """ Get an objective. """ class Objectives(object): def __getitem__(_self, name): return self.getObjective(name) def __iter__(_self): return self.getObjectives() return Objectives()
[ "def", "_obj", "(", "self", ")", ":", "class", "Objectives", "(", "object", ")", ":", "def", "__getitem__", "(", "_self", ",", "name", ")", ":", "return", "self", ".", "getObjective", "(", "name", ")", "def", "__iter__", "(", "_self", ")", ":", "return", "self", ".", "getObjectives", "(", ")", "return", "Objectives", "(", ")" ]
Get an objective.
[ "Get", "an", "objective", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L891-L902
1,987
ampl/amplpy
amplpy/ampl.py
AMPL.exportData
def exportData(self, datfile): """ Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute). """ def ampl_set(name, values): def format_entry(e): return repr(e).replace(' ', '') return 'set {0} := {1};'.format( name, ','.join(format_entry(e) for e in values) ) def ampl_param(name, values): def format_entry(k, v): k = repr(k).strip('()').replace(' ', '') if v == inf: v = "Infinity" elif v == -inf: v = "-Infinity" else: v = repr(v).strip('()').replace(' ', '') return '[{0}]{1}'.format(k, v) return 'param {0} := {1};'.format( name, ''.join(format_entry(k, v) for k, v in values.items()) ) with open(datfile, 'w') as f: for name, entity in self.getSets(): values = entity.getValues().toList() print(ampl_set(name, values), file=f) for name, entity in self.getParameters(): if entity.isScalar(): print( 'param {} := {};'.format(name, entity.value()), file=f ) else: values = entity.getValues().toDict() print(ampl_param(name, values), file=f)
python
def exportData(self, datfile): """ Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute). """ def ampl_set(name, values): def format_entry(e): return repr(e).replace(' ', '') return 'set {0} := {1};'.format( name, ','.join(format_entry(e) for e in values) ) def ampl_param(name, values): def format_entry(k, v): k = repr(k).strip('()').replace(' ', '') if v == inf: v = "Infinity" elif v == -inf: v = "-Infinity" else: v = repr(v).strip('()').replace(' ', '') return '[{0}]{1}'.format(k, v) return 'param {0} := {1};'.format( name, ''.join(format_entry(k, v) for k, v in values.items()) ) with open(datfile, 'w') as f: for name, entity in self.getSets(): values = entity.getValues().toList() print(ampl_set(name, values), file=f) for name, entity in self.getParameters(): if entity.isScalar(): print( 'param {} := {};'.format(name, entity.value()), file=f ) else: values = entity.getValues().toDict() print(ampl_param(name, values), file=f)
[ "def", "exportData", "(", "self", ",", "datfile", ")", ":", "def", "ampl_set", "(", "name", ",", "values", ")", ":", "def", "format_entry", "(", "e", ")", ":", "return", "repr", "(", "e", ")", ".", "replace", "(", "' '", ",", "''", ")", "return", "'set {0} := {1};'", ".", "format", "(", "name", ",", "','", ".", "join", "(", "format_entry", "(", "e", ")", "for", "e", "in", "values", ")", ")", "def", "ampl_param", "(", "name", ",", "values", ")", ":", "def", "format_entry", "(", "k", ",", "v", ")", ":", "k", "=", "repr", "(", "k", ")", ".", "strip", "(", "'()'", ")", ".", "replace", "(", "' '", ",", "''", ")", "if", "v", "==", "inf", ":", "v", "=", "\"Infinity\"", "elif", "v", "==", "-", "inf", ":", "v", "=", "\"-Infinity\"", "else", ":", "v", "=", "repr", "(", "v", ")", ".", "strip", "(", "'()'", ")", ".", "replace", "(", "' '", ",", "''", ")", "return", "'[{0}]{1}'", ".", "format", "(", "k", ",", "v", ")", "return", "'param {0} := {1};'", ".", "format", "(", "name", ",", "''", ".", "join", "(", "format_entry", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "values", ".", "items", "(", ")", ")", ")", "with", "open", "(", "datfile", ",", "'w'", ")", "as", "f", ":", "for", "name", ",", "entity", "in", "self", ".", "getSets", "(", ")", ":", "values", "=", "entity", ".", "getValues", "(", ")", ".", "toList", "(", ")", "print", "(", "ampl_set", "(", "name", ",", "values", ")", ",", "file", "=", "f", ")", "for", "name", ",", "entity", "in", "self", ".", "getParameters", "(", ")", ":", "if", "entity", ".", "isScalar", "(", ")", ":", "print", "(", "'param {} := {};'", ".", "format", "(", "name", ",", "entity", ".", "value", "(", ")", ")", ",", "file", "=", "f", ")", "else", ":", "values", "=", "entity", ".", "getValues", "(", ")", ".", "toDict", "(", ")", "print", "(", "ampl_param", "(", "name", ",", "values", ")", ",", "file", "=", "f", ")" ]
Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute).
[ "Create", "a", ".", "dat", "file", "with", "the", "data", "that", "has", "been", "loaded", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L959-L1003
1,988
ampl/amplpy
amplpy/ampl.py
AMPL.importGurobiSolution
def importGurobiSolution(self, grbmodel): """ Import the solution from a gurobipy.Model object. Args: grbmodel: A :class:`gurobipy.Model` object with the model solved. """ self.eval(''.join( 'let {} := {};'.format(var.VarName, var.X) for var in grbmodel.getVars() if '$' not in var.VarName ))
python
def importGurobiSolution(self, grbmodel): """ Import the solution from a gurobipy.Model object. Args: grbmodel: A :class:`gurobipy.Model` object with the model solved. """ self.eval(''.join( 'let {} := {};'.format(var.VarName, var.X) for var in grbmodel.getVars() if '$' not in var.VarName ))
[ "def", "importGurobiSolution", "(", "self", ",", "grbmodel", ")", ":", "self", ".", "eval", "(", "''", ".", "join", "(", "'let {} := {};'", ".", "format", "(", "var", ".", "VarName", ",", "var", ".", "X", ")", "for", "var", "in", "grbmodel", ".", "getVars", "(", ")", "if", "'$'", "not", "in", "var", ".", "VarName", ")", ")" ]
Import the solution from a gurobipy.Model object. Args: grbmodel: A :class:`gurobipy.Model` object with the model solved.
[ "Import", "the", "solution", "from", "a", "gurobipy", ".", "Model", "object", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1070-L1081
1,989
ampl/amplpy
amplpy/ampl.py
AMPL._startRecording
def _startRecording(self, filename): """ Start recording the session to a file for debug purposes. """ self.setOption('_log_file_name', filename) self.setOption('_log_input_only', True) self.setOption('_log', True)
python
def _startRecording(self, filename): """ Start recording the session to a file for debug purposes. """ self.setOption('_log_file_name', filename) self.setOption('_log_input_only', True) self.setOption('_log', True)
[ "def", "_startRecording", "(", "self", ",", "filename", ")", ":", "self", ".", "setOption", "(", "'_log_file_name'", ",", "filename", ")", "self", ".", "setOption", "(", "'_log_input_only'", ",", "True", ")", "self", ".", "setOption", "(", "'_log'", ",", "True", ")" ]
Start recording the session to a file for debug purposes.
[ "Start", "recording", "the", "session", "to", "a", "file", "for", "debug", "purposes", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1084-L1090
1,990
ampl/amplpy
amplpy/ampl.py
AMPL._loadSession
def _loadSession(self, filename): """ Load a recorded session. """ try: self.eval(open(filename).read()) except RuntimeError as e: print(e)
python
def _loadSession(self, filename): """ Load a recorded session. """ try: self.eval(open(filename).read()) except RuntimeError as e: print(e)
[ "def", "_loadSession", "(", "self", ",", "filename", ")", ":", "try", ":", "self", ".", "eval", "(", "open", "(", "filename", ")", ".", "read", "(", ")", ")", "except", "RuntimeError", "as", "e", ":", "print", "(", "e", ")" ]
Load a recorded session.
[ "Load", "a", "recorded", "session", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1098-L1105
1,991
ampl/amplpy
setup.py
ls_dir
def ls_dir(base_dir): """List files recursively.""" return [ os.path.join(dirpath.replace(base_dir, '', 1), f) for (dirpath, dirnames, files) in os.walk(base_dir) for f in files ]
python
def ls_dir(base_dir): """List files recursively.""" return [ os.path.join(dirpath.replace(base_dir, '', 1), f) for (dirpath, dirnames, files) in os.walk(base_dir) for f in files ]
[ "def", "ls_dir", "(", "base_dir", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "dirpath", ".", "replace", "(", "base_dir", ",", "''", ",", "1", ")", ",", "f", ")", "for", "(", "dirpath", ",", "dirnames", ",", "files", ")", "in", "os", ".", "walk", "(", "base_dir", ")", "for", "f", "in", "files", "]" ]
List files recursively.
[ "List", "files", "recursively", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/setup.py#L45-L51
1,992
ampl/amplpy
amplpy/entity.py
Entity.get
def get(self, *index): """ Get the instance with the specified index. Returns: The corresponding instance. """ assert self.wrapFunction is not None if len(index) == 1 and isinstance(index[0], (tuple, list)): index = index[0] if len(index) == 0: return self.wrapFunction(self._impl.get()) else: return self.wrapFunction(self._impl.get(Tuple(index)._impl))
python
def get(self, *index): """ Get the instance with the specified index. Returns: The corresponding instance. """ assert self.wrapFunction is not None if len(index) == 1 and isinstance(index[0], (tuple, list)): index = index[0] if len(index) == 0: return self.wrapFunction(self._impl.get()) else: return self.wrapFunction(self._impl.get(Tuple(index)._impl))
[ "def", "get", "(", "self", ",", "*", "index", ")", ":", "assert", "self", ".", "wrapFunction", "is", "not", "None", "if", "len", "(", "index", ")", "==", "1", "and", "isinstance", "(", "index", "[", "0", "]", ",", "(", "tuple", ",", "list", ")", ")", ":", "index", "=", "index", "[", "0", "]", "if", "len", "(", "index", ")", "==", "0", ":", "return", "self", ".", "wrapFunction", "(", "self", ".", "_impl", ".", "get", "(", ")", ")", "else", ":", "return", "self", ".", "wrapFunction", "(", "self", ".", "_impl", ".", "get", "(", "Tuple", "(", "index", ")", ".", "_impl", ")", ")" ]
Get the instance with the specified index. Returns: The corresponding instance.
[ "Get", "the", "instance", "with", "the", "specified", "index", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L60-L73
1,993
ampl/amplpy
amplpy/entity.py
Entity.find
def find(self, *index): """ Searches the current entity for an instance with the specified index. Returns: The wanted instance if found, otherwise it returns `None`. """ assert self.wrapFunction is not None if len(index) == 1 and isinstance(index[0], (tuple, list)): index = index[0] it = self._impl.find(Tuple(index)._impl) if it == self._impl.end(): return None else: return self.wrapFunction(it)
python
def find(self, *index): """ Searches the current entity for an instance with the specified index. Returns: The wanted instance if found, otherwise it returns `None`. """ assert self.wrapFunction is not None if len(index) == 1 and isinstance(index[0], (tuple, list)): index = index[0] it = self._impl.find(Tuple(index)._impl) if it == self._impl.end(): return None else: return self.wrapFunction(it)
[ "def", "find", "(", "self", ",", "*", "index", ")", ":", "assert", "self", ".", "wrapFunction", "is", "not", "None", "if", "len", "(", "index", ")", "==", "1", "and", "isinstance", "(", "index", "[", "0", "]", ",", "(", "tuple", ",", "list", ")", ")", ":", "index", "=", "index", "[", "0", "]", "it", "=", "self", ".", "_impl", ".", "find", "(", "Tuple", "(", "index", ")", ".", "_impl", ")", "if", "it", "==", "self", ".", "_impl", ".", "end", "(", ")", ":", "return", "None", "else", ":", "return", "self", ".", "wrapFunction", "(", "it", ")" ]
Searches the current entity for an instance with the specified index. Returns: The wanted instance if found, otherwise it returns `None`.
[ "Searches", "the", "current", "entity", "for", "an", "instance", "with", "the", "specified", "index", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L75-L89
1,994
ampl/amplpy
amplpy/dataframe.py
DataFrame.addRow
def addRow(self, *value): """ Add a row to the DataFrame. The size of the tuple must be equal to the total number of columns in the dataframe. Args: value: A single argument with a tuple containing all the values for the row to be added, or multiple arguments with the values for each column. """ if len(value) == 1 and isinstance(value[0], (tuple, list)): value = value[0] assert len(value) == self.getNumCols() self._impl.addRow(Tuple(value)._impl)
python
def addRow(self, *value): """ Add a row to the DataFrame. The size of the tuple must be equal to the total number of columns in the dataframe. Args: value: A single argument with a tuple containing all the values for the row to be added, or multiple arguments with the values for each column. """ if len(value) == 1 and isinstance(value[0], (tuple, list)): value = value[0] assert len(value) == self.getNumCols() self._impl.addRow(Tuple(value)._impl)
[ "def", "addRow", "(", "self", ",", "*", "value", ")", ":", "if", "len", "(", "value", ")", "==", "1", "and", "isinstance", "(", "value", "[", "0", "]", ",", "(", "tuple", ",", "list", ")", ")", ":", "value", "=", "value", "[", "0", "]", "assert", "len", "(", "value", ")", "==", "self", ".", "getNumCols", "(", ")", "self", ".", "_impl", ".", "addRow", "(", "Tuple", "(", "value", ")", ".", "_impl", ")" ]
Add a row to the DataFrame. The size of the tuple must be equal to the total number of columns in the dataframe. Args: value: A single argument with a tuple containing all the values for the row to be added, or multiple arguments with the values for each column.
[ "Add", "a", "row", "to", "the", "DataFrame", ".", "The", "size", "of", "the", "tuple", "must", "be", "equal", "to", "the", "total", "number", "of", "columns", "in", "the", "dataframe", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L155-L168
1,995
ampl/amplpy
amplpy/dataframe.py
DataFrame.addColumn
def addColumn(self, header, values=[]): """ Add a new column with the corresponding header and values to the dataframe. Args: header: The name of the new column. values: A list of size :func:`~amplpy.DataFrame.getNumRows` with all the values of the new column. """ if len(values) == 0: self._impl.addColumn(header) else: assert len(values) == self.getNumRows() if any(isinstance(value, basestring) for value in values): values = list(map(str, values)) self._impl.addColumnStr(header, values) elif all(isinstance(value, Real) for value in values): values = list(map(float, values)) self._impl.addColumnDbl(header, values) else: raise NotImplementedError
python
def addColumn(self, header, values=[]): """ Add a new column with the corresponding header and values to the dataframe. Args: header: The name of the new column. values: A list of size :func:`~amplpy.DataFrame.getNumRows` with all the values of the new column. """ if len(values) == 0: self._impl.addColumn(header) else: assert len(values) == self.getNumRows() if any(isinstance(value, basestring) for value in values): values = list(map(str, values)) self._impl.addColumnStr(header, values) elif all(isinstance(value, Real) for value in values): values = list(map(float, values)) self._impl.addColumnDbl(header, values) else: raise NotImplementedError
[ "def", "addColumn", "(", "self", ",", "header", ",", "values", "=", "[", "]", ")", ":", "if", "len", "(", "values", ")", "==", "0", ":", "self", ".", "_impl", ".", "addColumn", "(", "header", ")", "else", ":", "assert", "len", "(", "values", ")", "==", "self", ".", "getNumRows", "(", ")", "if", "any", "(", "isinstance", "(", "value", ",", "basestring", ")", "for", "value", "in", "values", ")", ":", "values", "=", "list", "(", "map", "(", "str", ",", "values", ")", ")", "self", ".", "_impl", ".", "addColumnStr", "(", "header", ",", "values", ")", "elif", "all", "(", "isinstance", "(", "value", ",", "Real", ")", "for", "value", "in", "values", ")", ":", "values", "=", "list", "(", "map", "(", "float", ",", "values", ")", ")", "self", ".", "_impl", ".", "addColumnDbl", "(", "header", ",", "values", ")", "else", ":", "raise", "NotImplementedError" ]
Add a new column with the corresponding header and values to the dataframe. Args: header: The name of the new column. values: A list of size :func:`~amplpy.DataFrame.getNumRows` with all the values of the new column.
[ "Add", "a", "new", "column", "with", "the", "corresponding", "header", "and", "values", "to", "the", "dataframe", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L170-L192
1,996
ampl/amplpy
amplpy/dataframe.py
DataFrame.setColumn
def setColumn(self, header, values): """ Set the values of a column. Args: header: The header of the column to be set. values: The values to set. """ if any(isinstance(value, basestring) for value in values): values = list(map(str, values)) self._impl.setColumnStr(header, values, len(values)) elif all(isinstance(value, Real) for value in values): values = list(map(float, values)) self._impl.setColumnDbl(header, values, len(values)) else: print(values) raise NotImplementedError
python
def setColumn(self, header, values): """ Set the values of a column. Args: header: The header of the column to be set. values: The values to set. """ if any(isinstance(value, basestring) for value in values): values = list(map(str, values)) self._impl.setColumnStr(header, values, len(values)) elif all(isinstance(value, Real) for value in values): values = list(map(float, values)) self._impl.setColumnDbl(header, values, len(values)) else: print(values) raise NotImplementedError
[ "def", "setColumn", "(", "self", ",", "header", ",", "values", ")", ":", "if", "any", "(", "isinstance", "(", "value", ",", "basestring", ")", "for", "value", "in", "values", ")", ":", "values", "=", "list", "(", "map", "(", "str", ",", "values", ")", ")", "self", ".", "_impl", ".", "setColumnStr", "(", "header", ",", "values", ",", "len", "(", "values", ")", ")", "elif", "all", "(", "isinstance", "(", "value", ",", "Real", ")", "for", "value", "in", "values", ")", ":", "values", "=", "list", "(", "map", "(", "float", ",", "values", ")", ")", "self", ".", "_impl", ".", "setColumnDbl", "(", "header", ",", "values", ",", "len", "(", "values", ")", ")", "else", ":", "print", "(", "values", ")", "raise", "NotImplementedError" ]
Set the values of a column. Args: header: The header of the column to be set. values: The values to set.
[ "Set", "the", "values", "of", "a", "column", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L203-L220
1,997
ampl/amplpy
amplpy/dataframe.py
DataFrame.getRow
def getRow(self, key): """ Get a row by value of the indexing columns. If the index is not specified, gets the only row of a dataframe with no indexing columns. Args: key: Tuple representing the index of the desired row. Returns: The row. """ return Row(self._impl.getRow(Tuple(key)._impl))
python
def getRow(self, key): """ Get a row by value of the indexing columns. If the index is not specified, gets the only row of a dataframe with no indexing columns. Args: key: Tuple representing the index of the desired row. Returns: The row. """ return Row(self._impl.getRow(Tuple(key)._impl))
[ "def", "getRow", "(", "self", ",", "key", ")", ":", "return", "Row", "(", "self", ".", "_impl", ".", "getRow", "(", "Tuple", "(", "key", ")", ".", "_impl", ")", ")" ]
Get a row by value of the indexing columns. If the index is not specified, gets the only row of a dataframe with no indexing columns. Args: key: Tuple representing the index of the desired row. Returns: The row.
[ "Get", "a", "row", "by", "value", "of", "the", "indexing", "columns", ".", "If", "the", "index", "is", "not", "specified", "gets", "the", "only", "row", "of", "a", "dataframe", "with", "no", "indexing", "columns", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L222-L233
1,998
ampl/amplpy
amplpy/dataframe.py
DataFrame.getRowByIndex
def getRowByIndex(self, index): """ Get row by numeric index. Args: index: Zero-based index of the row to get. Returns: The corresponding row. """ assert isinstance(index, int) return Row(self._impl.getRowByIndex(index))
python
def getRowByIndex(self, index): """ Get row by numeric index. Args: index: Zero-based index of the row to get. Returns: The corresponding row. """ assert isinstance(index, int) return Row(self._impl.getRowByIndex(index))
[ "def", "getRowByIndex", "(", "self", ",", "index", ")", ":", "assert", "isinstance", "(", "index", ",", "int", ")", "return", "Row", "(", "self", ".", "_impl", ".", "getRowByIndex", "(", "index", ")", ")" ]
Get row by numeric index. Args: index: Zero-based index of the row to get. Returns: The corresponding row.
[ "Get", "row", "by", "numeric", "index", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L235-L246
1,999
ampl/amplpy
amplpy/dataframe.py
DataFrame.getHeaders
def getHeaders(self): """ Get the headers of this DataFrame. Returns: The headers of this DataFrame. """ headers = self._impl.getHeaders() return tuple( headers.getIndex(i) for i in range(self._impl.getNumCols()) )
python
def getHeaders(self): """ Get the headers of this DataFrame. Returns: The headers of this DataFrame. """ headers = self._impl.getHeaders() return tuple( headers.getIndex(i) for i in range(self._impl.getNumCols()) )
[ "def", "getHeaders", "(", "self", ")", ":", "headers", "=", "self", ".", "_impl", ".", "getHeaders", "(", ")", "return", "tuple", "(", "headers", ".", "getIndex", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "_impl", ".", "getNumCols", "(", ")", ")", ")" ]
Get the headers of this DataFrame. Returns: The headers of this DataFrame.
[ "Get", "the", "headers", "of", "this", "DataFrame", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L248-L258