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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.relative_path
def relative_path(self, absolute_path, output_filename): """Rewrite paths relative to the output stylesheet path""" absolute_path = posixpath.join(settings.PIPELINE_ROOT, absolute_path) output_path = posixpath.join(settings.PIPELINE_ROOT, posixpath.dirname(output_filename)) return relpath(absolute_path, output_path)
python
def relative_path(self, absolute_path, output_filename): """Rewrite paths relative to the output stylesheet path""" absolute_path = posixpath.join(settings.PIPELINE_ROOT, absolute_path) output_path = posixpath.join(settings.PIPELINE_ROOT, posixpath.dirname(output_filename)) return relpath(absolute_path, output_path)
[ "def", "relative_path", "(", "self", ",", "absolute_path", ",", "output_filename", ")", ":", "absolute_path", "=", "posixpath", ".", "join", "(", "settings", ".", "PIPELINE_ROOT", ",", "absolute_path", ")", "output_path", "=", "posixpath", ".", "join", "(", "s...
Rewrite paths relative to the output stylesheet path
[ "Rewrite", "paths", "relative", "to", "the", "output", "stylesheet", "path" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L208-L212
train
208,100
jazzband/django-pipeline
pipeline/compressors/__init__.py
Compressor.read_bytes
def read_bytes(self, path): """Read file content in binary mode""" file = staticfiles_storage.open(path) content = file.read() file.close() return content
python
def read_bytes(self, path): """Read file content in binary mode""" file = staticfiles_storage.open(path) content = file.read() file.close() return content
[ "def", "read_bytes", "(", "self", ",", "path", ")", ":", "file", "=", "staticfiles_storage", ".", "open", "(", "path", ")", "content", "=", "file", ".", "read", "(", ")", "file", ".", "close", "(", ")", "return", "content" ]
Read file content in binary mode
[ "Read", "file", "content", "in", "binary", "mode" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compressors/__init__.py#L214-L219
train
208,101
jazzband/django-pipeline
pipeline/utils.py
set_std_streams_blocking
def set_std_streams_blocking(): """ Set stdout and stderr to be blocking. This is called after Popen.communicate() to revert stdout and stderr back to be blocking (the default) in the event that the process to which they were passed manipulated one or both file descriptors to be non-blocking. """ if not fcntl: return for f in (sys.__stdout__, sys.__stderr__): fileno = f.fileno() flags = fcntl.fcntl(fileno, fcntl.F_GETFL) fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
python
def set_std_streams_blocking(): """ Set stdout and stderr to be blocking. This is called after Popen.communicate() to revert stdout and stderr back to be blocking (the default) in the event that the process to which they were passed manipulated one or both file descriptors to be non-blocking. """ if not fcntl: return for f in (sys.__stdout__, sys.__stderr__): fileno = f.fileno() flags = fcntl.fcntl(fileno, fcntl.F_GETFL) fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
[ "def", "set_std_streams_blocking", "(", ")", ":", "if", "not", "fcntl", ":", "return", "for", "f", "in", "(", "sys", ".", "__stdout__", ",", "sys", ".", "__stderr__", ")", ":", "fileno", "=", "f", ".", "fileno", "(", ")", "flags", "=", "fcntl", ".", ...
Set stdout and stderr to be blocking. This is called after Popen.communicate() to revert stdout and stderr back to be blocking (the default) in the event that the process to which they were passed manipulated one or both file descriptors to be non-blocking.
[ "Set", "stdout", "and", "stderr", "to", "be", "blocking", "." ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/utils.py#L67-L80
train
208,102
jazzband/django-pipeline
pipeline/compilers/__init__.py
SubProcessCompiler.execute_command
def execute_command(self, command, cwd=None, stdout_captured=None): """Execute a command at cwd, saving its normal output at stdout_captured. Errors, defined as nonzero return code or a failure to start execution, will raise a CompilerError exception with a description of the cause. They do not write output. This is file-system safe (any valid file names are allowed, even with spaces or crazy characters) and OS agnostic (existing and future OSes that Python supports should already work). The only thing weird here is that any incoming command arg item may itself be a tuple. This allows compiler implementations to look clean while supporting historical string config settings and maintaining backwards compatibility. Thus, we flatten one layer deep. ((env, foocomp), infile, (-arg,)) -> (env, foocomp, infile, -arg) """ argument_list = [] for flattening_arg in command: if isinstance(flattening_arg, string_types): argument_list.append(flattening_arg) else: argument_list.extend(flattening_arg) # The first element in argument_list is the program that will be executed; if it is '', then # a PermissionError will be raised. Thus empty arguments are filtered out from argument_list argument_list = list(filter(None, argument_list)) stdout = None try: # We always catch stdout in a file, but we may not have a use for it. temp_file_container = cwd or os.path.dirname(stdout_captured or "") or os.getcwd() with NamedTemporaryFile(delete=False, dir=temp_file_container) as stdout: compiling = subprocess.Popen(argument_list, cwd=cwd, stdout=stdout, stderr=subprocess.PIPE) _, stderr = compiling.communicate() set_std_streams_blocking() if compiling.returncode != 0: stdout_captured = None # Don't save erroneous result. raise CompilerError( "{0!r} exit code {1}\n{2}".format(argument_list, compiling.returncode, stderr), command=argument_list, error_output=stderr) # User wants to see everything that happened. if self.verbose: with open(stdout.name) as out: print(out.read()) print(stderr) except OSError as e: stdout_captured = None # Don't save erroneous result. raise CompilerError(e, command=argument_list, error_output=text_type(e)) finally: # Decide what to do with captured stdout. if stdout: if stdout_captured: shutil.move(stdout.name, os.path.join(cwd or os.curdir, stdout_captured)) else: os.remove(stdout.name)
python
def execute_command(self, command, cwd=None, stdout_captured=None): """Execute a command at cwd, saving its normal output at stdout_captured. Errors, defined as nonzero return code or a failure to start execution, will raise a CompilerError exception with a description of the cause. They do not write output. This is file-system safe (any valid file names are allowed, even with spaces or crazy characters) and OS agnostic (existing and future OSes that Python supports should already work). The only thing weird here is that any incoming command arg item may itself be a tuple. This allows compiler implementations to look clean while supporting historical string config settings and maintaining backwards compatibility. Thus, we flatten one layer deep. ((env, foocomp), infile, (-arg,)) -> (env, foocomp, infile, -arg) """ argument_list = [] for flattening_arg in command: if isinstance(flattening_arg, string_types): argument_list.append(flattening_arg) else: argument_list.extend(flattening_arg) # The first element in argument_list is the program that will be executed; if it is '', then # a PermissionError will be raised. Thus empty arguments are filtered out from argument_list argument_list = list(filter(None, argument_list)) stdout = None try: # We always catch stdout in a file, but we may not have a use for it. temp_file_container = cwd or os.path.dirname(stdout_captured or "") or os.getcwd() with NamedTemporaryFile(delete=False, dir=temp_file_container) as stdout: compiling = subprocess.Popen(argument_list, cwd=cwd, stdout=stdout, stderr=subprocess.PIPE) _, stderr = compiling.communicate() set_std_streams_blocking() if compiling.returncode != 0: stdout_captured = None # Don't save erroneous result. raise CompilerError( "{0!r} exit code {1}\n{2}".format(argument_list, compiling.returncode, stderr), command=argument_list, error_output=stderr) # User wants to see everything that happened. if self.verbose: with open(stdout.name) as out: print(out.read()) print(stderr) except OSError as e: stdout_captured = None # Don't save erroneous result. raise CompilerError(e, command=argument_list, error_output=text_type(e)) finally: # Decide what to do with captured stdout. if stdout: if stdout_captured: shutil.move(stdout.name, os.path.join(cwd or os.curdir, stdout_captured)) else: os.remove(stdout.name)
[ "def", "execute_command", "(", "self", ",", "command", ",", "cwd", "=", "None", ",", "stdout_captured", "=", "None", ")", ":", "argument_list", "=", "[", "]", "for", "flattening_arg", "in", "command", ":", "if", "isinstance", "(", "flattening_arg", ",", "s...
Execute a command at cwd, saving its normal output at stdout_captured. Errors, defined as nonzero return code or a failure to start execution, will raise a CompilerError exception with a description of the cause. They do not write output. This is file-system safe (any valid file names are allowed, even with spaces or crazy characters) and OS agnostic (existing and future OSes that Python supports should already work). The only thing weird here is that any incoming command arg item may itself be a tuple. This allows compiler implementations to look clean while supporting historical string config settings and maintaining backwards compatibility. Thus, we flatten one layer deep. ((env, foocomp), infile, (-arg,)) -> (env, foocomp, infile, -arg)
[ "Execute", "a", "command", "at", "cwd", "saving", "its", "normal", "output", "at", "stdout_captured", ".", "Errors", "defined", "as", "nonzero", "return", "code", "or", "a", "failure", "to", "start", "execution", "will", "raise", "a", "CompilerError", "excepti...
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/compilers/__init__.py#L94-L153
train
208,103
jazzband/django-pipeline
pipeline/forms.py
PipelineFormMediaMetaClass._get_css_files
def _get_css_files(cls, extra_files): """Return all CSS files from the Media class. Args: extra_files (dict): The contents of the Media class's original :py:attr:`css` attribute, if one was provided. Returns: dict: The CSS media types and files to return for the :py:attr:`css` attribute. """ packager = Packager() css_packages = getattr(cls, 'css_packages', {}) return dict( (media_target, cls._get_media_files(packager=packager, media_packages=media_packages, media_type='css', extra_files=extra_files.get(media_target, []))) for media_target, media_packages in six.iteritems(css_packages) )
python
def _get_css_files(cls, extra_files): """Return all CSS files from the Media class. Args: extra_files (dict): The contents of the Media class's original :py:attr:`css` attribute, if one was provided. Returns: dict: The CSS media types and files to return for the :py:attr:`css` attribute. """ packager = Packager() css_packages = getattr(cls, 'css_packages', {}) return dict( (media_target, cls._get_media_files(packager=packager, media_packages=media_packages, media_type='css', extra_files=extra_files.get(media_target, []))) for media_target, media_packages in six.iteritems(css_packages) )
[ "def", "_get_css_files", "(", "cls", ",", "extra_files", ")", ":", "packager", "=", "Packager", "(", ")", "css_packages", "=", "getattr", "(", "cls", ",", "'css_packages'", ",", "{", "}", ")", "return", "dict", "(", "(", "media_target", ",", "cls", ".", ...
Return all CSS files from the Media class. Args: extra_files (dict): The contents of the Media class's original :py:attr:`css` attribute, if one was provided. Returns: dict: The CSS media types and files to return for the :py:attr:`css` attribute.
[ "Return", "all", "CSS", "files", "from", "the", "Media", "class", "." ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/forms.py#L148-L172
train
208,104
jazzband/django-pipeline
pipeline/forms.py
PipelineFormMediaMetaClass._get_js_files
def _get_js_files(cls, extra_files): """Return all JavaScript files from the Media class. Args: extra_files (list): The contents of the Media class's original :py:attr:`js` attribute, if one was provided. Returns: list: The JavaScript files to return for the :py:attr:`js` attribute. """ return cls._get_media_files( packager=Packager(), media_packages=getattr(cls, 'js_packages', {}), media_type='js', extra_files=extra_files)
python
def _get_js_files(cls, extra_files): """Return all JavaScript files from the Media class. Args: extra_files (list): The contents of the Media class's original :py:attr:`js` attribute, if one was provided. Returns: list: The JavaScript files to return for the :py:attr:`js` attribute. """ return cls._get_media_files( packager=Packager(), media_packages=getattr(cls, 'js_packages', {}), media_type='js', extra_files=extra_files)
[ "def", "_get_js_files", "(", "cls", ",", "extra_files", ")", ":", "return", "cls", ".", "_get_media_files", "(", "packager", "=", "Packager", "(", ")", ",", "media_packages", "=", "getattr", "(", "cls", ",", "'js_packages'", ",", "{", "}", ")", ",", "med...
Return all JavaScript files from the Media class. Args: extra_files (list): The contents of the Media class's original :py:attr:`js` attribute, if one was provided. Returns: list: The JavaScript files to return for the :py:attr:`js` attribute.
[ "Return", "all", "JavaScript", "files", "from", "the", "Media", "class", "." ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/forms.py#L174-L190
train
208,105
jazzband/django-pipeline
pipeline/forms.py
PipelineFormMediaMetaClass._get_media_files
def _get_media_files(cls, packager, media_packages, media_type, extra_files): """Return source or output media files for a list of packages. This will go through the media files belonging to the provided list of packages referenced in a Media class and return the output files (if Pipeline is enabled) or the source files (if not enabled). Args: packager (pipeline.packager.Packager): The packager responsible for media compilation for this type of package. media_packages (list of unicode): The list of media packages referenced in Media to compile or return. extra_files (list of unicode): The list of extra files to include in the result. This would be the list stored in the Media class's original :py:attr:`css` or :py:attr:`js` attributes. Returns: list: The list of media files for the given packages. """ source_files = list(extra_files) if (not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED): default_collector.collect() for media_package in media_packages: package = packager.package_for(media_type, media_package) if settings.PIPELINE_ENABLED: source_files.append( staticfiles_storage.url(package.output_filename)) else: source_files += packager.compile(package.paths) return source_files
python
def _get_media_files(cls, packager, media_packages, media_type, extra_files): """Return source or output media files for a list of packages. This will go through the media files belonging to the provided list of packages referenced in a Media class and return the output files (if Pipeline is enabled) or the source files (if not enabled). Args: packager (pipeline.packager.Packager): The packager responsible for media compilation for this type of package. media_packages (list of unicode): The list of media packages referenced in Media to compile or return. extra_files (list of unicode): The list of extra files to include in the result. This would be the list stored in the Media class's original :py:attr:`css` or :py:attr:`js` attributes. Returns: list: The list of media files for the given packages. """ source_files = list(extra_files) if (not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED): default_collector.collect() for media_package in media_packages: package = packager.package_for(media_type, media_package) if settings.PIPELINE_ENABLED: source_files.append( staticfiles_storage.url(package.output_filename)) else: source_files += packager.compile(package.paths) return source_files
[ "def", "_get_media_files", "(", "cls", ",", "packager", ",", "media_packages", ",", "media_type", ",", "extra_files", ")", ":", "source_files", "=", "list", "(", "extra_files", ")", "if", "(", "not", "settings", ".", "PIPELINE_ENABLED", "and", "settings", ".",...
Return source or output media files for a list of packages. This will go through the media files belonging to the provided list of packages referenced in a Media class and return the output files (if Pipeline is enabled) or the source files (if not enabled). Args: packager (pipeline.packager.Packager): The packager responsible for media compilation for this type of package. media_packages (list of unicode): The list of media packages referenced in Media to compile or return. extra_files (list of unicode): The list of extra files to include in the result. This would be the list stored in the Media class's original :py:attr:`css` or :py:attr:`js` attributes. Returns: list: The list of media files for the given packages.
[ "Return", "source", "or", "output", "media", "files", "for", "a", "list", "of", "packages", "." ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/forms.py#L192-L233
train
208,106
jazzband/django-pipeline
pipeline/templatetags/pipeline.py
PipelineMixin.render_compressed
def render_compressed(self, package, package_name, package_type): """Render HTML for the package. If ``PIPELINE_ENABLED`` is ``True``, this will render the package's output file (using :py:meth:`render_compressed_output`). Otherwise, this will render the package's source files (using :py:meth:`render_compressed_sources`). Subclasses can override this method to provide custom behavior for determining what to render. """ if settings.PIPELINE_ENABLED: return self.render_compressed_output(package, package_name, package_type) else: return self.render_compressed_sources(package, package_name, package_type)
python
def render_compressed(self, package, package_name, package_type): """Render HTML for the package. If ``PIPELINE_ENABLED`` is ``True``, this will render the package's output file (using :py:meth:`render_compressed_output`). Otherwise, this will render the package's source files (using :py:meth:`render_compressed_sources`). Subclasses can override this method to provide custom behavior for determining what to render. """ if settings.PIPELINE_ENABLED: return self.render_compressed_output(package, package_name, package_type) else: return self.render_compressed_sources(package, package_name, package_type)
[ "def", "render_compressed", "(", "self", ",", "package", ",", "package_name", ",", "package_type", ")", ":", "if", "settings", ".", "PIPELINE_ENABLED", ":", "return", "self", ".", "render_compressed_output", "(", "package", ",", "package_name", ",", "package_type"...
Render HTML for the package. If ``PIPELINE_ENABLED`` is ``True``, this will render the package's output file (using :py:meth:`render_compressed_output`). Otherwise, this will render the package's source files (using :py:meth:`render_compressed_sources`). Subclasses can override this method to provide custom behavior for determining what to render.
[ "Render", "HTML", "for", "the", "package", "." ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/templatetags/pipeline.py#L56-L72
train
208,107
jazzband/django-pipeline
pipeline/templatetags/pipeline.py
PipelineMixin.render_compressed_output
def render_compressed_output(self, package, package_name, package_type): """Render HTML for using the package's output file. Subclasses can override this method to provide custom behavior for rendering the output file. """ method = getattr(self, 'render_{0}'.format(package_type)) return method(package, package.output_filename)
python
def render_compressed_output(self, package, package_name, package_type): """Render HTML for using the package's output file. Subclasses can override this method to provide custom behavior for rendering the output file. """ method = getattr(self, 'render_{0}'.format(package_type)) return method(package, package.output_filename)
[ "def", "render_compressed_output", "(", "self", ",", "package", ",", "package_name", ",", "package_type", ")", ":", "method", "=", "getattr", "(", "self", ",", "'render_{0}'", ".", "format", "(", "package_type", ")", ")", "return", "method", "(", "package", ...
Render HTML for using the package's output file. Subclasses can override this method to provide custom behavior for rendering the output file.
[ "Render", "HTML", "for", "using", "the", "package", "s", "output", "file", "." ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/templatetags/pipeline.py#L74-L82
train
208,108
jazzband/django-pipeline
pipeline/templatetags/pipeline.py
PipelineMixin.render_compressed_sources
def render_compressed_sources(self, package, package_name, package_type): """Render HTML for using the package's list of source files. Each source file will first be collected, if ``PIPELINE_COLLECTOR_ENABLED`` is ``True``. If there are any errors compiling any of the source files, an ``SHOW_ERRORS_INLINE`` is ``True``, those errors will be shown at the top of the page. Subclasses can override this method to provide custom behavior for rendering the source files. """ if settings.PIPELINE_COLLECTOR_ENABLED: default_collector.collect(self.request) packager = Packager() method = getattr(self, 'render_individual_{0}'.format(package_type)) try: paths = packager.compile(package.paths) except CompilerError as e: if settings.SHOW_ERRORS_INLINE: method = getattr(self, 'render_error_{0}'.format( package_type)) return method(package_name, e) else: raise templates = packager.pack_templates(package) return method(package, paths, templates=templates)
python
def render_compressed_sources(self, package, package_name, package_type): """Render HTML for using the package's list of source files. Each source file will first be collected, if ``PIPELINE_COLLECTOR_ENABLED`` is ``True``. If there are any errors compiling any of the source files, an ``SHOW_ERRORS_INLINE`` is ``True``, those errors will be shown at the top of the page. Subclasses can override this method to provide custom behavior for rendering the source files. """ if settings.PIPELINE_COLLECTOR_ENABLED: default_collector.collect(self.request) packager = Packager() method = getattr(self, 'render_individual_{0}'.format(package_type)) try: paths = packager.compile(package.paths) except CompilerError as e: if settings.SHOW_ERRORS_INLINE: method = getattr(self, 'render_error_{0}'.format( package_type)) return method(package_name, e) else: raise templates = packager.pack_templates(package) return method(package, paths, templates=templates)
[ "def", "render_compressed_sources", "(", "self", ",", "package", ",", "package_name", ",", "package_type", ")", ":", "if", "settings", ".", "PIPELINE_COLLECTOR_ENABLED", ":", "default_collector", ".", "collect", "(", "self", ".", "request", ")", "packager", "=", ...
Render HTML for using the package's list of source files. Each source file will first be collected, if ``PIPELINE_COLLECTOR_ENABLED`` is ``True``. If there are any errors compiling any of the source files, an ``SHOW_ERRORS_INLINE`` is ``True``, those errors will be shown at the top of the page. Subclasses can override this method to provide custom behavior for rendering the source files.
[ "Render", "HTML", "for", "using", "the", "package", "s", "list", "of", "source", "files", "." ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/templatetags/pipeline.py#L84-L116
train
208,109
jazzband/django-pipeline
pipeline/finders.py
ManifestFinder.find
def find(self, path, all=False): """ Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT """ matches = [] for elem in chain(settings.STYLESHEETS.values(), settings.JAVASCRIPT.values()): if normpath(elem['output_filename']) == normpath(path): match = safe_join(settings.PIPELINE_ROOT, path) if not all: return match matches.append(match) return matches
python
def find(self, path, all=False): """ Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT """ matches = [] for elem in chain(settings.STYLESHEETS.values(), settings.JAVASCRIPT.values()): if normpath(elem['output_filename']) == normpath(path): match = safe_join(settings.PIPELINE_ROOT, path) if not all: return match matches.append(match) return matches
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "matches", "=", "[", "]", "for", "elem", "in", "chain", "(", "settings", ".", "STYLESHEETS", ".", "values", "(", ")", ",", "settings", ".", "JAVASCRIPT", ".", "values", "(...
Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT
[ "Looks", "for", "files", "in", "PIPELINE", ".", "STYLESHEETS", "and", "PIPELINE", ".", "JAVASCRIPT" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/finders.py#L26-L37
train
208,110
jazzband/django-pipeline
pipeline/finders.py
CachedFileFinder.find
def find(self, path, all=False): """ Work out the uncached name of the file and look that up instead """ try: start, _, extn = path.rsplit('.', 2) except ValueError: return [] path = '.'.join((start, extn)) return find(path, all=all) or []
python
def find(self, path, all=False): """ Work out the uncached name of the file and look that up instead """ try: start, _, extn = path.rsplit('.', 2) except ValueError: return [] path = '.'.join((start, extn)) return find(path, all=all) or []
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "try", ":", "start", ",", "_", ",", "extn", "=", "path", ".", "rsplit", "(", "'.'", ",", "2", ")", "except", "ValueError", ":", "return", "[", "]", "path", "=", "'.'",...
Work out the uncached name of the file and look that up instead
[ "Work", "out", "the", "uncached", "name", "of", "the", "file", "and", "look", "that", "up", "instead" ]
3cd2f93bb47bf8d34447e13ff691f7027e7b07a2
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/finders.py#L44-L53
train
208,111
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
AttachmentPublic.get
def get(cls, attachment_public_uuid, custom_headers=None): """ Get a specific attachment's metadata through its UUID. The Content-Type header of the response will describe the MIME type of the attachment file. :type api_context: context.ApiContext :type attachment_public_uuid: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseAttachmentPublic """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(attachment_public_uuid) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseAttachmentPublic.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_GET) )
python
def get(cls, attachment_public_uuid, custom_headers=None): """ Get a specific attachment's metadata through its UUID. The Content-Type header of the response will describe the MIME type of the attachment file. :type api_context: context.ApiContext :type attachment_public_uuid: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseAttachmentPublic """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(attachment_public_uuid) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseAttachmentPublic.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_GET) )
[ "def", "get", "(", "cls", ",", "attachment_public_uuid", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "api_client", "=", "client", ".", "ApiClient", "(", "cls", ".", "_get_api_conte...
Get a specific attachment's metadata through its UUID. The Content-Type header of the response will describe the MIME type of the attachment file. :type api_context: context.ApiContext :type attachment_public_uuid: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseAttachmentPublic
[ "Get", "a", "specific", "attachment", "s", "metadata", "through", "its", "UUID", ".", "The", "Content", "-", "Type", "header", "of", "the", "response", "will", "describe", "the", "MIME", "type", "of", "the", "attachment", "file", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L1494-L1516
train
208,112
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
TabAttachmentTab.get
def get(cls, tab_uuid, tab_attachment_tab_id, custom_headers=None): """ Get a specific attachment. The header of the response contains the content-type of the attachment. :type api_context: context.ApiContext :type tab_uuid: str :type tab_attachment_tab_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseTabAttachmentTab """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(tab_uuid, tab_attachment_tab_id) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseTabAttachmentTab.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_GET) )
python
def get(cls, tab_uuid, tab_attachment_tab_id, custom_headers=None): """ Get a specific attachment. The header of the response contains the content-type of the attachment. :type api_context: context.ApiContext :type tab_uuid: str :type tab_attachment_tab_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseTabAttachmentTab """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(tab_uuid, tab_attachment_tab_id) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseTabAttachmentTab.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_GET) )
[ "def", "get", "(", "cls", ",", "tab_uuid", ",", "tab_attachment_tab_id", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "api_client", "=", "client", ".", "ApiClient", "(", "cls", "....
Get a specific attachment. The header of the response contains the content-type of the attachment. :type api_context: context.ApiContext :type tab_uuid: str :type tab_attachment_tab_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseTabAttachmentTab
[ "Get", "a", "specific", "attachment", ".", "The", "header", "of", "the", "response", "contains", "the", "content", "-", "type", "of", "the", "attachment", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L1758-L1781
train
208,113
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
Payment.create
def create(cls, amount, counterparty_alias, description, monetary_account_id=None, attachment=None, merchant_reference=None, allow_bunqto=None, custom_headers=None): """ Create a new Payment. :type user_id: int :type monetary_account_id: int :param amount: The Amount to transfer with the Payment. Must be bigger than 0 and smaller than the MonetaryAccount's balance. :type amount: object_.Amount :param counterparty_alias: The Alias of the party we are transferring the money to. Can be an Alias of type EMAIL or PHONE_NUMBER (for bunq MonetaryAccounts or bunq.to payments) or IBAN (for external bank account). :type counterparty_alias: object_.Pointer :param description: The description for the Payment. Maximum 140 characters for Payments to external IBANs, 9000 characters for Payments to only other bunq MonetaryAccounts. Field is required but can be an empty string. :type description: str :param attachment: The Attachments to attach to the Payment. :type attachment: list[object_.AttachmentMonetaryAccountPayment] :param merchant_reference: Optional data to be included with the Payment specific to the merchant. :type merchant_reference: str :param allow_bunqto: Whether or not sending a bunq.to payment is allowed. :type allow_bunqto: bool :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_AMOUNT: amount, cls.FIELD_COUNTERPARTY_ALIAS: counterparty_alias, cls.FIELD_DESCRIPTION: description, cls.FIELD_ATTACHMENT: attachment, cls.FIELD_MERCHANT_REFERENCE: merchant_reference, cls.FIELD_ALLOW_BUNQTO: allow_bunqto } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, amount, counterparty_alias, description, monetary_account_id=None, attachment=None, merchant_reference=None, allow_bunqto=None, custom_headers=None): """ Create a new Payment. :type user_id: int :type monetary_account_id: int :param amount: The Amount to transfer with the Payment. Must be bigger than 0 and smaller than the MonetaryAccount's balance. :type amount: object_.Amount :param counterparty_alias: The Alias of the party we are transferring the money to. Can be an Alias of type EMAIL or PHONE_NUMBER (for bunq MonetaryAccounts or bunq.to payments) or IBAN (for external bank account). :type counterparty_alias: object_.Pointer :param description: The description for the Payment. Maximum 140 characters for Payments to external IBANs, 9000 characters for Payments to only other bunq MonetaryAccounts. Field is required but can be an empty string. :type description: str :param attachment: The Attachments to attach to the Payment. :type attachment: list[object_.AttachmentMonetaryAccountPayment] :param merchant_reference: Optional data to be included with the Payment specific to the merchant. :type merchant_reference: str :param allow_bunqto: Whether or not sending a bunq.to payment is allowed. :type allow_bunqto: bool :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_AMOUNT: amount, cls.FIELD_COUNTERPARTY_ALIAS: counterparty_alias, cls.FIELD_DESCRIPTION: description, cls.FIELD_ATTACHMENT: attachment, cls.FIELD_MERCHANT_REFERENCE: merchant_reference, cls.FIELD_ALLOW_BUNQTO: allow_bunqto } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "amount", ",", "counterparty_alias", ",", "description", ",", "monetary_account_id", "=", "None", ",", "attachment", "=", "None", ",", "merchant_reference", "=", "None", ",", "allow_bunqto", "=", "None", ",", "custom_headers", ...
Create a new Payment. :type user_id: int :type monetary_account_id: int :param amount: The Amount to transfer with the Payment. Must be bigger than 0 and smaller than the MonetaryAccount's balance. :type amount: object_.Amount :param counterparty_alias: The Alias of the party we are transferring the money to. Can be an Alias of type EMAIL or PHONE_NUMBER (for bunq MonetaryAccounts or bunq.to payments) or IBAN (for external bank account). :type counterparty_alias: object_.Pointer :param description: The description for the Payment. Maximum 140 characters for Payments to external IBANs, 9000 characters for Payments to only other bunq MonetaryAccounts. Field is required but can be an empty string. :type description: str :param attachment: The Attachments to attach to the Payment. :type attachment: list[object_.AttachmentMonetaryAccountPayment] :param merchant_reference: Optional data to be included with the Payment specific to the merchant. :type merchant_reference: str :param allow_bunqto: Whether or not sending a bunq.to payment is allowed. :type allow_bunqto: bool :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Create", "a", "new", "Payment", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L2537-L2595
train
208,114
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
CardDebit.create
def create(cls, second_line, name_on_card, alias=None, type_=None, pin_code_assignment=None, monetary_account_id_fallback=None, custom_headers=None): """ Create a new debit card request. :type user_id: int :param second_line: The second line of text on the card, used as name/description for it. It can contain at most 17 characters and it can be empty. :type second_line: str :param name_on_card: The user's name as it will be on the card. Check 'card-name' for the available card names for a user. :type name_on_card: str :param alias: The pointer to the monetary account that will be connected at first with the card. Its IBAN code is also the one that will be printed on the card itself. The pointer must be of type IBAN. :type alias: object_.Pointer :param type_: The type of card to order. Can be MAESTRO or MASTERCARD. :type type_: str :param pin_code_assignment: Array of Types, PINs, account IDs assigned to the card. :type pin_code_assignment: list[object_.CardPinAssignment] :param monetary_account_id_fallback: ID of the MA to be used as fallback for this card if insufficient balance. Fallback account is removed if not supplied. :type monetary_account_id_fallback: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCardDebit """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_SECOND_LINE: second_line, cls.FIELD_NAME_ON_CARD: name_on_card, cls.FIELD_ALIAS: alias, cls.FIELD_TYPE: type_, cls.FIELD_PIN_CODE_ASSIGNMENT: pin_code_assignment, cls.FIELD_MONETARY_ACCOUNT_ID_FALLBACK: monetary_account_id_fallback } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() request_bytes = security.encrypt(cls._get_api_context(), request_bytes, custom_headers) endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id()) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseCardDebit.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_POST) )
python
def create(cls, second_line, name_on_card, alias=None, type_=None, pin_code_assignment=None, monetary_account_id_fallback=None, custom_headers=None): """ Create a new debit card request. :type user_id: int :param second_line: The second line of text on the card, used as name/description for it. It can contain at most 17 characters and it can be empty. :type second_line: str :param name_on_card: The user's name as it will be on the card. Check 'card-name' for the available card names for a user. :type name_on_card: str :param alias: The pointer to the monetary account that will be connected at first with the card. Its IBAN code is also the one that will be printed on the card itself. The pointer must be of type IBAN. :type alias: object_.Pointer :param type_: The type of card to order. Can be MAESTRO or MASTERCARD. :type type_: str :param pin_code_assignment: Array of Types, PINs, account IDs assigned to the card. :type pin_code_assignment: list[object_.CardPinAssignment] :param monetary_account_id_fallback: ID of the MA to be used as fallback for this card if insufficient balance. Fallback account is removed if not supplied. :type monetary_account_id_fallback: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCardDebit """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_SECOND_LINE: second_line, cls.FIELD_NAME_ON_CARD: name_on_card, cls.FIELD_ALIAS: alias, cls.FIELD_TYPE: type_, cls.FIELD_PIN_CODE_ASSIGNMENT: pin_code_assignment, cls.FIELD_MONETARY_ACCOUNT_ID_FALLBACK: monetary_account_id_fallback } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() request_bytes = security.encrypt(cls._get_api_context(), request_bytes, custom_headers) endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id()) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseCardDebit.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_POST) )
[ "def", "create", "(", "cls", ",", "second_line", ",", "name_on_card", ",", "alias", "=", "None", ",", "type_", "=", "None", ",", "pin_code_assignment", "=", "None", ",", "monetary_account_id_fallback", "=", "None", ",", "custom_headers", "=", "None", ")", ":...
Create a new debit card request. :type user_id: int :param second_line: The second line of text on the card, used as name/description for it. It can contain at most 17 characters and it can be empty. :type second_line: str :param name_on_card: The user's name as it will be on the card. Check 'card-name' for the available card names for a user. :type name_on_card: str :param alias: The pointer to the monetary account that will be connected at first with the card. Its IBAN code is also the one that will be printed on the card itself. The pointer must be of type IBAN. :type alias: object_.Pointer :param type_: The type of card to order. Can be MAESTRO or MASTERCARD. :type type_: str :param pin_code_assignment: Array of Types, PINs, account IDs assigned to the card. :type pin_code_assignment: list[object_.CardPinAssignment] :param monetary_account_id_fallback: ID of the MA to be used as fallback for this card if insufficient balance. Fallback account is removed if not supplied. :type monetary_account_id_fallback: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCardDebit
[ "Create", "a", "new", "debit", "card", "request", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L4294-L4350
train
208,115
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
CardGeneratedCvc2.create
def create(cls, card_id, type_=None, custom_headers=None): """ Generate a new CVC2 code for a card. :type user_id: int :type card_id: int :param type_: The type of generated cvc2. Can be STATIC or GENERATED. :type type_: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_TYPE: type_ } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() request_bytes = security.encrypt(cls._get_api_context(), request_bytes, custom_headers) endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), card_id) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, card_id, type_=None, custom_headers=None): """ Generate a new CVC2 code for a card. :type user_id: int :type card_id: int :param type_: The type of generated cvc2. Can be STATIC or GENERATED. :type type_: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_TYPE: type_ } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() request_bytes = security.encrypt(cls._get_api_context(), request_bytes, custom_headers) endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), card_id) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "card_id", ",", "type_", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "request_map", "=", "{", "cls", ".", "FIELD_TYPE", ":", "t...
Generate a new CVC2 code for a card. :type user_id: int :type card_id: int :param type_: The type of generated cvc2. Can be STATIC or GENERATED. :type type_: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Generate", "a", "new", "CVC2", "code", "for", "a", "card", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L4641-L4674
train
208,116
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
CardReplace.create
def create(cls, card_id, name_on_card=None, pin_code=None, second_line=None, custom_headers=None): """ Request a card replacement. :type user_id: int :type card_id: int :param name_on_card: The user's name as it will be on the card. Check 'card-name' for the available card names for a user. :type name_on_card: str :param pin_code: The plaintext pin code. Requests require encryption to be enabled. :type pin_code: str :param second_line: The second line on the card. :type second_line: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_NAME_ON_CARD: name_on_card, cls.FIELD_PIN_CODE: pin_code, cls.FIELD_SECOND_LINE: second_line } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() request_bytes = security.encrypt(cls._get_api_context(), request_bytes, custom_headers) endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), card_id) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, card_id, name_on_card=None, pin_code=None, second_line=None, custom_headers=None): """ Request a card replacement. :type user_id: int :type card_id: int :param name_on_card: The user's name as it will be on the card. Check 'card-name' for the available card names for a user. :type name_on_card: str :param pin_code: The plaintext pin code. Requests require encryption to be enabled. :type pin_code: str :param second_line: The second line on the card. :type second_line: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_NAME_ON_CARD: name_on_card, cls.FIELD_PIN_CODE: pin_code, cls.FIELD_SECOND_LINE: second_line } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() request_bytes = security.encrypt(cls._get_api_context(), request_bytes, custom_headers) endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), card_id) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "card_id", ",", "name_on_card", "=", "None", ",", "pin_code", "=", "None", ",", "second_line", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", ...
Request a card replacement. :type user_id: int :type card_id: int :param name_on_card: The user's name as it will be on the card. Check 'card-name' for the available card names for a user. :type name_on_card: str :param pin_code: The plaintext pin code. Requests require encryption to be enabled. :type pin_code: str :param second_line: The second line on the card. :type second_line: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Request", "a", "card", "replacement", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L4991-L5033
train
208,117
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
Card.update
def update(cls, card_id, pin_code=None, activation_code=None, status=None, card_limit=None, card_limit_atm=None, limit=None, mag_stripe_permission=None, country_permission=None, pin_code_assignment=None, primary_account_numbers_virtual=None, monetary_account_id_fallback=None, custom_headers=None): """ Update the card details. Allow to change pin code, status, limits, country permissions and the monetary account connected to the card. When the card has been received, it can be also activated through this endpoint. :type user_id: int :type card_id: int :param pin_code: The plaintext pin code. Requests require encryption to be enabled. :type pin_code: str :param activation_code: DEPRECATED: Activate a card by setting status to ACTIVE when the order_status is ACCEPTED_FOR_PRODUCTION. :type activation_code: str :param status: The status to set for the card. Can be ACTIVE, DEACTIVATED, LOST, STOLEN or CANCELLED, and can only be set to LOST/STOLEN/CANCELLED when order status is ACCEPTED_FOR_PRODUCTION/DELIVERED_TO_CUSTOMER/CARD_UPDATE_REQUESTED/CARD_UPDATE_SENT/CARD_UPDATE_ACCEPTED. Can only be set to DEACTIVATED after initial activation, i.e. order_status is DELIVERED_TO_CUSTOMER/CARD_UPDATE_REQUESTED/CARD_UPDATE_SENT/CARD_UPDATE_ACCEPTED. Mind that all the possible choices (apart from ACTIVE and DEACTIVATED) are permanent and cannot be changed after. :type status: str :param card_limit: The spending limit for the card. :type card_limit: object_.Amount :param card_limit_atm: The ATM spending limit for the card. :type card_limit_atm: object_.Amount :param limit: DEPRECATED: The limits to define for the card, among CARD_LIMIT_CONTACTLESS, CARD_LIMIT_ATM, CARD_LIMIT_DIPPING and CARD_LIMIT_POS_ICC (e.g. 25 EUR for CARD_LIMIT_CONTACTLESS). All the limits must be provided on update. :type limit: list[object_.CardLimit] :param mag_stripe_permission: DEPRECATED: Whether or not it is allowed to use the mag stripe for the card. :type mag_stripe_permission: object_.CardMagStripePermission :param country_permission: The countries for which to grant (temporary) permissions to use the card. :type country_permission: list[object_.CardCountryPermission] :param pin_code_assignment: Array of Types, PINs, account IDs assigned to the card. :type pin_code_assignment: list[object_.CardPinAssignment] :param primary_account_numbers_virtual: Array of PANs, status, description and account id for online cards. :type primary_account_numbers_virtual: list[object_.CardVirtualPrimaryAccountNumber] :param monetary_account_id_fallback: ID of the MA to be used as fallback for this card if insufficient balance. Fallback account is removed if not supplied. :type monetary_account_id_fallback: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCard """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_PIN_CODE: pin_code, cls.FIELD_ACTIVATION_CODE: activation_code, cls.FIELD_STATUS: status, cls.FIELD_CARD_LIMIT: card_limit, cls.FIELD_CARD_LIMIT_ATM: card_limit_atm, cls.FIELD_LIMIT: limit, cls.FIELD_MAG_STRIPE_PERMISSION: mag_stripe_permission, cls.FIELD_COUNTRY_PERMISSION: country_permission, cls.FIELD_PIN_CODE_ASSIGNMENT: pin_code_assignment, cls.FIELD_PRIMARY_ACCOUNT_NUMBERS_VIRTUAL: primary_account_numbers_virtual, cls.FIELD_MONETARY_ACCOUNT_ID_FALLBACK: monetary_account_id_fallback } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() request_bytes = security.encrypt(cls._get_api_context(), request_bytes, custom_headers) endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(), card_id) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseCard.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_PUT) )
python
def update(cls, card_id, pin_code=None, activation_code=None, status=None, card_limit=None, card_limit_atm=None, limit=None, mag_stripe_permission=None, country_permission=None, pin_code_assignment=None, primary_account_numbers_virtual=None, monetary_account_id_fallback=None, custom_headers=None): """ Update the card details. Allow to change pin code, status, limits, country permissions and the monetary account connected to the card. When the card has been received, it can be also activated through this endpoint. :type user_id: int :type card_id: int :param pin_code: The plaintext pin code. Requests require encryption to be enabled. :type pin_code: str :param activation_code: DEPRECATED: Activate a card by setting status to ACTIVE when the order_status is ACCEPTED_FOR_PRODUCTION. :type activation_code: str :param status: The status to set for the card. Can be ACTIVE, DEACTIVATED, LOST, STOLEN or CANCELLED, and can only be set to LOST/STOLEN/CANCELLED when order status is ACCEPTED_FOR_PRODUCTION/DELIVERED_TO_CUSTOMER/CARD_UPDATE_REQUESTED/CARD_UPDATE_SENT/CARD_UPDATE_ACCEPTED. Can only be set to DEACTIVATED after initial activation, i.e. order_status is DELIVERED_TO_CUSTOMER/CARD_UPDATE_REQUESTED/CARD_UPDATE_SENT/CARD_UPDATE_ACCEPTED. Mind that all the possible choices (apart from ACTIVE and DEACTIVATED) are permanent and cannot be changed after. :type status: str :param card_limit: The spending limit for the card. :type card_limit: object_.Amount :param card_limit_atm: The ATM spending limit for the card. :type card_limit_atm: object_.Amount :param limit: DEPRECATED: The limits to define for the card, among CARD_LIMIT_CONTACTLESS, CARD_LIMIT_ATM, CARD_LIMIT_DIPPING and CARD_LIMIT_POS_ICC (e.g. 25 EUR for CARD_LIMIT_CONTACTLESS). All the limits must be provided on update. :type limit: list[object_.CardLimit] :param mag_stripe_permission: DEPRECATED: Whether or not it is allowed to use the mag stripe for the card. :type mag_stripe_permission: object_.CardMagStripePermission :param country_permission: The countries for which to grant (temporary) permissions to use the card. :type country_permission: list[object_.CardCountryPermission] :param pin_code_assignment: Array of Types, PINs, account IDs assigned to the card. :type pin_code_assignment: list[object_.CardPinAssignment] :param primary_account_numbers_virtual: Array of PANs, status, description and account id for online cards. :type primary_account_numbers_virtual: list[object_.CardVirtualPrimaryAccountNumber] :param monetary_account_id_fallback: ID of the MA to be used as fallback for this card if insufficient balance. Fallback account is removed if not supplied. :type monetary_account_id_fallback: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCard """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_PIN_CODE: pin_code, cls.FIELD_ACTIVATION_CODE: activation_code, cls.FIELD_STATUS: status, cls.FIELD_CARD_LIMIT: card_limit, cls.FIELD_CARD_LIMIT_ATM: card_limit_atm, cls.FIELD_LIMIT: limit, cls.FIELD_MAG_STRIPE_PERMISSION: mag_stripe_permission, cls.FIELD_COUNTRY_PERMISSION: country_permission, cls.FIELD_PIN_CODE_ASSIGNMENT: pin_code_assignment, cls.FIELD_PRIMARY_ACCOUNT_NUMBERS_VIRTUAL: primary_account_numbers_virtual, cls.FIELD_MONETARY_ACCOUNT_ID_FALLBACK: monetary_account_id_fallback } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() request_bytes = security.encrypt(cls._get_api_context(), request_bytes, custom_headers) endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(), card_id) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseCard.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_PUT) )
[ "def", "update", "(", "cls", ",", "card_id", ",", "pin_code", "=", "None", ",", "activation_code", "=", "None", ",", "status", "=", "None", ",", "card_limit", "=", "None", ",", "card_limit_atm", "=", "None", ",", "limit", "=", "None", ",", "mag_stripe_pe...
Update the card details. Allow to change pin code, status, limits, country permissions and the monetary account connected to the card. When the card has been received, it can be also activated through this endpoint. :type user_id: int :type card_id: int :param pin_code: The plaintext pin code. Requests require encryption to be enabled. :type pin_code: str :param activation_code: DEPRECATED: Activate a card by setting status to ACTIVE when the order_status is ACCEPTED_FOR_PRODUCTION. :type activation_code: str :param status: The status to set for the card. Can be ACTIVE, DEACTIVATED, LOST, STOLEN or CANCELLED, and can only be set to LOST/STOLEN/CANCELLED when order status is ACCEPTED_FOR_PRODUCTION/DELIVERED_TO_CUSTOMER/CARD_UPDATE_REQUESTED/CARD_UPDATE_SENT/CARD_UPDATE_ACCEPTED. Can only be set to DEACTIVATED after initial activation, i.e. order_status is DELIVERED_TO_CUSTOMER/CARD_UPDATE_REQUESTED/CARD_UPDATE_SENT/CARD_UPDATE_ACCEPTED. Mind that all the possible choices (apart from ACTIVE and DEACTIVATED) are permanent and cannot be changed after. :type status: str :param card_limit: The spending limit for the card. :type card_limit: object_.Amount :param card_limit_atm: The ATM spending limit for the card. :type card_limit_atm: object_.Amount :param limit: DEPRECATED: The limits to define for the card, among CARD_LIMIT_CONTACTLESS, CARD_LIMIT_ATM, CARD_LIMIT_DIPPING and CARD_LIMIT_POS_ICC (e.g. 25 EUR for CARD_LIMIT_CONTACTLESS). All the limits must be provided on update. :type limit: list[object_.CardLimit] :param mag_stripe_permission: DEPRECATED: Whether or not it is allowed to use the mag stripe for the card. :type mag_stripe_permission: object_.CardMagStripePermission :param country_permission: The countries for which to grant (temporary) permissions to use the card. :type country_permission: list[object_.CardCountryPermission] :param pin_code_assignment: Array of Types, PINs, account IDs assigned to the card. :type pin_code_assignment: list[object_.CardPinAssignment] :param primary_account_numbers_virtual: Array of PANs, status, description and account id for online cards. :type primary_account_numbers_virtual: list[object_.CardVirtualPrimaryAccountNumber] :param monetary_account_id_fallback: ID of the MA to be used as fallback for this card if insufficient balance. Fallback account is removed if not supplied. :type monetary_account_id_fallback: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCard
[ "Update", "the", "card", "details", ".", "Allow", "to", "change", "pin", "code", "status", "limits", "country", "permissions", "and", "the", "monetary", "account", "connected", "to", "the", "card", ".", "When", "the", "card", "has", "been", "received", "it",...
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L5260-L5351
train
208,118
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
Card.get
def get(cls, card_id, custom_headers=None): """ Return the details of a specific card. :type api_context: context.ApiContext :type user_id: int :type card_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCard """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(cls._determine_user_id(), card_id) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseCard.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_GET) )
python
def get(cls, card_id, custom_headers=None): """ Return the details of a specific card. :type api_context: context.ApiContext :type user_id: int :type card_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCard """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(cls._determine_user_id(), card_id) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseCard.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_GET) )
[ "def", "get", "(", "cls", ",", "card_id", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "api_client", "=", "client", ".", "ApiClient", "(", "cls", ".", "_get_api_context", "(", "...
Return the details of a specific card. :type api_context: context.ApiContext :type user_id: int :type card_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCard
[ "Return", "the", "details", "of", "a", "specific", "card", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L5354-L5376
train
208,119
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
CashRegister.create
def create(cls, name, status, avatar_uuid, monetary_account_id=None, location=None, notification_filters=None, tab_text_waiting_screen=None, custom_headers=None): """ Create a new CashRegister. Only an UserCompany can create a CashRegisters. They need to be created with status PENDING_APPROVAL, an bunq admin has to approve your CashRegister before you can use it. In the sandbox testing environment an CashRegister will be automatically approved immediately after creation. :type user_id: int :type monetary_account_id: int :param name: The name of the CashRegister. Must be unique for this MonetaryAccount. :type name: str :param status: The status of the CashRegister. Can only be created or updated with PENDING_APPROVAL or CLOSED. :type status: str :param avatar_uuid: The UUID of the avatar of the CashRegister. Use the calls /attachment-public and /avatar to create a new Avatar and get its UUID. :type avatar_uuid: str :param location: The geolocation of the CashRegister. :type location: object_.Geolocation :param notification_filters: The types of notifications that will result in a push notification or URL callback for this CashRegister. :type notification_filters: list[object_.NotificationFilter] :param tab_text_waiting_screen: The tab text for waiting screen of CashRegister. :type tab_text_waiting_screen: list[object_.TabTextWaitingScreen] :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_NAME: name, cls.FIELD_STATUS: status, cls.FIELD_AVATAR_UUID: avatar_uuid, cls.FIELD_LOCATION: location, cls.FIELD_NOTIFICATION_FILTERS: notification_filters, cls.FIELD_TAB_TEXT_WAITING_SCREEN: tab_text_waiting_screen } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, name, status, avatar_uuid, monetary_account_id=None, location=None, notification_filters=None, tab_text_waiting_screen=None, custom_headers=None): """ Create a new CashRegister. Only an UserCompany can create a CashRegisters. They need to be created with status PENDING_APPROVAL, an bunq admin has to approve your CashRegister before you can use it. In the sandbox testing environment an CashRegister will be automatically approved immediately after creation. :type user_id: int :type monetary_account_id: int :param name: The name of the CashRegister. Must be unique for this MonetaryAccount. :type name: str :param status: The status of the CashRegister. Can only be created or updated with PENDING_APPROVAL or CLOSED. :type status: str :param avatar_uuid: The UUID of the avatar of the CashRegister. Use the calls /attachment-public and /avatar to create a new Avatar and get its UUID. :type avatar_uuid: str :param location: The geolocation of the CashRegister. :type location: object_.Geolocation :param notification_filters: The types of notifications that will result in a push notification or URL callback for this CashRegister. :type notification_filters: list[object_.NotificationFilter] :param tab_text_waiting_screen: The tab text for waiting screen of CashRegister. :type tab_text_waiting_screen: list[object_.TabTextWaitingScreen] :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_NAME: name, cls.FIELD_STATUS: status, cls.FIELD_AVATAR_UUID: avatar_uuid, cls.FIELD_LOCATION: location, cls.FIELD_NOTIFICATION_FILTERS: notification_filters, cls.FIELD_TAB_TEXT_WAITING_SCREEN: tab_text_waiting_screen } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "name", ",", "status", ",", "avatar_uuid", ",", "monetary_account_id", "=", "None", ",", "location", "=", "None", ",", "notification_filters", "=", "None", ",", "tab_text_waiting_screen", "=", "None", ",", "custom_headers", "=...
Create a new CashRegister. Only an UserCompany can create a CashRegisters. They need to be created with status PENDING_APPROVAL, an bunq admin has to approve your CashRegister before you can use it. In the sandbox testing environment an CashRegister will be automatically approved immediately after creation. :type user_id: int :type monetary_account_id: int :param name: The name of the CashRegister. Must be unique for this MonetaryAccount. :type name: str :param status: The status of the CashRegister. Can only be created or updated with PENDING_APPROVAL or CLOSED. :type status: str :param avatar_uuid: The UUID of the avatar of the CashRegister. Use the calls /attachment-public and /avatar to create a new Avatar and get its UUID. :type avatar_uuid: str :param location: The geolocation of the CashRegister. :type location: object_.Geolocation :param notification_filters: The types of notifications that will result in a push notification or URL callback for this CashRegister. :type notification_filters: list[object_.NotificationFilter] :param tab_text_waiting_screen: The tab text for waiting screen of CashRegister. :type tab_text_waiting_screen: list[object_.TabTextWaitingScreen] :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Create", "a", "new", "CashRegister", ".", "Only", "an", "UserCompany", "can", "create", "a", "CashRegisters", ".", "They", "need", "to", "be", "created", "with", "status", "PENDING_APPROVAL", "an", "bunq", "admin", "has", "to", "approve", "your", "CashRegiste...
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L6125-L6184
train
208,120
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
TabUsageMultiple.create
def create(cls, cash_register_id, description, status, amount_total, monetary_account_id=None, allow_amount_higher=None, allow_amount_lower=None, want_tip=None, minimum_age=None, require_address=None, redirect_url=None, visibility=None, expiration=None, tab_attachment=None, custom_headers=None): """ Create a TabUsageMultiple. On creation the status must be set to OPEN :type user_id: int :type monetary_account_id: int :type cash_register_id: int :param description: The description of the TabUsageMultiple. Maximum 9000 characters. Field is required but can be an empty string. :type description: str :param status: The status of the TabUsageMultiple. On creation the status must be set to OPEN. You can change the status from OPEN to PAYABLE. If the TabUsageMultiple gets paid the status will remain PAYABLE. :type status: str :param amount_total: The total amount of the Tab. Must be a positive amount. As long as the tab has the status OPEN you can change the total amount. This amount is not affected by the amounts of the TabItems. However, if you've created any TabItems for a Tab the sum of the amounts of these items must be equal to the total_amount of the Tab when you change its status to PAYABLE :type amount_total: object_.Amount :param allow_amount_higher: [DEPRECATED] Whether or not a higher amount can be paid. :type allow_amount_higher: bool :param allow_amount_lower: [DEPRECATED] Whether or not a lower amount can be paid. :type allow_amount_lower: bool :param want_tip: [DEPRECATED] Whether or not the user paying the Tab should be asked if he wants to give a tip. When want_tip is set to true, allow_amount_higher must also be set to true and allow_amount_lower must be false. :type want_tip: bool :param minimum_age: The minimum age of the user paying the Tab. :type minimum_age: int :param require_address: Whether a billing and shipping address must be provided when paying the Tab. Possible values are: BILLING, SHIPPING, BILLING_SHIPPING, NONE, OPTIONAL. Default is NONE. :type require_address: str :param redirect_url: The URL which the user is sent to after paying the Tab. :type redirect_url: str :param visibility: The visibility of a Tab. A Tab can be visible trough NearPay, the QR code of the CashRegister and its own QR code. :type visibility: object_.TabVisibility :param expiration: The moment when this Tab expires. Can be at most 365 days into the future. :type expiration: str :param tab_attachment: An array of attachments that describe the tab. Uploaded through the POST /user/{userid}/attachment-tab endpoint. :type tab_attachment: list[object_.BunqId] :type custom_headers: dict[str, str]|None :rtype: BunqResponseStr """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_DESCRIPTION: description, cls.FIELD_STATUS: status, cls.FIELD_AMOUNT_TOTAL: amount_total, cls.FIELD_ALLOW_AMOUNT_HIGHER: allow_amount_higher, cls.FIELD_ALLOW_AMOUNT_LOWER: allow_amount_lower, cls.FIELD_WANT_TIP: want_tip, cls.FIELD_MINIMUM_AGE: minimum_age, cls.FIELD_REQUIRE_ADDRESS: require_address, cls.FIELD_REDIRECT_URL: redirect_url, cls.FIELD_VISIBILITY: visibility, cls.FIELD_EXPIRATION: expiration, cls.FIELD_TAB_ATTACHMENT: tab_attachment } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id), cash_register_id) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseStr.cast_from_bunq_response( cls._process_for_uuid(response_raw) )
python
def create(cls, cash_register_id, description, status, amount_total, monetary_account_id=None, allow_amount_higher=None, allow_amount_lower=None, want_tip=None, minimum_age=None, require_address=None, redirect_url=None, visibility=None, expiration=None, tab_attachment=None, custom_headers=None): """ Create a TabUsageMultiple. On creation the status must be set to OPEN :type user_id: int :type monetary_account_id: int :type cash_register_id: int :param description: The description of the TabUsageMultiple. Maximum 9000 characters. Field is required but can be an empty string. :type description: str :param status: The status of the TabUsageMultiple. On creation the status must be set to OPEN. You can change the status from OPEN to PAYABLE. If the TabUsageMultiple gets paid the status will remain PAYABLE. :type status: str :param amount_total: The total amount of the Tab. Must be a positive amount. As long as the tab has the status OPEN you can change the total amount. This amount is not affected by the amounts of the TabItems. However, if you've created any TabItems for a Tab the sum of the amounts of these items must be equal to the total_amount of the Tab when you change its status to PAYABLE :type amount_total: object_.Amount :param allow_amount_higher: [DEPRECATED] Whether or not a higher amount can be paid. :type allow_amount_higher: bool :param allow_amount_lower: [DEPRECATED] Whether or not a lower amount can be paid. :type allow_amount_lower: bool :param want_tip: [DEPRECATED] Whether or not the user paying the Tab should be asked if he wants to give a tip. When want_tip is set to true, allow_amount_higher must also be set to true and allow_amount_lower must be false. :type want_tip: bool :param minimum_age: The minimum age of the user paying the Tab. :type minimum_age: int :param require_address: Whether a billing and shipping address must be provided when paying the Tab. Possible values are: BILLING, SHIPPING, BILLING_SHIPPING, NONE, OPTIONAL. Default is NONE. :type require_address: str :param redirect_url: The URL which the user is sent to after paying the Tab. :type redirect_url: str :param visibility: The visibility of a Tab. A Tab can be visible trough NearPay, the QR code of the CashRegister and its own QR code. :type visibility: object_.TabVisibility :param expiration: The moment when this Tab expires. Can be at most 365 days into the future. :type expiration: str :param tab_attachment: An array of attachments that describe the tab. Uploaded through the POST /user/{userid}/attachment-tab endpoint. :type tab_attachment: list[object_.BunqId] :type custom_headers: dict[str, str]|None :rtype: BunqResponseStr """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_DESCRIPTION: description, cls.FIELD_STATUS: status, cls.FIELD_AMOUNT_TOTAL: amount_total, cls.FIELD_ALLOW_AMOUNT_HIGHER: allow_amount_higher, cls.FIELD_ALLOW_AMOUNT_LOWER: allow_amount_lower, cls.FIELD_WANT_TIP: want_tip, cls.FIELD_MINIMUM_AGE: minimum_age, cls.FIELD_REQUIRE_ADDRESS: require_address, cls.FIELD_REDIRECT_URL: redirect_url, cls.FIELD_VISIBILITY: visibility, cls.FIELD_EXPIRATION: expiration, cls.FIELD_TAB_ATTACHMENT: tab_attachment } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id), cash_register_id) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseStr.cast_from_bunq_response( cls._process_for_uuid(response_raw) )
[ "def", "create", "(", "cls", ",", "cash_register_id", ",", "description", ",", "status", ",", "amount_total", ",", "monetary_account_id", "=", "None", ",", "allow_amount_higher", "=", "None", ",", "allow_amount_lower", "=", "None", ",", "want_tip", "=", "None", ...
Create a TabUsageMultiple. On creation the status must be set to OPEN :type user_id: int :type monetary_account_id: int :type cash_register_id: int :param description: The description of the TabUsageMultiple. Maximum 9000 characters. Field is required but can be an empty string. :type description: str :param status: The status of the TabUsageMultiple. On creation the status must be set to OPEN. You can change the status from OPEN to PAYABLE. If the TabUsageMultiple gets paid the status will remain PAYABLE. :type status: str :param amount_total: The total amount of the Tab. Must be a positive amount. As long as the tab has the status OPEN you can change the total amount. This amount is not affected by the amounts of the TabItems. However, if you've created any TabItems for a Tab the sum of the amounts of these items must be equal to the total_amount of the Tab when you change its status to PAYABLE :type amount_total: object_.Amount :param allow_amount_higher: [DEPRECATED] Whether or not a higher amount can be paid. :type allow_amount_higher: bool :param allow_amount_lower: [DEPRECATED] Whether or not a lower amount can be paid. :type allow_amount_lower: bool :param want_tip: [DEPRECATED] Whether or not the user paying the Tab should be asked if he wants to give a tip. When want_tip is set to true, allow_amount_higher must also be set to true and allow_amount_lower must be false. :type want_tip: bool :param minimum_age: The minimum age of the user paying the Tab. :type minimum_age: int :param require_address: Whether a billing and shipping address must be provided when paying the Tab. Possible values are: BILLING, SHIPPING, BILLING_SHIPPING, NONE, OPTIONAL. Default is NONE. :type require_address: str :param redirect_url: The URL which the user is sent to after paying the Tab. :type redirect_url: str :param visibility: The visibility of a Tab. A Tab can be visible trough NearPay, the QR code of the CashRegister and its own QR code. :type visibility: object_.TabVisibility :param expiration: The moment when this Tab expires. Can be at most 365 days into the future. :type expiration: str :param tab_attachment: An array of attachments that describe the tab. Uploaded through the POST /user/{userid}/attachment-tab endpoint. :type tab_attachment: list[object_.BunqId] :type custom_headers: dict[str, str]|None :rtype: BunqResponseStr
[ "Create", "a", "TabUsageMultiple", ".", "On", "creation", "the", "status", "must", "be", "set", "to", "OPEN" ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L7569-L7660
train
208,121
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
DeviceServer.get
def get(cls, device_server_id, custom_headers=None): """ Get one of your DeviceServers. :type api_context: context.ApiContext :type device_server_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseDeviceServer """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(device_server_id) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseDeviceServer.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_GET) )
python
def get(cls, device_server_id, custom_headers=None): """ Get one of your DeviceServers. :type api_context: context.ApiContext :type device_server_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseDeviceServer """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(device_server_id) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseDeviceServer.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_GET) )
[ "def", "get", "(", "cls", ",", "device_server_id", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "api_client", "=", "client", ".", "ApiClient", "(", "cls", ".", "_get_api_context", ...
Get one of your DeviceServers. :type api_context: context.ApiContext :type device_server_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseDeviceServer
[ "Get", "one", "of", "your", "DeviceServers", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L8329-L8349
train
208,122
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
Device.get
def get(cls, device_id, custom_headers=None): """ Get a single Device. A Device is either a DevicePhone or a DeviceServer. :type api_context: context.ApiContext :type device_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseDevice """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(device_id) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseDevice.cast_from_bunq_response( cls._from_json(response_raw) )
python
def get(cls, device_id, custom_headers=None): """ Get a single Device. A Device is either a DevicePhone or a DeviceServer. :type api_context: context.ApiContext :type device_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseDevice """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_READ.format(device_id) response_raw = api_client.get(endpoint_url, {}, custom_headers) return BunqResponseDevice.cast_from_bunq_response( cls._from_json(response_raw) )
[ "def", "get", "(", "cls", ",", "device_id", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "api_client", "=", "client", ".", "ApiClient", "(", "cls", ".", "_get_api_context", "(", ...
Get a single Device. A Device is either a DevicePhone or a DeviceServer. :type api_context: context.ApiContext :type device_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseDevice
[ "Get", "a", "single", "Device", ".", "A", "Device", "is", "either", "a", "DevicePhone", "or", "a", "DeviceServer", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L8482-L8502
train
208,123
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
DraftPayment.create
def create(cls, entries, number_of_required_accepts, monetary_account_id=None, status=None, previous_updated_timestamp=None, custom_headers=None): """ Create a new DraftPayment. :type user_id: int :type monetary_account_id: int :param entries: The list of entries in the DraftPayment. Each entry will result in a payment when the DraftPayment is accepted. :type entries: list[object_.DraftPaymentEntry] :param number_of_required_accepts: The number of accepts that are required for the draft payment to receive status ACCEPTED. Currently only 1 is valid. :type number_of_required_accepts: int :param status: The status of the DraftPayment. :type status: str :param previous_updated_timestamp: The last updated_timestamp that you received for this DraftPayment. This needs to be provided to prevent race conditions. :type previous_updated_timestamp: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_STATUS: status, cls.FIELD_ENTRIES: entries, cls.FIELD_PREVIOUS_UPDATED_TIMESTAMP: previous_updated_timestamp, cls.FIELD_NUMBER_OF_REQUIRED_ACCEPTS: number_of_required_accepts } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, entries, number_of_required_accepts, monetary_account_id=None, status=None, previous_updated_timestamp=None, custom_headers=None): """ Create a new DraftPayment. :type user_id: int :type monetary_account_id: int :param entries: The list of entries in the DraftPayment. Each entry will result in a payment when the DraftPayment is accepted. :type entries: list[object_.DraftPaymentEntry] :param number_of_required_accepts: The number of accepts that are required for the draft payment to receive status ACCEPTED. Currently only 1 is valid. :type number_of_required_accepts: int :param status: The status of the DraftPayment. :type status: str :param previous_updated_timestamp: The last updated_timestamp that you received for this DraftPayment. This needs to be provided to prevent race conditions. :type previous_updated_timestamp: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_STATUS: status, cls.FIELD_ENTRIES: entries, cls.FIELD_PREVIOUS_UPDATED_TIMESTAMP: previous_updated_timestamp, cls.FIELD_NUMBER_OF_REQUIRED_ACCEPTS: number_of_required_accepts } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "entries", ",", "number_of_required_accepts", ",", "monetary_account_id", "=", "None", ",", "status", "=", "None", ",", "previous_updated_timestamp", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_heade...
Create a new DraftPayment. :type user_id: int :type monetary_account_id: int :param entries: The list of entries in the DraftPayment. Each entry will result in a payment when the DraftPayment is accepted. :type entries: list[object_.DraftPaymentEntry] :param number_of_required_accepts: The number of accepts that are required for the draft payment to receive status ACCEPTED. Currently only 1 is valid. :type number_of_required_accepts: int :param status: The status of the DraftPayment. :type status: str :param previous_updated_timestamp: The last updated_timestamp that you received for this DraftPayment. This needs to be provided to prevent race conditions. :type previous_updated_timestamp: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Create", "a", "new", "DraftPayment", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L8659-L8707
train
208,124
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
DraftShareInviteApiKey.update
def update(cls, draft_share_invite_api_key_id, status=None, sub_status=None, expiration=None, custom_headers=None): """ Update a draft share invite. When sending status CANCELLED it is possible to cancel the draft share invite. :type user_id: int :type draft_share_invite_api_key_id: int :param status: The status of the draft share invite. Can be CANCELLED (the user cancels the draft share before it's used). :type status: str :param sub_status: The sub-status of the draft share invite. Can be NONE, ACCEPTED or REJECTED. :type sub_status: str :param expiration: The moment when this draft share invite expires. :type expiration: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseDraftShareInviteApiKey """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_STATUS: status, cls.FIELD_SUB_STATUS: sub_status, cls.FIELD_EXPIRATION: expiration } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(), draft_share_invite_api_key_id) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseDraftShareInviteApiKey.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_PUT) )
python
def update(cls, draft_share_invite_api_key_id, status=None, sub_status=None, expiration=None, custom_headers=None): """ Update a draft share invite. When sending status CANCELLED it is possible to cancel the draft share invite. :type user_id: int :type draft_share_invite_api_key_id: int :param status: The status of the draft share invite. Can be CANCELLED (the user cancels the draft share before it's used). :type status: str :param sub_status: The sub-status of the draft share invite. Can be NONE, ACCEPTED or REJECTED. :type sub_status: str :param expiration: The moment when this draft share invite expires. :type expiration: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseDraftShareInviteApiKey """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_STATUS: status, cls.FIELD_SUB_STATUS: sub_status, cls.FIELD_EXPIRATION: expiration } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(), draft_share_invite_api_key_id) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseDraftShareInviteApiKey.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_PUT) )
[ "def", "update", "(", "cls", ",", "draft_share_invite_api_key_id", ",", "status", "=", "None", ",", "sub_status", "=", "None", ",", "expiration", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_he...
Update a draft share invite. When sending status CANCELLED it is possible to cancel the draft share invite. :type user_id: int :type draft_share_invite_api_key_id: int :param status: The status of the draft share invite. Can be CANCELLED (the user cancels the draft share before it's used). :type status: str :param sub_status: The sub-status of the draft share invite. Can be NONE, ACCEPTED or REJECTED. :type sub_status: str :param expiration: The moment when this draft share invite expires. :type expiration: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseDraftShareInviteApiKey
[ "Update", "a", "draft", "share", "invite", ".", "When", "sending", "status", "CANCELLED", "it", "is", "possible", "to", "cancel", "the", "draft", "share", "invite", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L9315-L9357
train
208,125
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
RequestInquiryBatch.create
def create(cls, request_inquiries, total_amount_inquired, monetary_account_id=None, status=None, event_id=None, custom_headers=None): """ Create a request batch by sending an array of single request objects, that will become part of the batch. :type user_id: int :type monetary_account_id: int :param request_inquiries: The list of request inquiries we want to send in 1 batch. :type request_inquiries: list[RequestInquiry] :param total_amount_inquired: The total amount originally inquired for this batch. :type total_amount_inquired: object_.Amount :param status: The status of the request. :type status: str :param event_id: The ID of the associated event if the request batch was made using 'split the bill'. :type event_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_REQUEST_INQUIRIES: request_inquiries, cls.FIELD_STATUS: status, cls.FIELD_TOTAL_AMOUNT_INQUIRED: total_amount_inquired, cls.FIELD_EVENT_ID: event_id } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, request_inquiries, total_amount_inquired, monetary_account_id=None, status=None, event_id=None, custom_headers=None): """ Create a request batch by sending an array of single request objects, that will become part of the batch. :type user_id: int :type monetary_account_id: int :param request_inquiries: The list of request inquiries we want to send in 1 batch. :type request_inquiries: list[RequestInquiry] :param total_amount_inquired: The total amount originally inquired for this batch. :type total_amount_inquired: object_.Amount :param status: The status of the request. :type status: str :param event_id: The ID of the associated event if the request batch was made using 'split the bill'. :type event_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_REQUEST_INQUIRIES: request_inquiries, cls.FIELD_STATUS: status, cls.FIELD_TOTAL_AMOUNT_INQUIRED: total_amount_inquired, cls.FIELD_EVENT_ID: event_id } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "request_inquiries", ",", "total_amount_inquired", ",", "monetary_account_id", "=", "None", ",", "status", "=", "None", ",", "event_id", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", ...
Create a request batch by sending an array of single request objects, that will become part of the batch. :type user_id: int :type monetary_account_id: int :param request_inquiries: The list of request inquiries we want to send in 1 batch. :type request_inquiries: list[RequestInquiry] :param total_amount_inquired: The total amount originally inquired for this batch. :type total_amount_inquired: object_.Amount :param status: The status of the request. :type status: str :param event_id: The ID of the associated event if the request batch was made using 'split the bill'. :type event_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Create", "a", "request", "batch", "by", "sending", "an", "array", "of", "single", "request", "objects", "that", "will", "become", "part", "of", "the", "batch", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L11951-L11998
train
208,126
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
RequestInquiry.create
def create(cls, amount_inquired, counterparty_alias, description, allow_bunqme, monetary_account_id=None, attachment=None, merchant_reference=None, status=None, minimum_age=None, require_address=None, want_tip=None, allow_amount_lower=None, allow_amount_higher=None, redirect_url=None, event_id=None, custom_headers=None): """ Create a new payment request. :type user_id: int :type monetary_account_id: int :param amount_inquired: The Amount requested to be paid by the person the RequestInquiry is sent to. Must be bigger than 0. :type amount_inquired: object_.Amount :param counterparty_alias: The Alias of the party we are requesting the money from. Can be an Alias of type EMAIL, PHONE_NUMBER or IBAN. In case the EMAIL or PHONE_NUMBER Alias does not refer to a bunq monetary account, 'allow_bunqme' needs to be 'true' in order to trigger the creation of a bunq.me request. Otherwise no request inquiry will be sent. :type counterparty_alias: object_.Pointer :param description: The description for the RequestInquiry. Maximum 9000 characters. Field is required but can be an empty string. :type description: str :param allow_bunqme: Whether or not sending a bunq.me request is allowed. :type allow_bunqme: bool :param attachment: The Attachments to attach to the RequestInquiry. :type attachment: list[object_.BunqId] :param merchant_reference: Optional data to be included with the RequestInquiry specific to the merchant. Has to be unique for the same source MonetaryAccount. :type merchant_reference: str :param status: The status of the RequestInquiry. Ignored in POST requests but can be used for revoking (cancelling) the RequestInquiry by setting REVOKED with a PUT request. :type status: str :param minimum_age: The minimum age the user accepting the RequestInquiry must have. Defaults to not checking. If set, must be between 12 and 100 inclusive. :type minimum_age: int :param require_address: Whether a billing and shipping address must be provided when paying the request. Possible values are: BILLING, SHIPPING, BILLING_SHIPPING, NONE, OPTIONAL. Default is NONE. :type require_address: str :param want_tip: [DEPRECATED] Whether or not the accepting user can give an extra tip on top of the requested Amount. Defaults to false. :type want_tip: bool :param allow_amount_lower: [DEPRECATED] Whether or not the accepting user can choose to accept with a lower amount than requested. Defaults to false. :type allow_amount_lower: bool :param allow_amount_higher: [DEPRECATED] Whether or not the accepting user can choose to accept with a higher amount than requested. Defaults to false. :type allow_amount_higher: bool :param redirect_url: The URL which the user is sent to after accepting or rejecting the Request. :type redirect_url: str :param event_id: The ID of the associated event if the request was made using 'split the bill'. :type event_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_AMOUNT_INQUIRED: amount_inquired, cls.FIELD_COUNTERPARTY_ALIAS: counterparty_alias, cls.FIELD_DESCRIPTION: description, cls.FIELD_ATTACHMENT: attachment, cls.FIELD_MERCHANT_REFERENCE: merchant_reference, cls.FIELD_STATUS: status, cls.FIELD_MINIMUM_AGE: minimum_age, cls.FIELD_REQUIRE_ADDRESS: require_address, cls.FIELD_WANT_TIP: want_tip, cls.FIELD_ALLOW_AMOUNT_LOWER: allow_amount_lower, cls.FIELD_ALLOW_AMOUNT_HIGHER: allow_amount_higher, cls.FIELD_ALLOW_BUNQME: allow_bunqme, cls.FIELD_REDIRECT_URL: redirect_url, cls.FIELD_EVENT_ID: event_id } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, amount_inquired, counterparty_alias, description, allow_bunqme, monetary_account_id=None, attachment=None, merchant_reference=None, status=None, minimum_age=None, require_address=None, want_tip=None, allow_amount_lower=None, allow_amount_higher=None, redirect_url=None, event_id=None, custom_headers=None): """ Create a new payment request. :type user_id: int :type monetary_account_id: int :param amount_inquired: The Amount requested to be paid by the person the RequestInquiry is sent to. Must be bigger than 0. :type amount_inquired: object_.Amount :param counterparty_alias: The Alias of the party we are requesting the money from. Can be an Alias of type EMAIL, PHONE_NUMBER or IBAN. In case the EMAIL or PHONE_NUMBER Alias does not refer to a bunq monetary account, 'allow_bunqme' needs to be 'true' in order to trigger the creation of a bunq.me request. Otherwise no request inquiry will be sent. :type counterparty_alias: object_.Pointer :param description: The description for the RequestInquiry. Maximum 9000 characters. Field is required but can be an empty string. :type description: str :param allow_bunqme: Whether or not sending a bunq.me request is allowed. :type allow_bunqme: bool :param attachment: The Attachments to attach to the RequestInquiry. :type attachment: list[object_.BunqId] :param merchant_reference: Optional data to be included with the RequestInquiry specific to the merchant. Has to be unique for the same source MonetaryAccount. :type merchant_reference: str :param status: The status of the RequestInquiry. Ignored in POST requests but can be used for revoking (cancelling) the RequestInquiry by setting REVOKED with a PUT request. :type status: str :param minimum_age: The minimum age the user accepting the RequestInquiry must have. Defaults to not checking. If set, must be between 12 and 100 inclusive. :type minimum_age: int :param require_address: Whether a billing and shipping address must be provided when paying the request. Possible values are: BILLING, SHIPPING, BILLING_SHIPPING, NONE, OPTIONAL. Default is NONE. :type require_address: str :param want_tip: [DEPRECATED] Whether or not the accepting user can give an extra tip on top of the requested Amount. Defaults to false. :type want_tip: bool :param allow_amount_lower: [DEPRECATED] Whether or not the accepting user can choose to accept with a lower amount than requested. Defaults to false. :type allow_amount_lower: bool :param allow_amount_higher: [DEPRECATED] Whether or not the accepting user can choose to accept with a higher amount than requested. Defaults to false. :type allow_amount_higher: bool :param redirect_url: The URL which the user is sent to after accepting or rejecting the Request. :type redirect_url: str :param event_id: The ID of the associated event if the request was made using 'split the bill'. :type event_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_AMOUNT_INQUIRED: amount_inquired, cls.FIELD_COUNTERPARTY_ALIAS: counterparty_alias, cls.FIELD_DESCRIPTION: description, cls.FIELD_ATTACHMENT: attachment, cls.FIELD_MERCHANT_REFERENCE: merchant_reference, cls.FIELD_STATUS: status, cls.FIELD_MINIMUM_AGE: minimum_age, cls.FIELD_REQUIRE_ADDRESS: require_address, cls.FIELD_WANT_TIP: want_tip, cls.FIELD_ALLOW_AMOUNT_LOWER: allow_amount_lower, cls.FIELD_ALLOW_AMOUNT_HIGHER: allow_amount_higher, cls.FIELD_ALLOW_BUNQME: allow_bunqme, cls.FIELD_REDIRECT_URL: redirect_url, cls.FIELD_EVENT_ID: event_id } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "amount_inquired", ",", "counterparty_alias", ",", "description", ",", "allow_bunqme", ",", "monetary_account_id", "=", "None", ",", "attachment", "=", "None", ",", "merchant_reference", "=", "None", ",", "status", "=", "None", ...
Create a new payment request. :type user_id: int :type monetary_account_id: int :param amount_inquired: The Amount requested to be paid by the person the RequestInquiry is sent to. Must be bigger than 0. :type amount_inquired: object_.Amount :param counterparty_alias: The Alias of the party we are requesting the money from. Can be an Alias of type EMAIL, PHONE_NUMBER or IBAN. In case the EMAIL or PHONE_NUMBER Alias does not refer to a bunq monetary account, 'allow_bunqme' needs to be 'true' in order to trigger the creation of a bunq.me request. Otherwise no request inquiry will be sent. :type counterparty_alias: object_.Pointer :param description: The description for the RequestInquiry. Maximum 9000 characters. Field is required but can be an empty string. :type description: str :param allow_bunqme: Whether or not sending a bunq.me request is allowed. :type allow_bunqme: bool :param attachment: The Attachments to attach to the RequestInquiry. :type attachment: list[object_.BunqId] :param merchant_reference: Optional data to be included with the RequestInquiry specific to the merchant. Has to be unique for the same source MonetaryAccount. :type merchant_reference: str :param status: The status of the RequestInquiry. Ignored in POST requests but can be used for revoking (cancelling) the RequestInquiry by setting REVOKED with a PUT request. :type status: str :param minimum_age: The minimum age the user accepting the RequestInquiry must have. Defaults to not checking. If set, must be between 12 and 100 inclusive. :type minimum_age: int :param require_address: Whether a billing and shipping address must be provided when paying the request. Possible values are: BILLING, SHIPPING, BILLING_SHIPPING, NONE, OPTIONAL. Default is NONE. :type require_address: str :param want_tip: [DEPRECATED] Whether or not the accepting user can give an extra tip on top of the requested Amount. Defaults to false. :type want_tip: bool :param allow_amount_lower: [DEPRECATED] Whether or not the accepting user can choose to accept with a lower amount than requested. Defaults to false. :type allow_amount_lower: bool :param allow_amount_higher: [DEPRECATED] Whether or not the accepting user can choose to accept with a higher amount than requested. Defaults to false. :type allow_amount_higher: bool :param redirect_url: The URL which the user is sent to after accepting or rejecting the Request. :type redirect_url: str :param event_id: The ID of the associated event if the request was made using 'split the bill'. :type event_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Create", "a", "new", "payment", "request", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L12379-L12478
train
208,127
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
RequestInquiry.update
def update(cls, request_inquiry_id, monetary_account_id=None, status=None, custom_headers=None): """ Revoke a request for payment, by updating the status to REVOKED. :type user_id: int :type monetary_account_id: int :type request_inquiry_id: int :param status: The status of the RequestInquiry. Ignored in POST requests but can be used for revoking (cancelling) the RequestInquiry by setting REVOKED with a PUT request. :type status: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseRequestInquiry """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_STATUS: status } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id), request_inquiry_id) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseRequestInquiry.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_PUT) )
python
def update(cls, request_inquiry_id, monetary_account_id=None, status=None, custom_headers=None): """ Revoke a request for payment, by updating the status to REVOKED. :type user_id: int :type monetary_account_id: int :type request_inquiry_id: int :param status: The status of the RequestInquiry. Ignored in POST requests but can be used for revoking (cancelling) the RequestInquiry by setting REVOKED with a PUT request. :type status: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseRequestInquiry """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_STATUS: status } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id), request_inquiry_id) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseRequestInquiry.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_PUT) )
[ "def", "update", "(", "cls", ",", "request_inquiry_id", ",", "monetary_account_id", "=", "None", ",", "status", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "api_client...
Revoke a request for payment, by updating the status to REVOKED. :type user_id: int :type monetary_account_id: int :type request_inquiry_id: int :param status: The status of the RequestInquiry. Ignored in POST requests but can be used for revoking (cancelling) the RequestInquiry by setting REVOKED with a PUT request. :type status: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseRequestInquiry
[ "Revoke", "a", "request", "for", "payment", "by", "updating", "the", "status", "to", "REVOKED", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L12481-L12519
train
208,128
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
RequestResponse.update
def update(cls, request_response_id, monetary_account_id=None, amount_responded=None, status=None, address_shipping=None, address_billing=None, custom_headers=None): """ Update the status to accept or reject the RequestResponse. :type user_id: int :type monetary_account_id: int :type request_response_id: int :param amount_responded: The Amount the user decides to pay. :type amount_responded: object_.Amount :param status: The responding status of the RequestResponse. Can be ACCEPTED or REJECTED. :type status: str :param address_shipping: The shipping Address to return to the user who created the RequestInquiry. Should only be provided if 'require_address' is set to SHIPPING, BILLING_SHIPPING or OPTIONAL. :type address_shipping: object_.Address :param address_billing: The billing Address to return to the user who created the RequestInquiry. Should only be provided if 'require_address' is set to BILLING, BILLING_SHIPPING or OPTIONAL. :type address_billing: object_.Address :type custom_headers: dict[str, str]|None :rtype: BunqResponseRequestResponse """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_AMOUNT_RESPONDED: amount_responded, cls.FIELD_STATUS: status, cls.FIELD_ADDRESS_SHIPPING: address_shipping, cls.FIELD_ADDRESS_BILLING: address_billing } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id), request_response_id) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseRequestResponse.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_PUT) )
python
def update(cls, request_response_id, monetary_account_id=None, amount_responded=None, status=None, address_shipping=None, address_billing=None, custom_headers=None): """ Update the status to accept or reject the RequestResponse. :type user_id: int :type monetary_account_id: int :type request_response_id: int :param amount_responded: The Amount the user decides to pay. :type amount_responded: object_.Amount :param status: The responding status of the RequestResponse. Can be ACCEPTED or REJECTED. :type status: str :param address_shipping: The shipping Address to return to the user who created the RequestInquiry. Should only be provided if 'require_address' is set to SHIPPING, BILLING_SHIPPING or OPTIONAL. :type address_shipping: object_.Address :param address_billing: The billing Address to return to the user who created the RequestInquiry. Should only be provided if 'require_address' is set to BILLING, BILLING_SHIPPING or OPTIONAL. :type address_billing: object_.Address :type custom_headers: dict[str, str]|None :rtype: BunqResponseRequestResponse """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_AMOUNT_RESPONDED: amount_responded, cls.FIELD_STATUS: status, cls.FIELD_ADDRESS_SHIPPING: address_shipping, cls.FIELD_ADDRESS_BILLING: address_billing } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id), request_response_id) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseRequestResponse.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_PUT) )
[ "def", "update", "(", "cls", ",", "request_response_id", ",", "monetary_account_id", "=", "None", ",", "amount_responded", "=", "None", ",", "status", "=", "None", ",", "address_shipping", "=", "None", ",", "address_billing", "=", "None", ",", "custom_headers", ...
Update the status to accept or reject the RequestResponse. :type user_id: int :type monetary_account_id: int :type request_response_id: int :param amount_responded: The Amount the user decides to pay. :type amount_responded: object_.Amount :param status: The responding status of the RequestResponse. Can be ACCEPTED or REJECTED. :type status: str :param address_shipping: The shipping Address to return to the user who created the RequestInquiry. Should only be provided if 'require_address' is set to SHIPPING, BILLING_SHIPPING or OPTIONAL. :type address_shipping: object_.Address :param address_billing: The billing Address to return to the user who created the RequestInquiry. Should only be provided if 'require_address' is set to BILLING, BILLING_SHIPPING or OPTIONAL. :type address_billing: object_.Address :type custom_headers: dict[str, str]|None :rtype: BunqResponseRequestResponse
[ "Update", "the", "status", "to", "accept", "or", "reject", "the", "RequestResponse", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L13047-L13098
train
208,129
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
ShareInviteBankInquiry.create
def create(cls, counter_user_alias, share_detail, status, monetary_account_id=None, draft_share_invite_bank_id=None, share_type=None, start_date=None, end_date=None, custom_headers=None): """ Create a new share inquiry for a monetary account, specifying the permission the other bunq user will have on it. :type user_id: int :type monetary_account_id: int :param counter_user_alias: The pointer of the user to share with. :type counter_user_alias: object_.Pointer :param share_detail: The share details. Only one of these objects may be passed. :type share_detail: object_.ShareDetail :param status: The status of the share. Can be PENDING, REVOKED (the user deletes the share inquiry before it's accepted), ACCEPTED, CANCELLED (the user deletes an active share) or CANCELLATION_PENDING, CANCELLATION_ACCEPTED, CANCELLATION_REJECTED (for canceling mutual connects). :type status: str :param draft_share_invite_bank_id: The id of the draft share invite bank. :type draft_share_invite_bank_id: int :param share_type: The share type, either STANDARD or MUTUAL. :type share_type: str :param start_date: The start date of this share. :type start_date: str :param end_date: The expiration date of this share. :type end_date: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_COUNTER_USER_ALIAS: counter_user_alias, cls.FIELD_DRAFT_SHARE_INVITE_BANK_ID: draft_share_invite_bank_id, cls.FIELD_SHARE_DETAIL: share_detail, cls.FIELD_STATUS: status, cls.FIELD_SHARE_TYPE: share_type, cls.FIELD_START_DATE: start_date, cls.FIELD_END_DATE: end_date } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, counter_user_alias, share_detail, status, monetary_account_id=None, draft_share_invite_bank_id=None, share_type=None, start_date=None, end_date=None, custom_headers=None): """ Create a new share inquiry for a monetary account, specifying the permission the other bunq user will have on it. :type user_id: int :type monetary_account_id: int :param counter_user_alias: The pointer of the user to share with. :type counter_user_alias: object_.Pointer :param share_detail: The share details. Only one of these objects may be passed. :type share_detail: object_.ShareDetail :param status: The status of the share. Can be PENDING, REVOKED (the user deletes the share inquiry before it's accepted), ACCEPTED, CANCELLED (the user deletes an active share) or CANCELLATION_PENDING, CANCELLATION_ACCEPTED, CANCELLATION_REJECTED (for canceling mutual connects). :type status: str :param draft_share_invite_bank_id: The id of the draft share invite bank. :type draft_share_invite_bank_id: int :param share_type: The share type, either STANDARD or MUTUAL. :type share_type: str :param start_date: The start date of this share. :type start_date: str :param end_date: The expiration date of this share. :type end_date: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_COUNTER_USER_ALIAS: counter_user_alias, cls.FIELD_DRAFT_SHARE_INVITE_BANK_ID: draft_share_invite_bank_id, cls.FIELD_SHARE_DETAIL: share_detail, cls.FIELD_STATUS: status, cls.FIELD_SHARE_TYPE: share_type, cls.FIELD_START_DATE: start_date, cls.FIELD_END_DATE: end_date } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id)) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "counter_user_alias", ",", "share_detail", ",", "status", ",", "monetary_account_id", "=", "None", ",", "draft_share_invite_bank_id", "=", "None", ",", "share_type", "=", "None", ",", "start_date", "=", "None", ",", "end_date", ...
Create a new share inquiry for a monetary account, specifying the permission the other bunq user will have on it. :type user_id: int :type monetary_account_id: int :param counter_user_alias: The pointer of the user to share with. :type counter_user_alias: object_.Pointer :param share_detail: The share details. Only one of these objects may be passed. :type share_detail: object_.ShareDetail :param status: The status of the share. Can be PENDING, REVOKED (the user deletes the share inquiry before it's accepted), ACCEPTED, CANCELLED (the user deletes an active share) or CANCELLATION_PENDING, CANCELLATION_ACCEPTED, CANCELLATION_REJECTED (for canceling mutual connects). :type status: str :param draft_share_invite_bank_id: The id of the draft share invite bank. :type draft_share_invite_bank_id: int :param share_type: The share type, either STANDARD or MUTUAL. :type share_type: str :param start_date: The start date of this share. :type start_date: str :param end_date: The expiration date of this share. :type end_date: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Create", "a", "new", "share", "inquiry", "for", "a", "monetary", "account", "specifying", "the", "permission", "the", "other", "bunq", "user", "will", "have", "on", "it", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L14338-L14398
train
208,130
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
User.list
def list(cls, params=None, custom_headers=None): """ Get a collection of all available users. :type params: dict[str, str]|None :type custom_headers: dict[str, str]|None :rtype: BunqResponseUserList """ if params is None: params = {} if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_LISTING response_raw = api_client.get(endpoint_url, params, custom_headers) return BunqResponseUserList.cast_from_bunq_response( cls._from_json_list(response_raw) )
python
def list(cls, params=None, custom_headers=None): """ Get a collection of all available users. :type params: dict[str, str]|None :type custom_headers: dict[str, str]|None :rtype: BunqResponseUserList """ if params is None: params = {} if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) endpoint_url = cls._ENDPOINT_URL_LISTING response_raw = api_client.get(endpoint_url, params, custom_headers) return BunqResponseUserList.cast_from_bunq_response( cls._from_json_list(response_raw) )
[ "def", "list", "(", "cls", ",", "params", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "api_client", ...
Get a collection of all available users. :type params: dict[str, str]|None :type custom_headers: dict[str, str]|None :rtype: BunqResponseUserList
[ "Get", "a", "collection", "of", "all", "available", "users", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L28512-L28534
train
208,131
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
UserPerson.update
def update(cls, first_name=None, middle_name=None, last_name=None, public_nick_name=None, address_main=None, address_postal=None, avatar_uuid=None, tax_resident=None, document_type=None, document_number=None, document_country_of_issuance=None, document_front_attachment_id=None, document_back_attachment_id=None, date_of_birth=None, place_of_birth=None, country_of_birth=None, nationality=None, language=None, region=None, gender=None, status=None, sub_status=None, legal_guardian_alias=None, session_timeout=None, card_ids=None, card_limits=None, daily_limit_without_confirmation_login=None, notification_filters=None, display_name=None, custom_headers=None): """ Modify a specific person object's data. :type user_person_id: int :param first_name: The person's first name. :type first_name: str :param middle_name: The person's middle name. :type middle_name: str :param last_name: The person's last name. :type last_name: str :param public_nick_name: The person's public nick name. :type public_nick_name: str :param address_main: The user's main address. :type address_main: object_.Address :param address_postal: The person's postal address. :type address_postal: object_.Address :param avatar_uuid: The public UUID of the user's avatar. :type avatar_uuid: str :param tax_resident: The user's tax residence numbers for different countries. :type tax_resident: list[object_.TaxResident] :param document_type: The type of identification document the person registered with. :type document_type: str :param document_number: The identification document number the person registered with. :type document_number: str :param document_country_of_issuance: The country which issued the identification document the person registered with. :type document_country_of_issuance: str :param document_front_attachment_id: The reference to the uploaded picture/scan of the front side of the identification document. :type document_front_attachment_id: int :param document_back_attachment_id: The reference to the uploaded picture/scan of the back side of the identification document. :type document_back_attachment_id: int :param date_of_birth: The person's date of birth. Accepts ISO8601 date formats. :type date_of_birth: str :param place_of_birth: The person's place of birth. :type place_of_birth: str :param country_of_birth: The person's country of birth. Formatted as a SO 3166-1 alpha-2 country code. :type country_of_birth: str :param nationality: The person's nationality. Formatted as a SO 3166-1 alpha-2 country code. :type nationality: str :param language: The person's preferred language. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type language: str :param region: The person's preferred region. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type region: str :param gender: The person's gender. Can be: MALE, FEMALE and UNKNOWN. :type gender: str :param status: The user status. You are not allowed to update the status via PUT. :type status: str :param sub_status: The user sub-status. Can be updated to SUBMIT if status is RECOVERY. :type sub_status: str :param legal_guardian_alias: The legal guardian of the user. Required for minors. :type legal_guardian_alias: object_.Pointer :param session_timeout: The setting for the session timeout of the user in seconds. :type session_timeout: int :param card_ids: Card ids used for centralized card limits. :type card_ids: list[object_.BunqId] :param card_limits: The centralized limits for user's cards. :type card_limits: list[object_.CardLimit] :param daily_limit_without_confirmation_login: The amount the user can pay in the session without asking for credentials. :type daily_limit_without_confirmation_login: object_.Amount :param notification_filters: The types of notifications that will result in a push notification or URL callback for this UserPerson. :type notification_filters: list[object_.NotificationFilter] :param display_name: The person's legal name. Available legal names can be listed via the 'user/{user_id}/legal-name' endpoint. :type display_name: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_FIRST_NAME: first_name, cls.FIELD_MIDDLE_NAME: middle_name, cls.FIELD_LAST_NAME: last_name, cls.FIELD_PUBLIC_NICK_NAME: public_nick_name, cls.FIELD_ADDRESS_MAIN: address_main, cls.FIELD_ADDRESS_POSTAL: address_postal, cls.FIELD_AVATAR_UUID: avatar_uuid, cls.FIELD_TAX_RESIDENT: tax_resident, cls.FIELD_DOCUMENT_TYPE: document_type, cls.FIELD_DOCUMENT_NUMBER: document_number, cls.FIELD_DOCUMENT_COUNTRY_OF_ISSUANCE: document_country_of_issuance, cls.FIELD_DOCUMENT_FRONT_ATTACHMENT_ID: document_front_attachment_id, cls.FIELD_DOCUMENT_BACK_ATTACHMENT_ID: document_back_attachment_id, cls.FIELD_DATE_OF_BIRTH: date_of_birth, cls.FIELD_PLACE_OF_BIRTH: place_of_birth, cls.FIELD_COUNTRY_OF_BIRTH: country_of_birth, cls.FIELD_NATIONALITY: nationality, cls.FIELD_LANGUAGE: language, cls.FIELD_REGION: region, cls.FIELD_GENDER: gender, cls.FIELD_STATUS: status, cls.FIELD_SUB_STATUS: sub_status, cls.FIELD_LEGAL_GUARDIAN_ALIAS: legal_guardian_alias, cls.FIELD_SESSION_TIMEOUT: session_timeout, cls.FIELD_CARD_IDS: card_ids, cls.FIELD_CARD_LIMITS: card_limits, cls.FIELD_DAILY_LIMIT_WITHOUT_CONFIRMATION_LOGIN: daily_limit_without_confirmation_login, cls.FIELD_NOTIFICATION_FILTERS: notification_filters, cls.FIELD_DISPLAY_NAME: display_name } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id()) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def update(cls, first_name=None, middle_name=None, last_name=None, public_nick_name=None, address_main=None, address_postal=None, avatar_uuid=None, tax_resident=None, document_type=None, document_number=None, document_country_of_issuance=None, document_front_attachment_id=None, document_back_attachment_id=None, date_of_birth=None, place_of_birth=None, country_of_birth=None, nationality=None, language=None, region=None, gender=None, status=None, sub_status=None, legal_guardian_alias=None, session_timeout=None, card_ids=None, card_limits=None, daily_limit_without_confirmation_login=None, notification_filters=None, display_name=None, custom_headers=None): """ Modify a specific person object's data. :type user_person_id: int :param first_name: The person's first name. :type first_name: str :param middle_name: The person's middle name. :type middle_name: str :param last_name: The person's last name. :type last_name: str :param public_nick_name: The person's public nick name. :type public_nick_name: str :param address_main: The user's main address. :type address_main: object_.Address :param address_postal: The person's postal address. :type address_postal: object_.Address :param avatar_uuid: The public UUID of the user's avatar. :type avatar_uuid: str :param tax_resident: The user's tax residence numbers for different countries. :type tax_resident: list[object_.TaxResident] :param document_type: The type of identification document the person registered with. :type document_type: str :param document_number: The identification document number the person registered with. :type document_number: str :param document_country_of_issuance: The country which issued the identification document the person registered with. :type document_country_of_issuance: str :param document_front_attachment_id: The reference to the uploaded picture/scan of the front side of the identification document. :type document_front_attachment_id: int :param document_back_attachment_id: The reference to the uploaded picture/scan of the back side of the identification document. :type document_back_attachment_id: int :param date_of_birth: The person's date of birth. Accepts ISO8601 date formats. :type date_of_birth: str :param place_of_birth: The person's place of birth. :type place_of_birth: str :param country_of_birth: The person's country of birth. Formatted as a SO 3166-1 alpha-2 country code. :type country_of_birth: str :param nationality: The person's nationality. Formatted as a SO 3166-1 alpha-2 country code. :type nationality: str :param language: The person's preferred language. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type language: str :param region: The person's preferred region. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type region: str :param gender: The person's gender. Can be: MALE, FEMALE and UNKNOWN. :type gender: str :param status: The user status. You are not allowed to update the status via PUT. :type status: str :param sub_status: The user sub-status. Can be updated to SUBMIT if status is RECOVERY. :type sub_status: str :param legal_guardian_alias: The legal guardian of the user. Required for minors. :type legal_guardian_alias: object_.Pointer :param session_timeout: The setting for the session timeout of the user in seconds. :type session_timeout: int :param card_ids: Card ids used for centralized card limits. :type card_ids: list[object_.BunqId] :param card_limits: The centralized limits for user's cards. :type card_limits: list[object_.CardLimit] :param daily_limit_without_confirmation_login: The amount the user can pay in the session without asking for credentials. :type daily_limit_without_confirmation_login: object_.Amount :param notification_filters: The types of notifications that will result in a push notification or URL callback for this UserPerson. :type notification_filters: list[object_.NotificationFilter] :param display_name: The person's legal name. Available legal names can be listed via the 'user/{user_id}/legal-name' endpoint. :type display_name: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_FIRST_NAME: first_name, cls.FIELD_MIDDLE_NAME: middle_name, cls.FIELD_LAST_NAME: last_name, cls.FIELD_PUBLIC_NICK_NAME: public_nick_name, cls.FIELD_ADDRESS_MAIN: address_main, cls.FIELD_ADDRESS_POSTAL: address_postal, cls.FIELD_AVATAR_UUID: avatar_uuid, cls.FIELD_TAX_RESIDENT: tax_resident, cls.FIELD_DOCUMENT_TYPE: document_type, cls.FIELD_DOCUMENT_NUMBER: document_number, cls.FIELD_DOCUMENT_COUNTRY_OF_ISSUANCE: document_country_of_issuance, cls.FIELD_DOCUMENT_FRONT_ATTACHMENT_ID: document_front_attachment_id, cls.FIELD_DOCUMENT_BACK_ATTACHMENT_ID: document_back_attachment_id, cls.FIELD_DATE_OF_BIRTH: date_of_birth, cls.FIELD_PLACE_OF_BIRTH: place_of_birth, cls.FIELD_COUNTRY_OF_BIRTH: country_of_birth, cls.FIELD_NATIONALITY: nationality, cls.FIELD_LANGUAGE: language, cls.FIELD_REGION: region, cls.FIELD_GENDER: gender, cls.FIELD_STATUS: status, cls.FIELD_SUB_STATUS: sub_status, cls.FIELD_LEGAL_GUARDIAN_ALIAS: legal_guardian_alias, cls.FIELD_SESSION_TIMEOUT: session_timeout, cls.FIELD_CARD_IDS: card_ids, cls.FIELD_CARD_LIMITS: card_limits, cls.FIELD_DAILY_LIMIT_WITHOUT_CONFIRMATION_LOGIN: daily_limit_without_confirmation_login, cls.FIELD_NOTIFICATION_FILTERS: notification_filters, cls.FIELD_DISPLAY_NAME: display_name } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id()) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "update", "(", "cls", ",", "first_name", "=", "None", ",", "middle_name", "=", "None", ",", "last_name", "=", "None", ",", "public_nick_name", "=", "None", ",", "address_main", "=", "None", ",", "address_postal", "=", "None", ",", "avatar_uuid", "="...
Modify a specific person object's data. :type user_person_id: int :param first_name: The person's first name. :type first_name: str :param middle_name: The person's middle name. :type middle_name: str :param last_name: The person's last name. :type last_name: str :param public_nick_name: The person's public nick name. :type public_nick_name: str :param address_main: The user's main address. :type address_main: object_.Address :param address_postal: The person's postal address. :type address_postal: object_.Address :param avatar_uuid: The public UUID of the user's avatar. :type avatar_uuid: str :param tax_resident: The user's tax residence numbers for different countries. :type tax_resident: list[object_.TaxResident] :param document_type: The type of identification document the person registered with. :type document_type: str :param document_number: The identification document number the person registered with. :type document_number: str :param document_country_of_issuance: The country which issued the identification document the person registered with. :type document_country_of_issuance: str :param document_front_attachment_id: The reference to the uploaded picture/scan of the front side of the identification document. :type document_front_attachment_id: int :param document_back_attachment_id: The reference to the uploaded picture/scan of the back side of the identification document. :type document_back_attachment_id: int :param date_of_birth: The person's date of birth. Accepts ISO8601 date formats. :type date_of_birth: str :param place_of_birth: The person's place of birth. :type place_of_birth: str :param country_of_birth: The person's country of birth. Formatted as a SO 3166-1 alpha-2 country code. :type country_of_birth: str :param nationality: The person's nationality. Formatted as a SO 3166-1 alpha-2 country code. :type nationality: str :param language: The person's preferred language. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type language: str :param region: The person's preferred region. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type region: str :param gender: The person's gender. Can be: MALE, FEMALE and UNKNOWN. :type gender: str :param status: The user status. You are not allowed to update the status via PUT. :type status: str :param sub_status: The user sub-status. Can be updated to SUBMIT if status is RECOVERY. :type sub_status: str :param legal_guardian_alias: The legal guardian of the user. Required for minors. :type legal_guardian_alias: object_.Pointer :param session_timeout: The setting for the session timeout of the user in seconds. :type session_timeout: int :param card_ids: Card ids used for centralized card limits. :type card_ids: list[object_.BunqId] :param card_limits: The centralized limits for user's cards. :type card_limits: list[object_.CardLimit] :param daily_limit_without_confirmation_login: The amount the user can pay in the session without asking for credentials. :type daily_limit_without_confirmation_login: object_.Amount :param notification_filters: The types of notifications that will result in a push notification or URL callback for this UserPerson. :type notification_filters: list[object_.NotificationFilter] :param display_name: The person's legal name. Available legal names can be listed via the 'user/{user_id}/legal-name' endpoint. :type display_name: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Modify", "a", "specific", "person", "object", "s", "data", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L29642-L29788
train
208,132
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
UserCompany.update
def update(cls, name=None, public_nick_name=None, avatar_uuid=None, address_main=None, address_postal=None, language=None, region=None, country=None, ubo=None, chamber_of_commerce_number=None, legal_form=None, status=None, sub_status=None, session_timeout=None, daily_limit_without_confirmation_login=None, notification_filters=None, custom_headers=None): """ Modify a specific company's data. :type user_company_id: int :param name: The company name. :type name: str :param public_nick_name: The company's nick name. :type public_nick_name: str :param avatar_uuid: The public UUID of the company's avatar. :type avatar_uuid: str :param address_main: The user's main address. :type address_main: object_.Address :param address_postal: The company's postal address. :type address_postal: object_.Address :param language: The person's preferred language. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type language: str :param region: The person's preferred region. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type region: str :param country: The country where the company is registered. :type country: str :param ubo: The names and birth dates of the company's ultimate beneficiary owners. Minimum zero, maximum four. :type ubo: list[object_.Ubo] :param chamber_of_commerce_number: The company's chamber of commerce number. :type chamber_of_commerce_number: str :param legal_form: The company's legal form. :type legal_form: str :param status: The user status. Can be: ACTIVE, SIGNUP, RECOVERY. :type status: str :param sub_status: The user sub-status. Can be: NONE, FACE_RESET, APPROVAL, APPROVAL_DIRECTOR, APPROVAL_PARENT, APPROVAL_SUPPORT, COUNTER_IBAN, IDEAL or SUBMIT. :type sub_status: str :param session_timeout: The setting for the session timeout of the company in seconds. :type session_timeout: int :param daily_limit_without_confirmation_login: The amount the company can pay in the session without asking for credentials. :type daily_limit_without_confirmation_login: object_.Amount :param notification_filters: The types of notifications that will result in a push notification or URL callback for this UserCompany. :type notification_filters: list[object_.NotificationFilter] :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_NAME: name, cls.FIELD_PUBLIC_NICK_NAME: public_nick_name, cls.FIELD_AVATAR_UUID: avatar_uuid, cls.FIELD_ADDRESS_MAIN: address_main, cls.FIELD_ADDRESS_POSTAL: address_postal, cls.FIELD_LANGUAGE: language, cls.FIELD_REGION: region, cls.FIELD_COUNTRY: country, cls.FIELD_UBO: ubo, cls.FIELD_CHAMBER_OF_COMMERCE_NUMBER: chamber_of_commerce_number, cls.FIELD_LEGAL_FORM: legal_form, cls.FIELD_STATUS: status, cls.FIELD_SUB_STATUS: sub_status, cls.FIELD_SESSION_TIMEOUT: session_timeout, cls.FIELD_DAILY_LIMIT_WITHOUT_CONFIRMATION_LOGIN: daily_limit_without_confirmation_login, cls.FIELD_NOTIFICATION_FILTERS: notification_filters } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id()) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def update(cls, name=None, public_nick_name=None, avatar_uuid=None, address_main=None, address_postal=None, language=None, region=None, country=None, ubo=None, chamber_of_commerce_number=None, legal_form=None, status=None, sub_status=None, session_timeout=None, daily_limit_without_confirmation_login=None, notification_filters=None, custom_headers=None): """ Modify a specific company's data. :type user_company_id: int :param name: The company name. :type name: str :param public_nick_name: The company's nick name. :type public_nick_name: str :param avatar_uuid: The public UUID of the company's avatar. :type avatar_uuid: str :param address_main: The user's main address. :type address_main: object_.Address :param address_postal: The company's postal address. :type address_postal: object_.Address :param language: The person's preferred language. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type language: str :param region: The person's preferred region. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type region: str :param country: The country where the company is registered. :type country: str :param ubo: The names and birth dates of the company's ultimate beneficiary owners. Minimum zero, maximum four. :type ubo: list[object_.Ubo] :param chamber_of_commerce_number: The company's chamber of commerce number. :type chamber_of_commerce_number: str :param legal_form: The company's legal form. :type legal_form: str :param status: The user status. Can be: ACTIVE, SIGNUP, RECOVERY. :type status: str :param sub_status: The user sub-status. Can be: NONE, FACE_RESET, APPROVAL, APPROVAL_DIRECTOR, APPROVAL_PARENT, APPROVAL_SUPPORT, COUNTER_IBAN, IDEAL or SUBMIT. :type sub_status: str :param session_timeout: The setting for the session timeout of the company in seconds. :type session_timeout: int :param daily_limit_without_confirmation_login: The amount the company can pay in the session without asking for credentials. :type daily_limit_without_confirmation_login: object_.Amount :param notification_filters: The types of notifications that will result in a push notification or URL callback for this UserCompany. :type notification_filters: list[object_.NotificationFilter] :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} api_client = client.ApiClient(cls._get_api_context()) request_map = { cls.FIELD_NAME: name, cls.FIELD_PUBLIC_NICK_NAME: public_nick_name, cls.FIELD_AVATAR_UUID: avatar_uuid, cls.FIELD_ADDRESS_MAIN: address_main, cls.FIELD_ADDRESS_POSTAL: address_postal, cls.FIELD_LANGUAGE: language, cls.FIELD_REGION: region, cls.FIELD_COUNTRY: country, cls.FIELD_UBO: ubo, cls.FIELD_CHAMBER_OF_COMMERCE_NUMBER: chamber_of_commerce_number, cls.FIELD_LEGAL_FORM: legal_form, cls.FIELD_STATUS: status, cls.FIELD_SUB_STATUS: sub_status, cls.FIELD_SESSION_TIMEOUT: session_timeout, cls.FIELD_DAILY_LIMIT_WITHOUT_CONFIRMATION_LOGIN: daily_limit_without_confirmation_login, cls.FIELD_NOTIFICATION_FILTERS: notification_filters } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id()) response_raw = api_client.put(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "update", "(", "cls", ",", "name", "=", "None", ",", "public_nick_name", "=", "None", ",", "avatar_uuid", "=", "None", ",", "address_main", "=", "None", ",", "address_postal", "=", "None", ",", "language", "=", "None", ",", "region", "=", "None", ...
Modify a specific company's data. :type user_company_id: int :param name: The company name. :type name: str :param public_nick_name: The company's nick name. :type public_nick_name: str :param avatar_uuid: The public UUID of the company's avatar. :type avatar_uuid: str :param address_main: The user's main address. :type address_main: object_.Address :param address_postal: The company's postal address. :type address_postal: object_.Address :param language: The person's preferred language. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type language: str :param region: The person's preferred region. Formatted as a ISO 639-1 language code plus a ISO 3166-1 alpha-2 country code, seperated by an underscore. :type region: str :param country: The country where the company is registered. :type country: str :param ubo: The names and birth dates of the company's ultimate beneficiary owners. Minimum zero, maximum four. :type ubo: list[object_.Ubo] :param chamber_of_commerce_number: The company's chamber of commerce number. :type chamber_of_commerce_number: str :param legal_form: The company's legal form. :type legal_form: str :param status: The user status. Can be: ACTIVE, SIGNUP, RECOVERY. :type status: str :param sub_status: The user sub-status. Can be: NONE, FACE_RESET, APPROVAL, APPROVAL_DIRECTOR, APPROVAL_PARENT, APPROVAL_SUPPORT, COUNTER_IBAN, IDEAL or SUBMIT. :type sub_status: str :param session_timeout: The setting for the session timeout of the company in seconds. :type session_timeout: int :param daily_limit_without_confirmation_login: The amount the company can pay in the session without asking for credentials. :type daily_limit_without_confirmation_login: object_.Amount :param notification_filters: The types of notifications that will result in a push notification or URL callback for this UserCompany. :type notification_filters: list[object_.NotificationFilter] :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Modify", "a", "specific", "company", "s", "data", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L30404-L30496
train
208,133
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
TabItemShop.create
def create(cls, cash_register_id, tab_uuid, description, monetary_account_id=None, ean_code=None, avatar_attachment_uuid=None, tab_attachment=None, quantity=None, amount=None, custom_headers=None): """ Create a new TabItem for a given Tab. :type user_id: int :type monetary_account_id: int :type cash_register_id: int :type tab_uuid: str :param description: The TabItem's brief description. Can't be empty and must be no longer than 100 characters :type description: str :param ean_code: The TabItem's EAN code. :type ean_code: str :param avatar_attachment_uuid: An AttachmentPublic UUID that used as an avatar for the TabItem. :type avatar_attachment_uuid: str :param tab_attachment: A list of AttachmentTab attached to the TabItem. :type tab_attachment: list[int] :param quantity: The quantity of the TabItem. Formatted as a number containing up to 15 digits, up to 15 decimals and using a dot. :type quantity: str :param amount: The money amount of the TabItem. Will not change the value of the corresponding Tab. :type amount: object_.Amount :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_DESCRIPTION: description, cls.FIELD_EAN_CODE: ean_code, cls.FIELD_AVATAR_ATTACHMENT_UUID: avatar_attachment_uuid, cls.FIELD_TAB_ATTACHMENT: tab_attachment, cls.FIELD_QUANTITY: quantity, cls.FIELD_AMOUNT: amount } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id), cash_register_id, tab_uuid) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, cash_register_id, tab_uuid, description, monetary_account_id=None, ean_code=None, avatar_attachment_uuid=None, tab_attachment=None, quantity=None, amount=None, custom_headers=None): """ Create a new TabItem for a given Tab. :type user_id: int :type monetary_account_id: int :type cash_register_id: int :type tab_uuid: str :param description: The TabItem's brief description. Can't be empty and must be no longer than 100 characters :type description: str :param ean_code: The TabItem's EAN code. :type ean_code: str :param avatar_attachment_uuid: An AttachmentPublic UUID that used as an avatar for the TabItem. :type avatar_attachment_uuid: str :param tab_attachment: A list of AttachmentTab attached to the TabItem. :type tab_attachment: list[int] :param quantity: The quantity of the TabItem. Formatted as a number containing up to 15 digits, up to 15 decimals and using a dot. :type quantity: str :param amount: The money amount of the TabItem. Will not change the value of the corresponding Tab. :type amount: object_.Amount :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_DESCRIPTION: description, cls.FIELD_EAN_CODE: ean_code, cls.FIELD_AVATAR_ATTACHMENT_UUID: avatar_attachment_uuid, cls.FIELD_TAB_ATTACHMENT: tab_attachment, cls.FIELD_QUANTITY: quantity, cls.FIELD_AMOUNT: amount } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(), cls._determine_monetary_account_id( monetary_account_id), cash_register_id, tab_uuid) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "cash_register_id", ",", "tab_uuid", ",", "description", ",", "monetary_account_id", "=", "None", ",", "ean_code", "=", "None", ",", "avatar_attachment_uuid", "=", "None", ",", "tab_attachment", "=", "None", ",", "quantity", "...
Create a new TabItem for a given Tab. :type user_id: int :type monetary_account_id: int :type cash_register_id: int :type tab_uuid: str :param description: The TabItem's brief description. Can't be empty and must be no longer than 100 characters :type description: str :param ean_code: The TabItem's EAN code. :type ean_code: str :param avatar_attachment_uuid: An AttachmentPublic UUID that used as an avatar for the TabItem. :type avatar_attachment_uuid: str :param tab_attachment: A list of AttachmentTab attached to the TabItem. :type tab_attachment: list[int] :param quantity: The quantity of the TabItem. Formatted as a number containing up to 15 digits, up to 15 decimals and using a dot. :type quantity: str :param amount: The money amount of the TabItem. Will not change the value of the corresponding Tab. :type amount: object_.Amount :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Create", "a", "new", "TabItem", "for", "a", "given", "Tab", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L32573-L32631
train
208,134
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
TokenQrRequestIdeal.create
def create(cls, token, custom_headers=None): """ Create a request from an ideal transaction. :type user_id: int :param token: The token passed from a site or read from a QR code. :type token: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseTokenQrRequestIdeal """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_TOKEN: token } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id()) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseTokenQrRequestIdeal.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_POST) )
python
def create(cls, token, custom_headers=None): """ Create a request from an ideal transaction. :type user_id: int :param token: The token passed from a site or read from a QR code. :type token: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseTokenQrRequestIdeal """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_TOKEN: token } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id()) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseTokenQrRequestIdeal.cast_from_bunq_response( cls._from_json(response_raw, cls._OBJECT_TYPE_POST) )
[ "def", "create", "(", "cls", ",", "token", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "request_map", "=", "{", "cls", ".", "FIELD_TOKEN", ":", "token", "}", "request_map_string"...
Create a request from an ideal transaction. :type user_id: int :param token: The token passed from a site or read from a QR code. :type token: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseTokenQrRequestIdeal
[ "Create", "a", "request", "from", "an", "ideal", "transaction", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L33060-L33089
train
208,135
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
WhitelistSdd.create
def create(cls, monetary_account_paying_id, request_id, maximum_amount_per_month, custom_headers=None): """ Create a new SDD whitelist entry. :type user_id: int :param monetary_account_paying_id: ID of the monetary account of which you want to pay from. :type monetary_account_paying_id: int :param request_id: ID of the request for which you want to whitelist the originating SDD. :type request_id: int :param maximum_amount_per_month: The maximum amount of money that is allowed to be deducted based on the whitelist. :type maximum_amount_per_month: object_.Amount :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_MONETARY_ACCOUNT_PAYING_ID: monetary_account_paying_id, cls.FIELD_REQUEST_ID: request_id, cls.FIELD_MAXIMUM_AMOUNT_PER_MONTH: maximum_amount_per_month } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id()) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
python
def create(cls, monetary_account_paying_id, request_id, maximum_amount_per_month, custom_headers=None): """ Create a new SDD whitelist entry. :type user_id: int :param monetary_account_paying_id: ID of the monetary account of which you want to pay from. :type monetary_account_paying_id: int :param request_id: ID of the request for which you want to whitelist the originating SDD. :type request_id: int :param maximum_amount_per_month: The maximum amount of money that is allowed to be deducted based on the whitelist. :type maximum_amount_per_month: object_.Amount :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_MONETARY_ACCOUNT_PAYING_ID: monetary_account_paying_id, cls.FIELD_REQUEST_ID: request_id, cls.FIELD_MAXIMUM_AMOUNT_PER_MONTH: maximum_amount_per_month } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_for_request(request_map_string) api_client = client.ApiClient(cls._get_api_context()) request_bytes = request_map_string.encode() endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id()) response_raw = api_client.post(endpoint_url, request_bytes, custom_headers) return BunqResponseInt.cast_from_bunq_response( cls._process_for_id(response_raw) )
[ "def", "create", "(", "cls", ",", "monetary_account_paying_id", ",", "request_id", ",", "maximum_amount_per_month", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "request_map", "=", "{",...
Create a new SDD whitelist entry. :type user_id: int :param monetary_account_paying_id: ID of the monetary account of which you want to pay from. :type monetary_account_paying_id: int :param request_id: ID of the request for which you want to whitelist the originating SDD. :type request_id: int :param maximum_amount_per_month: The maximum amount of money that is allowed to be deducted based on the whitelist. :type maximum_amount_per_month: object_.Amount :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
[ "Create", "a", "new", "SDD", "whitelist", "entry", "." ]
da6c9b83e6d83ee8062617f53c6eb7293c0d863d
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L33849-L33888
train
208,136
redcanari/canari3
src/canari/resource.py
icon_resource
def icon_resource(name, package=None): """ Returns the absolute URI path to an image. If a package is not explicitly specified then the calling package name is used. :param name: path relative to package path of the image resource. :param package: package name in dotted format. :return: the file URI path to the image resource (i.e. file:///foo/bar/image.png). """ if not package: package = '%s.resources.images' % calling_package() name = resource_filename(package, name) if not name.startswith('/'): return 'file://%s' % abspath(name) return 'file://%s' % name
python
def icon_resource(name, package=None): """ Returns the absolute URI path to an image. If a package is not explicitly specified then the calling package name is used. :param name: path relative to package path of the image resource. :param package: package name in dotted format. :return: the file URI path to the image resource (i.e. file:///foo/bar/image.png). """ if not package: package = '%s.resources.images' % calling_package() name = resource_filename(package, name) if not name.startswith('/'): return 'file://%s' % abspath(name) return 'file://%s' % name
[ "def", "icon_resource", "(", "name", ",", "package", "=", "None", ")", ":", "if", "not", "package", ":", "package", "=", "'%s.resources.images'", "%", "calling_package", "(", ")", "name", "=", "resource_filename", "(", "package", ",", "name", ")", "if", "n...
Returns the absolute URI path to an image. If a package is not explicitly specified then the calling package name is used. :param name: path relative to package path of the image resource. :param package: package name in dotted format. :return: the file URI path to the image resource (i.e. file:///foo/bar/image.png).
[ "Returns", "the", "absolute", "URI", "path", "to", "an", "image", ".", "If", "a", "package", "is", "not", "explicitly", "specified", "then", "the", "calling", "package", "name", "is", "used", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/resource.py#L41-L55
train
208,137
redcanari/canari3
src/canari/resource.py
image_resources
def image_resources(package=None, directory='resources'): """ Returns all images under the directory relative to a package path. If no directory or package is specified then the resources module of the calling package will be used. Images are recursively discovered. :param package: package name in dotted format. :param directory: path relative to package path of the resources directory. :return: a list of images under the specified resources path. """ if not package: package = calling_package() package_dir = '.'.join([package, directory]) images = [] for i in resource_listdir(package, directory): if i.startswith('__') or i.endswith('.egg-info'): continue fname = resource_filename(package_dir, i) if resource_isdir(package_dir, i): images.extend(image_resources(package_dir, i)) elif what(fname): images.append(fname) return images
python
def image_resources(package=None, directory='resources'): """ Returns all images under the directory relative to a package path. If no directory or package is specified then the resources module of the calling package will be used. Images are recursively discovered. :param package: package name in dotted format. :param directory: path relative to package path of the resources directory. :return: a list of images under the specified resources path. """ if not package: package = calling_package() package_dir = '.'.join([package, directory]) images = [] for i in resource_listdir(package, directory): if i.startswith('__') or i.endswith('.egg-info'): continue fname = resource_filename(package_dir, i) if resource_isdir(package_dir, i): images.extend(image_resources(package_dir, i)) elif what(fname): images.append(fname) return images
[ "def", "image_resources", "(", "package", "=", "None", ",", "directory", "=", "'resources'", ")", ":", "if", "not", "package", ":", "package", "=", "calling_package", "(", ")", "package_dir", "=", "'.'", ".", "join", "(", "[", "package", ",", "directory", ...
Returns all images under the directory relative to a package path. If no directory or package is specified then the resources module of the calling package will be used. Images are recursively discovered. :param package: package name in dotted format. :param directory: path relative to package path of the resources directory. :return: a list of images under the specified resources path.
[ "Returns", "all", "images", "under", "the", "directory", "relative", "to", "a", "package", "path", ".", "If", "no", "directory", "or", "package", "is", "specified", "then", "the", "resources", "module", "of", "the", "calling", "package", "will", "be", "used"...
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/resource.py#L58-L79
train
208,138
redcanari/canari3
src/canari/easygui.py
indexbox
def indexbox(msg="Shall I continue?" , title=" " , choices=("Yes","No") , image=None ): """ Display a buttonbox with the specified choices. Return the index of the choice selected. """ reply = buttonbox(msg=msg, choices=choices, title=title, image=image) index = -1 for choice in choices: index = index + 1 if reply == choice: return index raise AssertionError( "There is a program logic error in the EasyGui code for indexbox.")
python
def indexbox(msg="Shall I continue?" , title=" " , choices=("Yes","No") , image=None ): """ Display a buttonbox with the specified choices. Return the index of the choice selected. """ reply = buttonbox(msg=msg, choices=choices, title=title, image=image) index = -1 for choice in choices: index = index + 1 if reply == choice: return index raise AssertionError( "There is a program logic error in the EasyGui code for indexbox.")
[ "def", "indexbox", "(", "msg", "=", "\"Shall I continue?\"", ",", "title", "=", "\" \"", ",", "choices", "=", "(", "\"Yes\"", ",", "\"No\"", ")", ",", "image", "=", "None", ")", ":", "reply", "=", "buttonbox", "(", "msg", "=", "msg", ",", "choices", ...
Display a buttonbox with the specified choices. Return the index of the choice selected.
[ "Display", "a", "buttonbox", "with", "the", "specified", "choices", ".", "Return", "the", "index", "of", "the", "choice", "selected", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/easygui.py#L316-L331
train
208,139
redcanari/canari3
src/canari/easygui.py
msgbox
def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK",image=None,root=None): """ Display a messagebox """ if type(ok_button) != type("OK"): raise AssertionError("The 'ok_button' argument to msgbox must be a string.") return buttonbox(msg=msg, title=title, choices=[ok_button], image=image,root=root)
python
def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK",image=None,root=None): """ Display a messagebox """ if type(ok_button) != type("OK"): raise AssertionError("The 'ok_button' argument to msgbox must be a string.") return buttonbox(msg=msg, title=title, choices=[ok_button], image=image,root=root)
[ "def", "msgbox", "(", "msg", "=", "\"(Your message goes here)\"", ",", "title", "=", "\" \"", ",", "ok_button", "=", "\"OK\"", ",", "image", "=", "None", ",", "root", "=", "None", ")", ":", "if", "type", "(", "ok_button", ")", "!=", "type", "(", "\"OK\...
Display a messagebox
[ "Display", "a", "messagebox" ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/easygui.py#L337-L344
train
208,140
redcanari/canari3
src/canari/easygui.py
multpasswordbox
def multpasswordbox(msg="Fill in values for the fields." , title=" " , fields=tuple() ,values=tuple() ): r""" Same interface as multenterbox. But in multpassword box, the last of the fields is assumed to be a password, and is masked with asterisks. Example ======= Here is some example code, that shows how values returned from multpasswordbox can be checked for validity before they are accepted:: msg = "Enter logon information" title = "Demo of multpasswordbox" fieldNames = ["Server ID", "User ID", "Password"] fieldValues = [] # we start with blanks for the values fieldValues = multpasswordbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues) writeln("Reply was: %s" % str(fieldValues)) """ return __multfillablebox(msg,title,fields,values,"*")
python
def multpasswordbox(msg="Fill in values for the fields." , title=" " , fields=tuple() ,values=tuple() ): r""" Same interface as multenterbox. But in multpassword box, the last of the fields is assumed to be a password, and is masked with asterisks. Example ======= Here is some example code, that shows how values returned from multpasswordbox can be checked for validity before they are accepted:: msg = "Enter logon information" title = "Demo of multpasswordbox" fieldNames = ["Server ID", "User ID", "Password"] fieldValues = [] # we start with blanks for the values fieldValues = multpasswordbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues) writeln("Reply was: %s" % str(fieldValues)) """ return __multfillablebox(msg,title,fields,values,"*")
[ "def", "multpasswordbox", "(", "msg", "=", "\"Fill in values for the fields.\"", ",", "title", "=", "\" \"", ",", "fields", "=", "tuple", "(", ")", ",", "values", "=", "tuple", "(", ")", ")", ":", "return", "__multfillablebox", "(", "msg", ",", "title", ",...
r""" Same interface as multenterbox. But in multpassword box, the last of the fields is assumed to be a password, and is masked with asterisks. Example ======= Here is some example code, that shows how values returned from multpasswordbox can be checked for validity before they are accepted:: msg = "Enter logon information" title = "Demo of multpasswordbox" fieldNames = ["Server ID", "User ID", "Password"] fieldValues = [] # we start with blanks for the values fieldValues = multpasswordbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues) writeln("Reply was: %s" % str(fieldValues))
[ "r", "Same", "interface", "as", "multenterbox", ".", "But", "in", "multpassword", "box", "the", "last", "of", "the", "fields", "is", "assumed", "to", "be", "a", "password", "and", "is", "masked", "with", "asterisks", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/easygui.py#L596-L629
train
208,141
redcanari/canari3
src/canari/easygui.py
passwordbox
def passwordbox(msg="Enter your password." , title=" " , default="" , image=None , root=None ): """ Show a box in which a user can enter a password. The text is masked with asterisks, so the password is not displayed. Returns the text that the user entered, or None if he cancels the operation. """ return __fillablebox(msg, title, default, mask="*",image=image,root=root)
python
def passwordbox(msg="Enter your password." , title=" " , default="" , image=None , root=None ): """ Show a box in which a user can enter a password. The text is masked with asterisks, so the password is not displayed. Returns the text that the user entered, or None if he cancels the operation. """ return __fillablebox(msg, title, default, mask="*",image=image,root=root)
[ "def", "passwordbox", "(", "msg", "=", "\"Enter your password.\"", ",", "title", "=", "\" \"", ",", "default", "=", "\"\"", ",", "image", "=", "None", ",", "root", "=", "None", ")", ":", "return", "__fillablebox", "(", "msg", ",", "title", ",", "default"...
Show a box in which a user can enter a password. The text is masked with asterisks, so the password is not displayed. Returns the text that the user entered, or None if he cancels the operation.
[ "Show", "a", "box", "in", "which", "a", "user", "can", "enter", "a", "password", ".", "The", "text", "is", "masked", "with", "asterisks", "so", "the", "password", "is", "not", "displayed", ".", "Returns", "the", "text", "that", "the", "user", "entered", ...
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/easygui.py#L811-L822
train
208,142
redcanari/canari3
src/canari/easygui.py
diropenbox
def diropenbox(msg=None , title=None , default=None ): """ A dialog to get a directory name. Note that the msg argument, if specified, is ignored. Returns the name of a directory, or None if user chose to cancel. If the "default" argument specifies a directory name, and that directory exists, then the dialog box will start with that directory. """ if sys.platform == 'darwin': _bring_to_front() title=getFileDialogTitle(msg,title) localRoot = Tk() localRoot.withdraw() if not default: default = None f = tk_FileDialog.askdirectory( parent=localRoot , title=title , initialdir=default , initialfile=None ) localRoot.destroy() if not f: return None return os.path.normpath(f)
python
def diropenbox(msg=None , title=None , default=None ): """ A dialog to get a directory name. Note that the msg argument, if specified, is ignored. Returns the name of a directory, or None if user chose to cancel. If the "default" argument specifies a directory name, and that directory exists, then the dialog box will start with that directory. """ if sys.platform == 'darwin': _bring_to_front() title=getFileDialogTitle(msg,title) localRoot = Tk() localRoot.withdraw() if not default: default = None f = tk_FileDialog.askdirectory( parent=localRoot , title=title , initialdir=default , initialfile=None ) localRoot.destroy() if not f: return None return os.path.normpath(f)
[ "def", "diropenbox", "(", "msg", "=", "None", ",", "title", "=", "None", ",", "default", "=", "None", ")", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "_bring_to_front", "(", ")", "title", "=", "getFileDialogTitle", "(", "msg", ",", "titl...
A dialog to get a directory name. Note that the msg argument, if specified, is ignored. Returns the name of a directory, or None if user chose to cancel. If the "default" argument specifies a directory name, and that directory exists, then the dialog box will start with that directory.
[ "A", "dialog", "to", "get", "a", "directory", "name", ".", "Note", "that", "the", "msg", "argument", "if", "specified", "is", "ignored", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/easygui.py#L1554-L1581
train
208,143
redcanari/canari3
src/canari/easygui.py
__buttonEvent
def __buttonEvent(event): """ Handle an event that is generated by a person clicking a button. """ global boxRoot, __widgetTexts, __replyButtonText __replyButtonText = __widgetTexts[event.widget] boxRoot.quit()
python
def __buttonEvent(event): """ Handle an event that is generated by a person clicking a button. """ global boxRoot, __widgetTexts, __replyButtonText __replyButtonText = __widgetTexts[event.widget] boxRoot.quit()
[ "def", "__buttonEvent", "(", "event", ")", ":", "global", "boxRoot", ",", "__widgetTexts", ",", "__replyButtonText", "__replyButtonText", "=", "__widgetTexts", "[", "event", ".", "widget", "]", "boxRoot", ".", "quit", "(", ")" ]
Handle an event that is generated by a person clicking a button.
[ "Handle", "an", "event", "that", "is", "generated", "by", "a", "person", "clicking", "a", "button", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/easygui.py#L1851-L1857
train
208,144
redcanari/canari3
src/canari/maltego/utils.py
on_terminate
def on_terminate(func): """Register a signal handler to execute when Maltego forcibly terminates the transform.""" def exit_function(*args): func() exit(0) signal.signal(signal.SIGTERM, exit_function)
python
def on_terminate(func): """Register a signal handler to execute when Maltego forcibly terminates the transform.""" def exit_function(*args): func() exit(0) signal.signal(signal.SIGTERM, exit_function)
[ "def", "on_terminate", "(", "func", ")", ":", "def", "exit_function", "(", "*", "args", ")", ":", "func", "(", ")", "exit", "(", "0", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "exit_function", ")" ]
Register a signal handler to execute when Maltego forcibly terminates the transform.
[ "Register", "a", "signal", "handler", "to", "execute", "when", "Maltego", "forcibly", "terminates", "the", "transform", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/maltego/utils.py#L30-L35
train
208,145
redcanari/canari3
src/canari/maltego/utils.py
croak
def croak(error, message_writer=message): """Throw an exception in the Maltego GUI containing error_msg.""" if isinstance(error, MaltegoException): message_writer(MaltegoTransformExceptionMessage(exceptions=[error])) else: message_writer(MaltegoTransformExceptionMessage(exceptions=[MaltegoException(error)]))
python
def croak(error, message_writer=message): """Throw an exception in the Maltego GUI containing error_msg.""" if isinstance(error, MaltegoException): message_writer(MaltegoTransformExceptionMessage(exceptions=[error])) else: message_writer(MaltegoTransformExceptionMessage(exceptions=[MaltegoException(error)]))
[ "def", "croak", "(", "error", ",", "message_writer", "=", "message", ")", ":", "if", "isinstance", "(", "error", ",", "MaltegoException", ")", ":", "message_writer", "(", "MaltegoTransformExceptionMessage", "(", "exceptions", "=", "[", "error", "]", ")", ")", ...
Throw an exception in the Maltego GUI containing error_msg.
[ "Throw", "an", "exception", "in", "the", "Maltego", "GUI", "containing", "error_msg", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/maltego/utils.py#L49-L54
train
208,146
redcanari/canari3
src/canari/maltego/utils.py
debug
def debug(*args): """Send debug messages to the Maltego console.""" for i in args: click.echo('D:%s' % str(i), err=True)
python
def debug(*args): """Send debug messages to the Maltego console.""" for i in args: click.echo('D:%s' % str(i), err=True)
[ "def", "debug", "(", "*", "args", ")", ":", "for", "i", "in", "args", ":", "click", ".", "echo", "(", "'D:%s'", "%", "str", "(", "i", ")", ",", "err", "=", "True", ")" ]
Send debug messages to the Maltego console.
[ "Send", "debug", "messages", "to", "the", "Maltego", "console", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/maltego/utils.py#L106-L109
train
208,147
redcanari/canari3
src/canari/entrypoints.py
create_aws_lambda
def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key): """Creates an AWS Chalice project for deployment to AWS Lambda.""" from canari.commands.create_aws_lambda import create_aws_lambda create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_key)
python
def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key): """Creates an AWS Chalice project for deployment to AWS Lambda.""" from canari.commands.create_aws_lambda import create_aws_lambda create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_key)
[ "def", "create_aws_lambda", "(", "ctx", ",", "bucket", ",", "region_name", ",", "aws_access_key_id", ",", "aws_secret_access_key", ")", ":", "from", "canari", ".", "commands", ".", "create_aws_lambda", "import", "create_aws_lambda", "create_aws_lambda", "(", "ctx", ...
Creates an AWS Chalice project for deployment to AWS Lambda.
[ "Creates", "an", "AWS", "Chalice", "project", "for", "deployment", "to", "AWS", "Lambda", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L62-L65
train
208,148
redcanari/canari3
src/canari/entrypoints.py
create_package
def create_package(package, author, email, description, create_example): """Creates a Canari transform package skeleton.""" from canari.commands.create_package import create_package create_package(package, author, email, description, create_example)
python
def create_package(package, author, email, description, create_example): """Creates a Canari transform package skeleton.""" from canari.commands.create_package import create_package create_package(package, author, email, description, create_example)
[ "def", "create_package", "(", "package", ",", "author", ",", "email", ",", "description", ",", "create_example", ")", ":", "from", "canari", ".", "commands", ".", "create_package", "import", "create_package", "create_package", "(", "package", ",", "author", ",",...
Creates a Canari transform package skeleton.
[ "Creates", "a", "Canari", "transform", "package", "skeleton", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L74-L77
train
208,149
redcanari/canari3
src/canari/entrypoints.py
create_transform
def create_transform(ctx, transform): """Creates a new transform in the specified directory and auto-updates dependencies.""" from canari.commands.create_transform import create_transform create_transform(ctx.project, transform)
python
def create_transform(ctx, transform): """Creates a new transform in the specified directory and auto-updates dependencies.""" from canari.commands.create_transform import create_transform create_transform(ctx.project, transform)
[ "def", "create_transform", "(", "ctx", ",", "transform", ")", ":", "from", "canari", ".", "commands", ".", "create_transform", "import", "create_transform", "create_transform", "(", "ctx", ".", "project", ",", "transform", ")" ]
Creates a new transform in the specified directory and auto-updates dependencies.
[ "Creates", "a", "new", "transform", "in", "the", "specified", "directory", "and", "auto", "-", "updates", "dependencies", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L92-L95
train
208,150
redcanari/canari3
src/canari/entrypoints.py
dockerize_package
def dockerize_package(ctx, os, host): """Creates a Docker build file pre-configured with Plume.""" from canari.commands.dockerize_package import dockerize_package dockerize_package(ctx.project, os, host)
python
def dockerize_package(ctx, os, host): """Creates a Docker build file pre-configured with Plume.""" from canari.commands.dockerize_package import dockerize_package dockerize_package(ctx.project, os, host)
[ "def", "dockerize_package", "(", "ctx", ",", "os", ",", "host", ")", ":", "from", "canari", ".", "commands", ".", "dockerize_package", "import", "dockerize_package", "dockerize_package", "(", "ctx", ".", "project", ",", "os", ",", "host", ")" ]
Creates a Docker build file pre-configured with Plume.
[ "Creates", "a", "Docker", "build", "file", "pre", "-", "configured", "with", "Plume", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L117-L120
train
208,151
redcanari/canari3
src/canari/entrypoints.py
generate_entities
def generate_entities(ctx, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity): """Converts Maltego entity definition files to Canari python classes. Excludes Maltego built-in entities by default.""" from canari.commands.generate_entities import generate_entities generate_entities( ctx.project, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity)
python
def generate_entities(ctx, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity): """Converts Maltego entity definition files to Canari python classes. Excludes Maltego built-in entities by default.""" from canari.commands.generate_entities import generate_entities generate_entities( ctx.project, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity)
[ "def", "generate_entities", "(", "ctx", ",", "output_path", ",", "mtz_file", ",", "exclude_namespace", ",", "namespace", ",", "maltego_entities", ",", "append", ",", "entity", ")", ":", "from", "canari", ".", "commands", ".", "generate_entities", "import", "gene...
Converts Maltego entity definition files to Canari python classes. Excludes Maltego built-in entities by default.
[ "Converts", "Maltego", "entity", "definition", "files", "to", "Canari", "python", "classes", ".", "Excludes", "Maltego", "built", "-", "in", "entities", "by", "default", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L146-L151
train
208,152
redcanari/canari3
src/canari/entrypoints.py
generate_entities_doc
def generate_entities_doc(ctx, out_path, package): """Create entities documentation from Canari python classes file.""" from canari.commands.generate_entities_doc import generate_entities_doc generate_entities_doc(ctx.project, out_path, package)
python
def generate_entities_doc(ctx, out_path, package): """Create entities documentation from Canari python classes file.""" from canari.commands.generate_entities_doc import generate_entities_doc generate_entities_doc(ctx.project, out_path, package)
[ "def", "generate_entities_doc", "(", "ctx", ",", "out_path", ",", "package", ")", ":", "from", "canari", ".", "commands", ".", "generate_entities_doc", "import", "generate_entities_doc", "generate_entities_doc", "(", "ctx", ".", "project", ",", "out_path", ",", "p...
Create entities documentation from Canari python classes file.
[ "Create", "entities", "documentation", "from", "Canari", "python", "classes", "file", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L159-L162
train
208,153
redcanari/canari3
src/canari/entrypoints.py
load_plume_package
def load_plume_package(package, plume_dir, accept_defaults): """Loads a canari package into Plume.""" from canari.commands.load_plume_package import load_plume_package load_plume_package(package, plume_dir, accept_defaults)
python
def load_plume_package(package, plume_dir, accept_defaults): """Loads a canari package into Plume.""" from canari.commands.load_plume_package import load_plume_package load_plume_package(package, plume_dir, accept_defaults)
[ "def", "load_plume_package", "(", "package", ",", "plume_dir", ",", "accept_defaults", ")", ":", "from", "canari", ".", "commands", ".", "load_plume_package", "import", "load_plume_package", "load_plume_package", "(", "package", ",", "plume_dir", ",", "accept_defaults...
Loads a canari package into Plume.
[ "Loads", "a", "canari", "package", "into", "Plume", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L193-L196
train
208,154
redcanari/canari3
src/canari/entrypoints.py
shell
def shell(ctx, package, working_dir, sudo): """Runs a Canari interactive python shell""" ctx.mode = CanariMode.LocalShellDebug from canari.commands.shell import shell shell(package, working_dir, sudo)
python
def shell(ctx, package, working_dir, sudo): """Runs a Canari interactive python shell""" ctx.mode = CanariMode.LocalShellDebug from canari.commands.shell import shell shell(package, working_dir, sudo)
[ "def", "shell", "(", "ctx", ",", "package", ",", "working_dir", ",", "sudo", ")", ":", "ctx", ".", "mode", "=", "CanariMode", ".", "LocalShellDebug", "from", "canari", ".", "commands", ".", "shell", "import", "shell", "shell", "(", "package", ",", "worki...
Runs a Canari interactive python shell
[ "Runs", "a", "Canari", "interactive", "python", "shell" ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L254-L258
train
208,155
redcanari/canari3
src/canari/entrypoints.py
unload_plume_package
def unload_plume_package(package, plume_dir): """Unloads a canari package from Plume.""" from canari.commands.unload_plume_package import unload_plume_package unload_plume_package(package, plume_dir)
python
def unload_plume_package(package, plume_dir): """Unloads a canari package from Plume.""" from canari.commands.unload_plume_package import unload_plume_package unload_plume_package(package, plume_dir)
[ "def", "unload_plume_package", "(", "package", ",", "plume_dir", ")", ":", "from", "canari", ".", "commands", ".", "unload_plume_package", "import", "unload_plume_package", "unload_plume_package", "(", "package", ",", "plume_dir", ")" ]
Unloads a canari package from Plume.
[ "Unloads", "a", "canari", "package", "from", "Plume", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L265-L268
train
208,156
redcanari/canari3
src/canari/mode.py
set_canari_mode
def set_canari_mode(mode=CanariMode.Unknown): """ Sets the global operating mode for Canari. This is used to alter the behaviour of dangerous classes like the CanariConfigParser. :param mode: the numeric Canari operating mode (CanariMode.Local, CanariMode.Remote, etc.). :return: previous operating mode. """ global canari_mode old_mode = canari_mode canari_mode = mode return old_mode
python
def set_canari_mode(mode=CanariMode.Unknown): """ Sets the global operating mode for Canari. This is used to alter the behaviour of dangerous classes like the CanariConfigParser. :param mode: the numeric Canari operating mode (CanariMode.Local, CanariMode.Remote, etc.). :return: previous operating mode. """ global canari_mode old_mode = canari_mode canari_mode = mode return old_mode
[ "def", "set_canari_mode", "(", "mode", "=", "CanariMode", ".", "Unknown", ")", ":", "global", "canari_mode", "old_mode", "=", "canari_mode", "canari_mode", "=", "mode", "return", "old_mode" ]
Sets the global operating mode for Canari. This is used to alter the behaviour of dangerous classes like the CanariConfigParser. :param mode: the numeric Canari operating mode (CanariMode.Local, CanariMode.Remote, etc.). :return: previous operating mode.
[ "Sets", "the", "global", "operating", "mode", "for", "Canari", ".", "This", "is", "used", "to", "alter", "the", "behaviour", "of", "dangerous", "classes", "like", "the", "CanariConfigParser", "." ]
322d2bae4b49ac728229f418b786b51fcc227352
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/mode.py#L100-L111
train
208,157
pbrod/numdifftools
src/numdifftools/nd_statsmodels.py
approx_fprime
def approx_fprime(x, f, epsilon=None, args=(), kwargs=None, centered=True): """ Gradient of function, or Jacobian if function fun returns 1d array Parameters ---------- x : array parameters at which the derivative is evaluated fun : function `fun(*((x,)+args), **kwargs)` returning either one value or 1d array epsilon : float, optional Stepsize, if None, optimal stepsize is used. This is _EPS**(1/2)*x for `centered` == False and _EPS**(1/3)*x for `centered` == True. args : tuple Tuple of additional arguments for function `fun`. kwargs : dict Dictionary of additional keyword arguments for function `fun`. centered : bool Whether central difference should be returned. If not, does forward differencing. Returns ------- grad : array gradient or Jacobian Notes ----- If fun returns a 1d array, it returns a Jacobian. If a 2d array is returned by fun (e.g., with a value for each observation), it returns a 3d array with the Jacobian of each observation with shape xk x nobs x xk. I.e., the Jacobian of the first observation would be [:, 0, :] """ kwargs = {} if kwargs is None else kwargs n = len(x) f0 = f(*(x,) + args, **kwargs) dim = np.atleast_1d(f0).shape # it could be a scalar grad = np.zeros((n,) + dim, float) ei = np.zeros(np.shape(x), float) if not centered: epsilon = _get_epsilon(x, 2, epsilon, n) for k in range(n): ei[k] = epsilon[k] grad[k, :] = (f(*(x + ei,) + args, **kwargs) - f0) / epsilon[k] ei[k] = 0.0 else: epsilon = _get_epsilon(x, 3, epsilon, n) / 2. for k in range(n): ei[k] = epsilon[k] grad[k, :] = (f(*(x + ei,) + args, **kwargs) - f(*(x - ei,) + args, **kwargs)) / (2 * epsilon[k]) ei[k] = 0.0 grad = grad.squeeze() axes = [0, 1, 2][:grad.ndim] axes[:2] = axes[1::-1] return np.transpose(grad, axes=axes).squeeze()
python
def approx_fprime(x, f, epsilon=None, args=(), kwargs=None, centered=True): """ Gradient of function, or Jacobian if function fun returns 1d array Parameters ---------- x : array parameters at which the derivative is evaluated fun : function `fun(*((x,)+args), **kwargs)` returning either one value or 1d array epsilon : float, optional Stepsize, if None, optimal stepsize is used. This is _EPS**(1/2)*x for `centered` == False and _EPS**(1/3)*x for `centered` == True. args : tuple Tuple of additional arguments for function `fun`. kwargs : dict Dictionary of additional keyword arguments for function `fun`. centered : bool Whether central difference should be returned. If not, does forward differencing. Returns ------- grad : array gradient or Jacobian Notes ----- If fun returns a 1d array, it returns a Jacobian. If a 2d array is returned by fun (e.g., with a value for each observation), it returns a 3d array with the Jacobian of each observation with shape xk x nobs x xk. I.e., the Jacobian of the first observation would be [:, 0, :] """ kwargs = {} if kwargs is None else kwargs n = len(x) f0 = f(*(x,) + args, **kwargs) dim = np.atleast_1d(f0).shape # it could be a scalar grad = np.zeros((n,) + dim, float) ei = np.zeros(np.shape(x), float) if not centered: epsilon = _get_epsilon(x, 2, epsilon, n) for k in range(n): ei[k] = epsilon[k] grad[k, :] = (f(*(x + ei,) + args, **kwargs) - f0) / epsilon[k] ei[k] = 0.0 else: epsilon = _get_epsilon(x, 3, epsilon, n) / 2. for k in range(n): ei[k] = epsilon[k] grad[k, :] = (f(*(x + ei,) + args, **kwargs) - f(*(x - ei,) + args, **kwargs)) / (2 * epsilon[k]) ei[k] = 0.0 grad = grad.squeeze() axes = [0, 1, 2][:grad.ndim] axes[:2] = axes[1::-1] return np.transpose(grad, axes=axes).squeeze()
[ "def", "approx_fprime", "(", "x", ",", "f", ",", "epsilon", "=", "None", ",", "args", "=", "(", ")", ",", "kwargs", "=", "None", ",", "centered", "=", "True", ")", ":", "kwargs", "=", "{", "}", "if", "kwargs", "is", "None", "else", "kwargs", "n",...
Gradient of function, or Jacobian if function fun returns 1d array Parameters ---------- x : array parameters at which the derivative is evaluated fun : function `fun(*((x,)+args), **kwargs)` returning either one value or 1d array epsilon : float, optional Stepsize, if None, optimal stepsize is used. This is _EPS**(1/2)*x for `centered` == False and _EPS**(1/3)*x for `centered` == True. args : tuple Tuple of additional arguments for function `fun`. kwargs : dict Dictionary of additional keyword arguments for function `fun`. centered : bool Whether central difference should be returned. If not, does forward differencing. Returns ------- grad : array gradient or Jacobian Notes ----- If fun returns a 1d array, it returns a Jacobian. If a 2d array is returned by fun (e.g., with a value for each observation), it returns a 3d array with the Jacobian of each observation with shape xk x nobs x xk. I.e., the Jacobian of the first observation would be [:, 0, :]
[ "Gradient", "of", "function", "or", "Jacobian", "if", "function", "fun", "returns", "1d", "array" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/nd_statsmodels.py#L23-L79
train
208,158
pbrod/numdifftools
src/numdifftools/profiletools.py
do_cprofile
def do_cprofile(func): """ Decorator to profile a function It gives good numbers on various function calls but it omits a vital piece of information: what is it about a function that makes it so slow? However, it is a great start to basic profiling. Sometimes it can even point you to the solution with very little fuss. I often use it as a gut check to start the debugging process before I dig deeper into the specific functions that are either slow are called way too often. Pros: No external dependencies and quite fast. Useful for quick high-level checks. Cons: Rather limited information that usually requires deeper debugging; reports are a bit unintuitive, especially for complex codebases. See also -------- do_profile, test_do_profile """ def profiled_func(*args, **kwargs): profile = cProfile.Profile() try: profile.enable() result = func(*args, **kwargs) profile.disable() return result finally: profile.print_stats() return profiled_func
python
def do_cprofile(func): """ Decorator to profile a function It gives good numbers on various function calls but it omits a vital piece of information: what is it about a function that makes it so slow? However, it is a great start to basic profiling. Sometimes it can even point you to the solution with very little fuss. I often use it as a gut check to start the debugging process before I dig deeper into the specific functions that are either slow are called way too often. Pros: No external dependencies and quite fast. Useful for quick high-level checks. Cons: Rather limited information that usually requires deeper debugging; reports are a bit unintuitive, especially for complex codebases. See also -------- do_profile, test_do_profile """ def profiled_func(*args, **kwargs): profile = cProfile.Profile() try: profile.enable() result = func(*args, **kwargs) profile.disable() return result finally: profile.print_stats() return profiled_func
[ "def", "do_cprofile", "(", "func", ")", ":", "def", "profiled_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "profile", "=", "cProfile", ".", "Profile", "(", ")", "try", ":", "profile", ".", "enable", "(", ")", "result", "=", "func", "...
Decorator to profile a function It gives good numbers on various function calls but it omits a vital piece of information: what is it about a function that makes it so slow? However, it is a great start to basic profiling. Sometimes it can even point you to the solution with very little fuss. I often use it as a gut check to start the debugging process before I dig deeper into the specific functions that are either slow are called way too often. Pros: No external dependencies and quite fast. Useful for quick high-level checks. Cons: Rather limited information that usually requires deeper debugging; reports are a bit unintuitive, especially for complex codebases. See also -------- do_profile, test_do_profile
[ "Decorator", "to", "profile", "a", "function" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/profiletools.py#L143-L176
train
208,159
pbrod/numdifftools
src/numdifftools/extrapolation.py
convolve
def convolve(sequence, rule, **kwds): """Wrapper around scipy.ndimage.convolve1d that allows complex input.""" dtype = np.result_type(float, np.ravel(sequence)[0]) seq = np.asarray(sequence, dtype=dtype) if np.iscomplexobj(seq): return (convolve1d(seq.real, rule, **kwds) + 1j * convolve1d(seq.imag, rule, **kwds)) return convolve1d(seq, rule, **kwds)
python
def convolve(sequence, rule, **kwds): """Wrapper around scipy.ndimage.convolve1d that allows complex input.""" dtype = np.result_type(float, np.ravel(sequence)[0]) seq = np.asarray(sequence, dtype=dtype) if np.iscomplexobj(seq): return (convolve1d(seq.real, rule, **kwds) + 1j * convolve1d(seq.imag, rule, **kwds)) return convolve1d(seq, rule, **kwds)
[ "def", "convolve", "(", "sequence", ",", "rule", ",", "*", "*", "kwds", ")", ":", "dtype", "=", "np", ".", "result_type", "(", "float", ",", "np", ".", "ravel", "(", "sequence", ")", "[", "0", "]", ")", "seq", "=", "np", ".", "asarray", "(", "s...
Wrapper around scipy.ndimage.convolve1d that allows complex input.
[ "Wrapper", "around", "scipy", ".", "ndimage", ".", "convolve1d", "that", "allows", "complex", "input", "." ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/extrapolation.py#L22-L28
train
208,160
pbrod/numdifftools
src/numdifftools/extrapolation.py
dea3
def dea3(v0, v1, v2, symmetric=False): """ Extrapolate a slowly convergent sequence Parameters ---------- v0, v1, v2 : array-like 3 values of a convergent sequence to extrapolate Returns ------- result : array-like extrapolated value abserr : array-like absolute error estimate Notes ----- DEA3 attempts to extrapolate nonlinearly to a better estimate of the sequence's limiting value, thus improving the rate of convergence. The routine is based on the epsilon algorithm of P. Wynn, see [1]_. Examples -------- # integrate sin(x) from 0 to pi/2 >>> import numpy as np >>> import numdifftools as nd >>> Ei= np.zeros(3) >>> linfun = lambda i : np.linspace(0, np.pi/2., 2**(i+5)+1) >>> for k in np.arange(3): ... x = linfun(k) ... Ei[k] = np.trapz(np.sin(x),x) >>> [En, err] = nd.dea3(Ei[0], Ei[1], Ei[2]) >>> truErr = np.abs(En-1.) >>> np.all(truErr < err) True >>> np.allclose(En, 1) True >>> np.all(np.abs(Ei-1)<1e-3) True See also -------- dea References ---------- .. [1] C. Brezinski and M. Redivo Zaglia (1991) "Extrapolation Methods. Theory and Practice", North-Holland. .. [2] C. Brezinski (1977) "Acceleration de la convergence en analyse numerique", "Lecture Notes in Math.", vol. 584, Springer-Verlag, New York, 1977. .. [3] E. J. Weniger (1989) "Nonlinear sequence transformations for the acceleration of convergence and the summation of divergent series" Computer Physics Reports Vol. 10, 189 - 371 http://arxiv.org/abs/math/0306302v1 """ e0, e1, e2 = np.atleast_1d(v0, v1, v2) with warnings.catch_warnings(): warnings.simplefilter("ignore") # ignore division by zero and overflow delta2, delta1 = e2 - e1, e1 - e0 err2, err1 = np.abs(delta2), np.abs(delta1) tol2, tol1 = max_abs(e2, e1) * _EPS, max_abs(e1, e0) * _EPS delta1[err1 < _TINY] = _TINY delta2[err2 < _TINY] = _TINY # avoid division by zero and overflow ss = 1.0 / delta2 - 1.0 / delta1 + _TINY smalle2 = abs(ss * e1) <= 1.0e-3 converged = (err1 <= tol1) & (err2 <= tol2) | smalle2 result = np.where(converged, e2 * 1.0, e1 + 1.0 / ss) abserr = err1 + err2 + np.where(converged, tol2 * 10, np.abs(result - e2)) if symmetric and len(result) > 1: return result[:-1], abserr[1:] return result, abserr
python
def dea3(v0, v1, v2, symmetric=False): """ Extrapolate a slowly convergent sequence Parameters ---------- v0, v1, v2 : array-like 3 values of a convergent sequence to extrapolate Returns ------- result : array-like extrapolated value abserr : array-like absolute error estimate Notes ----- DEA3 attempts to extrapolate nonlinearly to a better estimate of the sequence's limiting value, thus improving the rate of convergence. The routine is based on the epsilon algorithm of P. Wynn, see [1]_. Examples -------- # integrate sin(x) from 0 to pi/2 >>> import numpy as np >>> import numdifftools as nd >>> Ei= np.zeros(3) >>> linfun = lambda i : np.linspace(0, np.pi/2., 2**(i+5)+1) >>> for k in np.arange(3): ... x = linfun(k) ... Ei[k] = np.trapz(np.sin(x),x) >>> [En, err] = nd.dea3(Ei[0], Ei[1], Ei[2]) >>> truErr = np.abs(En-1.) >>> np.all(truErr < err) True >>> np.allclose(En, 1) True >>> np.all(np.abs(Ei-1)<1e-3) True See also -------- dea References ---------- .. [1] C. Brezinski and M. Redivo Zaglia (1991) "Extrapolation Methods. Theory and Practice", North-Holland. .. [2] C. Brezinski (1977) "Acceleration de la convergence en analyse numerique", "Lecture Notes in Math.", vol. 584, Springer-Verlag, New York, 1977. .. [3] E. J. Weniger (1989) "Nonlinear sequence transformations for the acceleration of convergence and the summation of divergent series" Computer Physics Reports Vol. 10, 189 - 371 http://arxiv.org/abs/math/0306302v1 """ e0, e1, e2 = np.atleast_1d(v0, v1, v2) with warnings.catch_warnings(): warnings.simplefilter("ignore") # ignore division by zero and overflow delta2, delta1 = e2 - e1, e1 - e0 err2, err1 = np.abs(delta2), np.abs(delta1) tol2, tol1 = max_abs(e2, e1) * _EPS, max_abs(e1, e0) * _EPS delta1[err1 < _TINY] = _TINY delta2[err2 < _TINY] = _TINY # avoid division by zero and overflow ss = 1.0 / delta2 - 1.0 / delta1 + _TINY smalle2 = abs(ss * e1) <= 1.0e-3 converged = (err1 <= tol1) & (err2 <= tol2) | smalle2 result = np.where(converged, e2 * 1.0, e1 + 1.0 / ss) abserr = err1 + err2 + np.where(converged, tol2 * 10, np.abs(result - e2)) if symmetric and len(result) > 1: return result[:-1], abserr[1:] return result, abserr
[ "def", "dea3", "(", "v0", ",", "v1", ",", "v2", ",", "symmetric", "=", "False", ")", ":", "e0", ",", "e1", ",", "e2", "=", "np", ".", "atleast_1d", "(", "v0", ",", "v1", ",", "v2", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", ...
Extrapolate a slowly convergent sequence Parameters ---------- v0, v1, v2 : array-like 3 values of a convergent sequence to extrapolate Returns ------- result : array-like extrapolated value abserr : array-like absolute error estimate Notes ----- DEA3 attempts to extrapolate nonlinearly to a better estimate of the sequence's limiting value, thus improving the rate of convergence. The routine is based on the epsilon algorithm of P. Wynn, see [1]_. Examples -------- # integrate sin(x) from 0 to pi/2 >>> import numpy as np >>> import numdifftools as nd >>> Ei= np.zeros(3) >>> linfun = lambda i : np.linspace(0, np.pi/2., 2**(i+5)+1) >>> for k in np.arange(3): ... x = linfun(k) ... Ei[k] = np.trapz(np.sin(x),x) >>> [En, err] = nd.dea3(Ei[0], Ei[1], Ei[2]) >>> truErr = np.abs(En-1.) >>> np.all(truErr < err) True >>> np.allclose(En, 1) True >>> np.all(np.abs(Ei-1)<1e-3) True See also -------- dea References ---------- .. [1] C. Brezinski and M. Redivo Zaglia (1991) "Extrapolation Methods. Theory and Practice", North-Holland. .. [2] C. Brezinski (1977) "Acceleration de la convergence en analyse numerique", "Lecture Notes in Math.", vol. 584, Springer-Verlag, New York, 1977. .. [3] E. J. Weniger (1989) "Nonlinear sequence transformations for the acceleration of convergence and the summation of divergent series" Computer Physics Reports Vol. 10, 189 - 371 http://arxiv.org/abs/math/0306302v1
[ "Extrapolate", "a", "slowly", "convergent", "sequence" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/extrapolation.py#L316-L394
train
208,161
pbrod/numdifftools
src/numdifftools/core.py
Derivative._fd_matrix
def _fd_matrix(step_ratio, parity, nterms): """ Return matrix for finite difference and complex step derivation. Parameters ---------- step_ratio : real scalar ratio between steps in unequally spaced difference rule. parity : scalar, integer 0 (one sided, all terms included but zeroth order) 1 (only odd terms included) 2 (only even terms included) 3 (only every 4'th order terms included starting from order 2) 4 (only every 4'th order terms included starting from order 4) 5 (only every 4'th order terms included starting from order 1) 6 (only every 4'th order terms included starting from order 3) nterms : scalar, integer number of terms """ _assert(0 <= parity <= 6, 'Parity must be 0, 1, 2, 3, 4, 5 or 6! ({0:d})'.format(parity)) step = [1, 2, 2, 4, 4, 4, 4][parity] inv_sr = 1.0 / step_ratio offset = [1, 1, 2, 2, 4, 1, 3][parity] c0 = [1.0, 1.0, 1.0, 2.0, 24.0, 1.0, 6.0][parity] c = c0 / \ special.factorial(np.arange(offset, step * nterms + offset, step)) [i, j] = np.ogrid[0:nterms, 0:nterms] return np.atleast_2d(c[j] * inv_sr ** (i * (step * j + offset)))
python
def _fd_matrix(step_ratio, parity, nterms): """ Return matrix for finite difference and complex step derivation. Parameters ---------- step_ratio : real scalar ratio between steps in unequally spaced difference rule. parity : scalar, integer 0 (one sided, all terms included but zeroth order) 1 (only odd terms included) 2 (only even terms included) 3 (only every 4'th order terms included starting from order 2) 4 (only every 4'th order terms included starting from order 4) 5 (only every 4'th order terms included starting from order 1) 6 (only every 4'th order terms included starting from order 3) nterms : scalar, integer number of terms """ _assert(0 <= parity <= 6, 'Parity must be 0, 1, 2, 3, 4, 5 or 6! ({0:d})'.format(parity)) step = [1, 2, 2, 4, 4, 4, 4][parity] inv_sr = 1.0 / step_ratio offset = [1, 1, 2, 2, 4, 1, 3][parity] c0 = [1.0, 1.0, 1.0, 2.0, 24.0, 1.0, 6.0][parity] c = c0 / \ special.factorial(np.arange(offset, step * nterms + offset, step)) [i, j] = np.ogrid[0:nterms, 0:nterms] return np.atleast_2d(c[j] * inv_sr ** (i * (step * j + offset)))
[ "def", "_fd_matrix", "(", "step_ratio", ",", "parity", ",", "nterms", ")", ":", "_assert", "(", "0", "<=", "parity", "<=", "6", ",", "'Parity must be 0, 1, 2, 3, 4, 5 or 6! ({0:d})'", ".", "format", "(", "parity", ")", ")", "step", "=", "[", "1", ",", "2",...
Return matrix for finite difference and complex step derivation. Parameters ---------- step_ratio : real scalar ratio between steps in unequally spaced difference rule. parity : scalar, integer 0 (one sided, all terms included but zeroth order) 1 (only odd terms included) 2 (only even terms included) 3 (only every 4'th order terms included starting from order 2) 4 (only every 4'th order terms included starting from order 4) 5 (only every 4'th order terms included starting from order 1) 6 (only every 4'th order terms included starting from order 3) nterms : scalar, integer number of terms
[ "Return", "matrix", "for", "finite", "difference", "and", "complex", "step", "derivation", "." ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/core.py#L324-L352
train
208,162
pbrod/numdifftools
src/numdifftools/core.py
Derivative._apply_fd_rule
def _apply_fd_rule(self, step_ratio, sequence, steps): """ Return derivative estimates of fun at x0 for a sequence of stepsizes h Member variables used --------------------- n """ f_del, h, original_shape = self._vstack(sequence, steps) fd_rule = self._get_finite_difference_rule(step_ratio) ne = h.shape[0] nr = fd_rule.size - 1 _assert(nr < ne, 'num_steps ({0:d}) must be larger than ' '({1:d}) n + order - 1 = {2:d} + {3:d} -1' ' ({4:s})'.format(ne, nr+1, self.n, self.order, self.method)) f_diff = convolve(f_del, fd_rule[::-1], axis=0, origin=nr // 2) der_init = f_diff / (h ** self.n) ne = max(ne - nr, 1) return der_init[:ne], h[:ne], original_shape
python
def _apply_fd_rule(self, step_ratio, sequence, steps): """ Return derivative estimates of fun at x0 for a sequence of stepsizes h Member variables used --------------------- n """ f_del, h, original_shape = self._vstack(sequence, steps) fd_rule = self._get_finite_difference_rule(step_ratio) ne = h.shape[0] nr = fd_rule.size - 1 _assert(nr < ne, 'num_steps ({0:d}) must be larger than ' '({1:d}) n + order - 1 = {2:d} + {3:d} -1' ' ({4:s})'.format(ne, nr+1, self.n, self.order, self.method)) f_diff = convolve(f_del, fd_rule[::-1], axis=0, origin=nr // 2) der_init = f_diff / (h ** self.n) ne = max(ne - nr, 1) return der_init[:ne], h[:ne], original_shape
[ "def", "_apply_fd_rule", "(", "self", ",", "step_ratio", ",", "sequence", ",", "steps", ")", ":", "f_del", ",", "h", ",", "original_shape", "=", "self", ".", "_vstack", "(", "sequence", ",", "steps", ")", "fd_rule", "=", "self", ".", "_get_finite_differenc...
Return derivative estimates of fun at x0 for a sequence of stepsizes h Member variables used --------------------- n
[ "Return", "derivative", "estimates", "of", "fun", "at", "x0", "for", "a", "sequence", "of", "stepsizes", "h" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/core.py#L409-L428
train
208,163
pbrod/numdifftools
src/numdifftools/core.py
Hessian._complex_even
def _complex_even(f, fx, x, h): """ Calculate Hessian with complex-step derivative approximation The stepsize is the same for the complex and the finite difference part """ n = len(x) ee = np.diag(h) hess = 2. * np.outer(h, h) for i in range(n): for j in range(i, n): hess[i, j] = (f(x + 1j * ee[i] + ee[j]) - f(x + 1j * ee[i] - ee[j])).imag / hess[j, i] hess[j, i] = hess[i, j] return hess
python
def _complex_even(f, fx, x, h): """ Calculate Hessian with complex-step derivative approximation The stepsize is the same for the complex and the finite difference part """ n = len(x) ee = np.diag(h) hess = 2. * np.outer(h, h) for i in range(n): for j in range(i, n): hess[i, j] = (f(x + 1j * ee[i] + ee[j]) - f(x + 1j * ee[i] - ee[j])).imag / hess[j, i] hess[j, i] = hess[i, j] return hess
[ "def", "_complex_even", "(", "f", ",", "fx", ",", "x", ",", "h", ")", ":", "n", "=", "len", "(", "x", ")", "ee", "=", "np", ".", "diag", "(", "h", ")", "hess", "=", "2.", "*", "np", ".", "outer", "(", "h", ",", "h", ")", "for", "i", "in...
Calculate Hessian with complex-step derivative approximation The stepsize is the same for the complex and the finite difference part
[ "Calculate", "Hessian", "with", "complex", "-", "step", "derivative", "approximation" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/core.py#L920-L934
train
208,164
pbrod/numdifftools
src/numdifftools/core.py
Hessian._multicomplex2
def _multicomplex2(f, fx, x, h): """Calculate Hessian with Bicomplex-step derivative approximation""" n = len(x) ee = np.diag(h) hess = np.outer(h, h) cmplx_wrap = Bicomplex.__array_wrap__ for i in range(n): for j in range(i, n): zph = Bicomplex(x + 1j * ee[i, :], ee[j, :]) hess[i, j] = cmplx_wrap(f(zph)).imag12 / hess[j, i] hess[j, i] = hess[i, j] return hess
python
def _multicomplex2(f, fx, x, h): """Calculate Hessian with Bicomplex-step derivative approximation""" n = len(x) ee = np.diag(h) hess = np.outer(h, h) cmplx_wrap = Bicomplex.__array_wrap__ for i in range(n): for j in range(i, n): zph = Bicomplex(x + 1j * ee[i, :], ee[j, :]) hess[i, j] = cmplx_wrap(f(zph)).imag12 / hess[j, i] hess[j, i] = hess[i, j] return hess
[ "def", "_multicomplex2", "(", "f", ",", "fx", ",", "x", ",", "h", ")", ":", "n", "=", "len", "(", "x", ")", "ee", "=", "np", ".", "diag", "(", "h", ")", "hess", "=", "np", ".", "outer", "(", "h", ",", "h", ")", "cmplx_wrap", "=", "Bicomplex...
Calculate Hessian with Bicomplex-step derivative approximation
[ "Calculate", "Hessian", "with", "Bicomplex", "-", "step", "derivative", "approximation" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/core.py#L937-L948
train
208,165
pbrod/numdifftools
src/numdifftools/core.py
Hessian._central_even
def _central_even(f, fx, x, h): """Eq 9.""" n = len(x) ee = np.diag(h) dtype = np.result_type(fx) hess = np.empty((n, n), dtype=dtype) np.outer(h, h, out=hess) for i in range(n): hess[i, i] = (f(x + 2 * ee[i, :]) - 2 * fx + f(x - 2 * ee[i, :])) / (4. * hess[i, i]) for j in range(i + 1, n): hess[i, j] = (f(x + ee[i, :] + ee[j, :]) - f(x + ee[i, :] - ee[j, :]) - f(x - ee[i, :] + ee[j, :]) + f(x - ee[i, :] - ee[j, :])) / (4. * hess[j, i]) hess[j, i] = hess[i, j] return hess
python
def _central_even(f, fx, x, h): """Eq 9.""" n = len(x) ee = np.diag(h) dtype = np.result_type(fx) hess = np.empty((n, n), dtype=dtype) np.outer(h, h, out=hess) for i in range(n): hess[i, i] = (f(x + 2 * ee[i, :]) - 2 * fx + f(x - 2 * ee[i, :])) / (4. * hess[i, i]) for j in range(i + 1, n): hess[i, j] = (f(x + ee[i, :] + ee[j, :]) - f(x + ee[i, :] - ee[j, :]) - f(x - ee[i, :] + ee[j, :]) + f(x - ee[i, :] - ee[j, :])) / (4. * hess[j, i]) hess[j, i] = hess[i, j] return hess
[ "def", "_central_even", "(", "f", ",", "fx", ",", "x", ",", "h", ")", ":", "n", "=", "len", "(", "x", ")", "ee", "=", "np", ".", "diag", "(", "h", ")", "dtype", "=", "np", ".", "result_type", "(", "fx", ")", "hess", "=", "np", ".", "empty",...
Eq 9.
[ "Eq", "9", "." ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/core.py#L951-L966
train
208,166
pbrod/numdifftools
src/numdifftools/core.py
Hessian._central2
def _central2(f, fx, x, h): """Eq. 8""" n = len(x) ee = np.diag(h) dtype = np.result_type(fx) g = np.empty(n, dtype=dtype) gg = np.empty(n, dtype=dtype) for i in range(n): g[i] = f(x + ee[i]) gg[i] = f(x - ee[i]) hess = np.empty((n, n), dtype=dtype) np.outer(h, h, out=hess) for i in range(n): for j in range(i, n): hess[i, j] = (f(x + ee[i, :] + ee[j, :]) + f(x - ee[i, :] - ee[j, :]) - g[i] - g[j] + fx - gg[i] - gg[j] + fx) / (2 * hess[j, i]) hess[j, i] = hess[i, j] return hess
python
def _central2(f, fx, x, h): """Eq. 8""" n = len(x) ee = np.diag(h) dtype = np.result_type(fx) g = np.empty(n, dtype=dtype) gg = np.empty(n, dtype=dtype) for i in range(n): g[i] = f(x + ee[i]) gg[i] = f(x - ee[i]) hess = np.empty((n, n), dtype=dtype) np.outer(h, h, out=hess) for i in range(n): for j in range(i, n): hess[i, j] = (f(x + ee[i, :] + ee[j, :]) + f(x - ee[i, :] - ee[j, :]) - g[i] - g[j] + fx - gg[i] - gg[j] + fx) / (2 * hess[j, i]) hess[j, i] = hess[i, j] return hess
[ "def", "_central2", "(", "f", ",", "fx", ",", "x", ",", "h", ")", ":", "n", "=", "len", "(", "x", ")", "ee", "=", "np", ".", "diag", "(", "h", ")", "dtype", "=", "np", ".", "result_type", "(", "fx", ")", "g", "=", "np", ".", "empty", "(",...
Eq. 8
[ "Eq", ".", "8" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/core.py#L969-L989
train
208,167
pbrod/numdifftools
src/numdifftools/nd_algopy.py
directionaldiff
def directionaldiff(f, x0, vec, **options): """ Return directional derivative of a function of n variables Parameters ---------- fun: callable analytical function to differentiate. x0: array vector location at which to differentiate fun. If x0 is an nxm array, then fun is assumed to be a function of n*m variables. vec: array vector defining the line along which to take the derivative. It should be the same size as x0, but need not be a vector of unit length. **options: optional arguments to pass on to Derivative. Returns ------- dder: scalar estimate of the first derivative of fun in the specified direction. Examples -------- At the global minimizer (1,1) of the Rosenbrock function, compute the directional derivative in the direction [1 2] >>> import numpy as np >>> import numdifftools as nd >>> vec = np.r_[1, 2] >>> rosen = lambda x: (1-x[0])**2 + 105*(x[1]-x[0]**2)**2 >>> dd, info = nd.directionaldiff(rosen, [1, 1], vec, full_output=True) >>> np.allclose(dd, 0) True >>> np.abs(info.error_estimate)<1e-14 True See also -------- Derivative, Gradient """ x0 = np.asarray(x0) vec = np.asarray(vec) if x0.size != vec.size: raise ValueError('vec and x0 must be the same shapes') vec = np.reshape(vec/np.linalg.norm(vec.ravel()), x0.shape) return Derivative(lambda t: f(x0+t*vec), **options)(0)
python
def directionaldiff(f, x0, vec, **options): """ Return directional derivative of a function of n variables Parameters ---------- fun: callable analytical function to differentiate. x0: array vector location at which to differentiate fun. If x0 is an nxm array, then fun is assumed to be a function of n*m variables. vec: array vector defining the line along which to take the derivative. It should be the same size as x0, but need not be a vector of unit length. **options: optional arguments to pass on to Derivative. Returns ------- dder: scalar estimate of the first derivative of fun in the specified direction. Examples -------- At the global minimizer (1,1) of the Rosenbrock function, compute the directional derivative in the direction [1 2] >>> import numpy as np >>> import numdifftools as nd >>> vec = np.r_[1, 2] >>> rosen = lambda x: (1-x[0])**2 + 105*(x[1]-x[0]**2)**2 >>> dd, info = nd.directionaldiff(rosen, [1, 1], vec, full_output=True) >>> np.allclose(dd, 0) True >>> np.abs(info.error_estimate)<1e-14 True See also -------- Derivative, Gradient """ x0 = np.asarray(x0) vec = np.asarray(vec) if x0.size != vec.size: raise ValueError('vec and x0 must be the same shapes') vec = np.reshape(vec/np.linalg.norm(vec.ravel()), x0.shape) return Derivative(lambda t: f(x0+t*vec), **options)(0)
[ "def", "directionaldiff", "(", "f", ",", "x0", ",", "vec", ",", "*", "*", "options", ")", ":", "x0", "=", "np", ".", "asarray", "(", "x0", ")", "vec", "=", "np", ".", "asarray", "(", "vec", ")", "if", "x0", ".", "size", "!=", "vec", ".", "siz...
Return directional derivative of a function of n variables Parameters ---------- fun: callable analytical function to differentiate. x0: array vector location at which to differentiate fun. If x0 is an nxm array, then fun is assumed to be a function of n*m variables. vec: array vector defining the line along which to take the derivative. It should be the same size as x0, but need not be a vector of unit length. **options: optional arguments to pass on to Derivative. Returns ------- dder: scalar estimate of the first derivative of fun in the specified direction. Examples -------- At the global minimizer (1,1) of the Rosenbrock function, compute the directional derivative in the direction [1 2] >>> import numpy as np >>> import numdifftools as nd >>> vec = np.r_[1, 2] >>> rosen = lambda x: (1-x[0])**2 + 105*(x[1]-x[0]**2)**2 >>> dd, info = nd.directionaldiff(rosen, [1, 1], vec, full_output=True) >>> np.allclose(dd, 0) True >>> np.abs(info.error_estimate)<1e-14 True See also -------- Derivative, Gradient
[ "Return", "directional", "derivative", "of", "a", "function", "of", "n", "variables" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/nd_algopy.py#L485-L533
train
208,168
pbrod/numdifftools
src/numdifftools/step_generators.py
valarray
def valarray(shape, value=np.NaN, typecode=None): """Return an array of all value.""" if typecode is None: typecode = bool out = np.ones(shape, dtype=typecode) * value if not isinstance(out, np.ndarray): out = np.asarray(out) return out
python
def valarray(shape, value=np.NaN, typecode=None): """Return an array of all value.""" if typecode is None: typecode = bool out = np.ones(shape, dtype=typecode) * value if not isinstance(out, np.ndarray): out = np.asarray(out) return out
[ "def", "valarray", "(", "shape", ",", "value", "=", "np", ".", "NaN", ",", "typecode", "=", "None", ")", ":", "if", "typecode", "is", "None", ":", "typecode", "=", "bool", "out", "=", "np", ".", "ones", "(", "shape", ",", "dtype", "=", "typecode", ...
Return an array of all value.
[ "Return", "an", "array", "of", "all", "value", "." ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/step_generators.py#L21-L29
train
208,169
pbrod/numdifftools
src/numdifftools/step_generators.py
nominal_step
def nominal_step(x=None): """Return nominal step""" if x is None: return 1.0 return np.log1p(np.abs(x)).clip(min=1.0)
python
def nominal_step(x=None): """Return nominal step""" if x is None: return 1.0 return np.log1p(np.abs(x)).clip(min=1.0)
[ "def", "nominal_step", "(", "x", "=", "None", ")", ":", "if", "x", "is", "None", ":", "return", "1.0", "return", "np", ".", "log1p", "(", "np", ".", "abs", "(", "x", ")", ")", ".", "clip", "(", "min", "=", "1.0", ")" ]
Return nominal step
[ "Return", "nominal", "step" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/step_generators.py#L32-L36
train
208,170
pbrod/numdifftools
src/numdifftools/finite_difference.py
LogRule.rule
def rule(self): """ Return finite differencing rule. The rule is for a nominal unit step size, and must be scaled later to reflect the local step size. Member methods used ------------------- _fd_matrix Member variables used --------------------- n order method """ step_ratio = self.step_ratio method = self.method if method in ('multicomplex', ) or self.n == 0: return np.ones((1,)) order, method_order = self.n - 1, self._method_order parity = self._parity(method, order, method_order) step = self._richardson_step() num_terms, ix = (order + method_order) // step, order // step fd_rules = FD_RULES.get((step_ratio, parity, num_terms)) if fd_rules is None: fd_mat = self._fd_matrix(step_ratio, parity, num_terms) fd_rules = linalg.pinv(fd_mat) FD_RULES[(step_ratio, parity, num_terms)] = fd_rules if self._flip_fd_rule: return -fd_rules[ix] return fd_rules[ix]
python
def rule(self): """ Return finite differencing rule. The rule is for a nominal unit step size, and must be scaled later to reflect the local step size. Member methods used ------------------- _fd_matrix Member variables used --------------------- n order method """ step_ratio = self.step_ratio method = self.method if method in ('multicomplex', ) or self.n == 0: return np.ones((1,)) order, method_order = self.n - 1, self._method_order parity = self._parity(method, order, method_order) step = self._richardson_step() num_terms, ix = (order + method_order) // step, order // step fd_rules = FD_RULES.get((step_ratio, parity, num_terms)) if fd_rules is None: fd_mat = self._fd_matrix(step_ratio, parity, num_terms) fd_rules = linalg.pinv(fd_mat) FD_RULES[(step_ratio, parity, num_terms)] = fd_rules if self._flip_fd_rule: return -fd_rules[ix] return fd_rules[ix]
[ "def", "rule", "(", "self", ")", ":", "step_ratio", "=", "self", ".", "step_ratio", "method", "=", "self", ".", "method", "if", "method", "in", "(", "'multicomplex'", ",", ")", "or", "self", ".", "n", "==", "0", ":", "return", "np", ".", "ones", "(...
Return finite differencing rule. The rule is for a nominal unit step size, and must be scaled later to reflect the local step size. Member methods used ------------------- _fd_matrix Member variables used --------------------- n order method
[ "Return", "finite", "differencing", "rule", "." ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/finite_difference.py#L206-L240
train
208,171
pbrod/numdifftools
src/numdifftools/finite_difference.py
LogRule.apply
def apply(self, f_del, h): """ Apply finite difference rule along the first axis. """ fd_rule = self.rule ne = h.shape[0] nr = fd_rule.size - 1 _assert(nr < ne, 'num_steps ({0:d}) must be larger than ' '({1:d}) n + order - 1 = {2:d} + {3:d} -1' ' ({4:s})'.format(ne, nr+1, self.n, self.order, self.method)) f_diff = convolve(f_del, fd_rule[::-1], axis=0, origin=nr // 2) der_init = f_diff / (h ** self.n) ne = max(ne - nr, 1) return der_init[:ne], h[:ne]
python
def apply(self, f_del, h): """ Apply finite difference rule along the first axis. """ fd_rule = self.rule ne = h.shape[0] nr = fd_rule.size - 1 _assert(nr < ne, 'num_steps ({0:d}) must be larger than ' '({1:d}) n + order - 1 = {2:d} + {3:d} -1' ' ({4:s})'.format(ne, nr+1, self.n, self.order, self.method)) f_diff = convolve(f_del, fd_rule[::-1], axis=0, origin=nr // 2) der_init = f_diff / (h ** self.n) ne = max(ne - nr, 1) return der_init[:ne], h[:ne]
[ "def", "apply", "(", "self", ",", "f_del", ",", "h", ")", ":", "fd_rule", "=", "self", ".", "rule", "ne", "=", "h", ".", "shape", "[", "0", "]", "nr", "=", "fd_rule", ".", "size", "-", "1", "_assert", "(", "nr", "<", "ne", ",", "'num_steps ({0:...
Apply finite difference rule along the first axis.
[ "Apply", "finite", "difference", "rule", "along", "the", "first", "axis", "." ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/finite_difference.py#L242-L258
train
208,172
pbrod/numdifftools
src/numdifftools/fornberg.py
fd_weights_all
def fd_weights_all(x, x0=0, n=1): """ Return finite difference weights for derivatives of all orders up to n. Parameters ---------- x : vector, length m x-coordinates for grid points x0 : scalar location where approximations are to be accurate n : scalar integer highest derivative that we want to find weights for Returns ------- weights : array, shape n+1 x m contains coefficients for the j'th derivative in row j (0 <= j <= n) Notes ----- The x values can be arbitrarily spaced but must be distinct and len(x) > n. The Fornberg algorithm is much more stable numerically than regular vandermonde systems for large values of n. See also -------- fd_weights References ---------- B. Fornberg (1998) "Calculation of weights_and_points in finite difference formulas", SIAM Review 40, pp. 685-691. http://www.scholarpedia.org/article/Finite_difference_method """ m = len(x) _assert(n < m, 'len(x) must be larger than n') weights = np.zeros((m, n + 1)) _fd_weights_all(weights, x, x0, n) return weights.T
python
def fd_weights_all(x, x0=0, n=1): """ Return finite difference weights for derivatives of all orders up to n. Parameters ---------- x : vector, length m x-coordinates for grid points x0 : scalar location where approximations are to be accurate n : scalar integer highest derivative that we want to find weights for Returns ------- weights : array, shape n+1 x m contains coefficients for the j'th derivative in row j (0 <= j <= n) Notes ----- The x values can be arbitrarily spaced but must be distinct and len(x) > n. The Fornberg algorithm is much more stable numerically than regular vandermonde systems for large values of n. See also -------- fd_weights References ---------- B. Fornberg (1998) "Calculation of weights_and_points in finite difference formulas", SIAM Review 40, pp. 685-691. http://www.scholarpedia.org/article/Finite_difference_method """ m = len(x) _assert(n < m, 'len(x) must be larger than n') weights = np.zeros((m, n + 1)) _fd_weights_all(weights, x, x0, n) return weights.T
[ "def", "fd_weights_all", "(", "x", ",", "x0", "=", "0", ",", "n", "=", "1", ")", ":", "m", "=", "len", "(", "x", ")", "_assert", "(", "n", "<", "m", ",", "'len(x) must be larger than n'", ")", "weights", "=", "np", ".", "zeros", "(", "(", "m", ...
Return finite difference weights for derivatives of all orders up to n. Parameters ---------- x : vector, length m x-coordinates for grid points x0 : scalar location where approximations are to be accurate n : scalar integer highest derivative that we want to find weights for Returns ------- weights : array, shape n+1 x m contains coefficients for the j'th derivative in row j (0 <= j <= n) Notes ----- The x values can be arbitrarily spaced but must be distinct and len(x) > n. The Fornberg algorithm is much more stable numerically than regular vandermonde systems for large values of n. See also -------- fd_weights References ---------- B. Fornberg (1998) "Calculation of weights_and_points in finite difference formulas", SIAM Review 40, pp. 685-691. http://www.scholarpedia.org/article/Finite_difference_method
[ "Return", "finite", "difference", "weights", "for", "derivatives", "of", "all", "orders", "up", "to", "n", "." ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/fornberg.py#L33-L75
train
208,173
pbrod/numdifftools
src/numdifftools/fornberg.py
fd_derivative
def fd_derivative(fx, x, n=1, m=2): """ Return the n'th derivative for all points using Finite Difference method. Parameters ---------- fx : vector function values which are evaluated on x i.e. fx[i] = f(x[i]) x : vector abscissas on which fx is evaluated. The x values can be arbitrarily spaced but must be distinct and len(x) > n. n : scalar integer order of derivative. m : scalar integer defines the stencil size. The stencil size is of 2 * mm + 1 points in the interior, and 2 * mm + 2 points for each of the 2 * mm boundary points where mm = n // 2 + m. fd_derivative evaluates an approximation for the n'th derivative of the vector function f(x) using the Fornberg finite difference method. Restrictions: 0 < n < len(x) and 2*mm+2 <= len(x) Examples -------- >>> import numpy as np >>> import numdifftools.fornberg as ndf >>> x = np.linspace(-1, 1, 25) >>> fx = np.exp(x) >>> df = ndf.fd_derivative(fx, x, n=1) >>> np.allclose(df, fx) True See also -------- fd_weights """ num_x = len(x) _assert(n < num_x, 'len(x) must be larger than n') _assert(num_x == len(fx), 'len(x) must be equal len(fx)') du = np.zeros_like(fx) mm = n // 2 + m size = 2 * mm + 2 # stencil size at boundary # 2 * mm boundary points for i in range(mm): du[i] = np.dot(fd_weights(x[:size], x0=x[i], n=n), fx[:size]) du[-i-1] = np.dot(fd_weights(x[-size:], x0=x[-i-1], n=n), fx[-size:]) # interior points for i in range(mm, num_x-mm): du[i] = np.dot(fd_weights(x[i-mm:i+mm+1], x0=x[i], n=n), fx[i-mm:i+mm+1]) return du
python
def fd_derivative(fx, x, n=1, m=2): """ Return the n'th derivative for all points using Finite Difference method. Parameters ---------- fx : vector function values which are evaluated on x i.e. fx[i] = f(x[i]) x : vector abscissas on which fx is evaluated. The x values can be arbitrarily spaced but must be distinct and len(x) > n. n : scalar integer order of derivative. m : scalar integer defines the stencil size. The stencil size is of 2 * mm + 1 points in the interior, and 2 * mm + 2 points for each of the 2 * mm boundary points where mm = n // 2 + m. fd_derivative evaluates an approximation for the n'th derivative of the vector function f(x) using the Fornberg finite difference method. Restrictions: 0 < n < len(x) and 2*mm+2 <= len(x) Examples -------- >>> import numpy as np >>> import numdifftools.fornberg as ndf >>> x = np.linspace(-1, 1, 25) >>> fx = np.exp(x) >>> df = ndf.fd_derivative(fx, x, n=1) >>> np.allclose(df, fx) True See also -------- fd_weights """ num_x = len(x) _assert(n < num_x, 'len(x) must be larger than n') _assert(num_x == len(fx), 'len(x) must be equal len(fx)') du = np.zeros_like(fx) mm = n // 2 + m size = 2 * mm + 2 # stencil size at boundary # 2 * mm boundary points for i in range(mm): du[i] = np.dot(fd_weights(x[:size], x0=x[i], n=n), fx[:size]) du[-i-1] = np.dot(fd_weights(x[-size:], x0=x[-i-1], n=n), fx[-size:]) # interior points for i in range(mm, num_x-mm): du[i] = np.dot(fd_weights(x[i-mm:i+mm+1], x0=x[i], n=n), fx[i-mm:i+mm+1]) return du
[ "def", "fd_derivative", "(", "fx", ",", "x", ",", "n", "=", "1", ",", "m", "=", "2", ")", ":", "num_x", "=", "len", "(", "x", ")", "_assert", "(", "n", "<", "num_x", ",", "'len(x) must be larger than n'", ")", "_assert", "(", "num_x", "==", "len", ...
Return the n'th derivative for all points using Finite Difference method. Parameters ---------- fx : vector function values which are evaluated on x i.e. fx[i] = f(x[i]) x : vector abscissas on which fx is evaluated. The x values can be arbitrarily spaced but must be distinct and len(x) > n. n : scalar integer order of derivative. m : scalar integer defines the stencil size. The stencil size is of 2 * mm + 1 points in the interior, and 2 * mm + 2 points for each of the 2 * mm boundary points where mm = n // 2 + m. fd_derivative evaluates an approximation for the n'th derivative of the vector function f(x) using the Fornberg finite difference method. Restrictions: 0 < n < len(x) and 2*mm+2 <= len(x) Examples -------- >>> import numpy as np >>> import numdifftools.fornberg as ndf >>> x = np.linspace(-1, 1, 25) >>> fx = np.exp(x) >>> df = ndf.fd_derivative(fx, x, n=1) >>> np.allclose(df, fx) True See also -------- fd_weights
[ "Return", "the", "n", "th", "derivative", "for", "all", "points", "using", "Finite", "Difference", "method", "." ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/fornberg.py#L126-L180
train
208,174
pbrod/numdifftools
src/numdifftools/fornberg.py
_poor_convergence
def _poor_convergence(z, r, f, bn, mvec): """ Test for poor convergence based on three function evaluations. This test evaluates the function at the three points and returns false if the relative error is greater than 1e-3. """ check_points = (-0.4 + 0.3j, 0.7 + 0.2j, 0.02 - 0.06j) diffs = [] ftests = [] for check_point in check_points: rtest = r * check_point ztest = z + rtest ftest = f(ztest) # Evaluate powerseries: comp = np.sum(bn * np.power(check_point, mvec)) ftests.append(ftest) diffs.append(comp - ftest) max_abs_error = np.max(np.abs(diffs)) max_f_value = np.max(np.abs(ftests)) return max_abs_error > 1e-3 * max_f_value
python
def _poor_convergence(z, r, f, bn, mvec): """ Test for poor convergence based on three function evaluations. This test evaluates the function at the three points and returns false if the relative error is greater than 1e-3. """ check_points = (-0.4 + 0.3j, 0.7 + 0.2j, 0.02 - 0.06j) diffs = [] ftests = [] for check_point in check_points: rtest = r * check_point ztest = z + rtest ftest = f(ztest) # Evaluate powerseries: comp = np.sum(bn * np.power(check_point, mvec)) ftests.append(ftest) diffs.append(comp - ftest) max_abs_error = np.max(np.abs(diffs)) max_f_value = np.max(np.abs(ftests)) return max_abs_error > 1e-3 * max_f_value
[ "def", "_poor_convergence", "(", "z", ",", "r", ",", "f", ",", "bn", ",", "mvec", ")", ":", "check_points", "=", "(", "-", "0.4", "+", "0.3j", ",", "0.7", "+", "0.2j", ",", "0.02", "-", "0.06j", ")", "diffs", "=", "[", "]", "ftests", "=", "[", ...
Test for poor convergence based on three function evaluations. This test evaluates the function at the three points and returns false if the relative error is greater than 1e-3.
[ "Test", "for", "poor", "convergence", "based", "on", "three", "function", "evaluations", "." ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/fornberg.py#L188-L209
train
208,175
pbrod/numdifftools
src/numdifftools/fornberg.py
_num_taylor_coefficients
def _num_taylor_coefficients(n): """ Return number of taylor coefficients Parameters ---------- n : scalar integer Wanted number of taylor coefficients Returns ------- m : scalar integer Number of taylor coefficients calculated 8 if n <= 6 16 if 6 < n <= 12 32 if 12 < n <= 25 64 if 25 < n <= 51 128 if 51 < n <= 103 256 if 103 < n <= 192 """ _assert(n < 193, 'Number of derivatives too large. Must be less than 193') correction = np.array([0, 0, 1, 3, 4, 7])[_get_logn(n)] log2n = _get_logn(n - correction) m = 2 ** (log2n + 3) return m
python
def _num_taylor_coefficients(n): """ Return number of taylor coefficients Parameters ---------- n : scalar integer Wanted number of taylor coefficients Returns ------- m : scalar integer Number of taylor coefficients calculated 8 if n <= 6 16 if 6 < n <= 12 32 if 12 < n <= 25 64 if 25 < n <= 51 128 if 51 < n <= 103 256 if 103 < n <= 192 """ _assert(n < 193, 'Number of derivatives too large. Must be less than 193') correction = np.array([0, 0, 1, 3, 4, 7])[_get_logn(n)] log2n = _get_logn(n - correction) m = 2 ** (log2n + 3) return m
[ "def", "_num_taylor_coefficients", "(", "n", ")", ":", "_assert", "(", "n", "<", "193", ",", "'Number of derivatives too large. Must be less than 193'", ")", "correction", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "1", ",", "3", ",", "4", ","...
Return number of taylor coefficients Parameters ---------- n : scalar integer Wanted number of taylor coefficients Returns ------- m : scalar integer Number of taylor coefficients calculated 8 if n <= 6 16 if 6 < n <= 12 32 if 12 < n <= 25 64 if 25 < n <= 51 128 if 51 < n <= 103 256 if 103 < n <= 192
[ "Return", "number", "of", "taylor", "coefficients" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/fornberg.py#L219-L243
train
208,176
pbrod/numdifftools
src/numdifftools/fornberg.py
richardson
def richardson(vals, k, c=None): """Richardson extrapolation with parameter estimation""" if c is None: c = richardson_parameter(vals, k) return vals[k] - (vals[k] - vals[k - 1]) / c
python
def richardson(vals, k, c=None): """Richardson extrapolation with parameter estimation""" if c is None: c = richardson_parameter(vals, k) return vals[k] - (vals[k] - vals[k - 1]) / c
[ "def", "richardson", "(", "vals", ",", "k", ",", "c", "=", "None", ")", ":", "if", "c", "is", "None", ":", "c", "=", "richardson_parameter", "(", "vals", ",", "k", ")", "return", "vals", "[", "k", "]", "-", "(", "vals", "[", "k", "]", "-", "v...
Richardson extrapolation with parameter estimation
[ "Richardson", "extrapolation", "with", "parameter", "estimation" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/fornberg.py#L253-L257
train
208,177
pbrod/numdifftools
src/numdifftools/fornberg.py
taylor
def taylor(fun, z0=0, n=1, r=0.0061, num_extrap=3, step_ratio=1.6, **kwds): """ Return Taylor coefficients of complex analytic function using FFT Parameters ---------- fun : callable function to differentiate z0 : real or complex scalar at which to evaluate the derivatives n : scalar integer, default 1 Number of taylor coefficents to compute. Maximum number is 100. r : real scalar, default 0.0061 Initial radius at which to evaluate. For well-behaved functions, the computation should be insensitive to the initial radius to within about four orders of magnitude. num_extrap : scalar integer, default 3 number of extrapolation steps used in the calculation step_ratio : real scalar, default 1.6 Initial grow/shrinking factor for finding the best radius. max_iter : scalar integer, default 30 Maximum number of iterations min_iter : scalar integer, default max_iter // 2 Minimum number of iterations before the solution may be deemed degenerate. A larger number allows the algorithm to correct a bad initial radius. full_output : bool, optional If `full_output` is False, only the coefficents is returned (default). If `full_output` is True, then (coefs, status) is returned Returns ------- coefs : ndarray array of taylor coefficents status: Optional object into which output information is written: degenerate: True if the algorithm was unable to bound the error iterations: Number of iterations executed function_count: Number of function calls final_radius: Ending radius of the algorithm failed: True if the maximum number of iterations was reached error_estimate: approximate bounds of the rounding error. Notes ----- This module uses the method of Fornberg to compute the Taylor series coefficents of a complex analytic function along with error bounds. The method uses a Fast Fourier Transform to invert function evaluations around a circle into Taylor series coefficients and uses Richardson Extrapolation to improve and bound the estimate. Unlike real-valued finite differences, the method searches for a desirable radius and so is reasonably insensitive to the initial radius-to within a number of orders of magnitude at least. For most cases, the default configuration is likely to succeed. Restrictions The method uses the coefficients themselves to control the truncation error, so the error will not be properly bounded for functions like low-order polynomials whose Taylor series coefficients are nearly zero. If the error cannot be bounded, degenerate flag will be set to true, and an answer will still be computed and returned but should be used with caution. Examples -------- Compute the first 6 taylor coefficients 1 / (1 - z) expanded round z0 = 0: >>> import numdifftools.fornberg as ndf >>> import numpy as np >>> c, info = ndf.taylor(lambda x: 1./(1-x), z0=0, n=6, full_output=True) >>> np.allclose(c, np.ones(8)) True >>> np.all(info.error_estimate < 1e-9) True >>> (info.function_count, info.iterations, info.failed) == (144, 18, False) True References ---------- [1] Fornberg, B. (1981). Numerical Differentiation of Analytic Functions. ACM Transactions on Mathematical Software (TOMS), 7(4), 512-526. http://doi.org/10.1145/355972.355979 """ return Taylor(fun, n=n, r=r, num_extrap=num_extrap, step_ratio=step_ratio, **kwds)(z0)
python
def taylor(fun, z0=0, n=1, r=0.0061, num_extrap=3, step_ratio=1.6, **kwds): """ Return Taylor coefficients of complex analytic function using FFT Parameters ---------- fun : callable function to differentiate z0 : real or complex scalar at which to evaluate the derivatives n : scalar integer, default 1 Number of taylor coefficents to compute. Maximum number is 100. r : real scalar, default 0.0061 Initial radius at which to evaluate. For well-behaved functions, the computation should be insensitive to the initial radius to within about four orders of magnitude. num_extrap : scalar integer, default 3 number of extrapolation steps used in the calculation step_ratio : real scalar, default 1.6 Initial grow/shrinking factor for finding the best radius. max_iter : scalar integer, default 30 Maximum number of iterations min_iter : scalar integer, default max_iter // 2 Minimum number of iterations before the solution may be deemed degenerate. A larger number allows the algorithm to correct a bad initial radius. full_output : bool, optional If `full_output` is False, only the coefficents is returned (default). If `full_output` is True, then (coefs, status) is returned Returns ------- coefs : ndarray array of taylor coefficents status: Optional object into which output information is written: degenerate: True if the algorithm was unable to bound the error iterations: Number of iterations executed function_count: Number of function calls final_radius: Ending radius of the algorithm failed: True if the maximum number of iterations was reached error_estimate: approximate bounds of the rounding error. Notes ----- This module uses the method of Fornberg to compute the Taylor series coefficents of a complex analytic function along with error bounds. The method uses a Fast Fourier Transform to invert function evaluations around a circle into Taylor series coefficients and uses Richardson Extrapolation to improve and bound the estimate. Unlike real-valued finite differences, the method searches for a desirable radius and so is reasonably insensitive to the initial radius-to within a number of orders of magnitude at least. For most cases, the default configuration is likely to succeed. Restrictions The method uses the coefficients themselves to control the truncation error, so the error will not be properly bounded for functions like low-order polynomials whose Taylor series coefficients are nearly zero. If the error cannot be bounded, degenerate flag will be set to true, and an answer will still be computed and returned but should be used with caution. Examples -------- Compute the first 6 taylor coefficients 1 / (1 - z) expanded round z0 = 0: >>> import numdifftools.fornberg as ndf >>> import numpy as np >>> c, info = ndf.taylor(lambda x: 1./(1-x), z0=0, n=6, full_output=True) >>> np.allclose(c, np.ones(8)) True >>> np.all(info.error_estimate < 1e-9) True >>> (info.function_count, info.iterations, info.failed) == (144, 18, False) True References ---------- [1] Fornberg, B. (1981). Numerical Differentiation of Analytic Functions. ACM Transactions on Mathematical Software (TOMS), 7(4), 512-526. http://doi.org/10.1145/355972.355979 """ return Taylor(fun, n=n, r=r, num_extrap=num_extrap, step_ratio=step_ratio, **kwds)(z0)
[ "def", "taylor", "(", "fun", ",", "z0", "=", "0", ",", "n", "=", "1", ",", "r", "=", "0.0061", ",", "num_extrap", "=", "3", ",", "step_ratio", "=", "1.6", ",", "*", "*", "kwds", ")", ":", "return", "Taylor", "(", "fun", ",", "n", "=", "n", ...
Return Taylor coefficients of complex analytic function using FFT Parameters ---------- fun : callable function to differentiate z0 : real or complex scalar at which to evaluate the derivatives n : scalar integer, default 1 Number of taylor coefficents to compute. Maximum number is 100. r : real scalar, default 0.0061 Initial radius at which to evaluate. For well-behaved functions, the computation should be insensitive to the initial radius to within about four orders of magnitude. num_extrap : scalar integer, default 3 number of extrapolation steps used in the calculation step_ratio : real scalar, default 1.6 Initial grow/shrinking factor for finding the best radius. max_iter : scalar integer, default 30 Maximum number of iterations min_iter : scalar integer, default max_iter // 2 Minimum number of iterations before the solution may be deemed degenerate. A larger number allows the algorithm to correct a bad initial radius. full_output : bool, optional If `full_output` is False, only the coefficents is returned (default). If `full_output` is True, then (coefs, status) is returned Returns ------- coefs : ndarray array of taylor coefficents status: Optional object into which output information is written: degenerate: True if the algorithm was unable to bound the error iterations: Number of iterations executed function_count: Number of function calls final_radius: Ending radius of the algorithm failed: True if the maximum number of iterations was reached error_estimate: approximate bounds of the rounding error. Notes ----- This module uses the method of Fornberg to compute the Taylor series coefficents of a complex analytic function along with error bounds. The method uses a Fast Fourier Transform to invert function evaluations around a circle into Taylor series coefficients and uses Richardson Extrapolation to improve and bound the estimate. Unlike real-valued finite differences, the method searches for a desirable radius and so is reasonably insensitive to the initial radius-to within a number of orders of magnitude at least. For most cases, the default configuration is likely to succeed. Restrictions The method uses the coefficients themselves to control the truncation error, so the error will not be properly bounded for functions like low-order polynomials whose Taylor series coefficients are nearly zero. If the error cannot be bounded, degenerate flag will be set to true, and an answer will still be computed and returned but should be used with caution. Examples -------- Compute the first 6 taylor coefficients 1 / (1 - z) expanded round z0 = 0: >>> import numdifftools.fornberg as ndf >>> import numpy as np >>> c, info = ndf.taylor(lambda x: 1./(1-x), z0=0, n=6, full_output=True) >>> np.allclose(c, np.ones(8)) True >>> np.all(info.error_estimate < 1e-9) True >>> (info.function_count, info.iterations, info.failed) == (144, 18, False) True References ---------- [1] Fornberg, B. (1981). Numerical Differentiation of Analytic Functions. ACM Transactions on Mathematical Software (TOMS), 7(4), 512-526. http://doi.org/10.1145/355972.355979
[ "Return", "Taylor", "coefficients", "of", "complex", "analytic", "function", "using", "FFT" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/fornberg.py#L479-L563
train
208,178
pbrod/numdifftools
src/numdifftools/fornberg.py
derivative
def derivative(fun, z0, n=1, **kwds): """ Calculate n-th derivative of complex analytic function using FFT Parameters ---------- fun : callable function to differentiate z0 : real or complex scalar at which to evaluate the derivatives n : scalar integer, default 1 Number of derivatives to compute where 0 represents the value of the function and n represents the nth derivative. Maximum number is 100. r : real scalar, default 0.0061 Initial radius at which to evaluate. For well-behaved functions, the computation should be insensitive to the initial radius to within about four orders of magnitude. max_iter : scalar integer, default 30 Maximum number of iterations min_iter : scalar integer, default max_iter // 2 Minimum number of iterations before the solution may be deemed degenerate. A larger number allows the algorithm to correct a bad initial radius. step_ratio : real scalar, default 1.6 Initial grow/shrinking factor for finding the best radius. num_extrap : scalar integer, default 3 number of extrapolation steps used in the calculation full_output : bool, optional If `full_output` is False, only the derivative is returned (default). If `full_output` is True, then (der, status) is returned `der` is the derivative, and `status` is a Results object. Returns ------- der : ndarray array of derivatives status: Optional object into which output information is written. Fields: degenerate: True if the algorithm was unable to bound the error iterations: Number of iterations executed function_count: Number of function calls final_radius: Ending radius of the algorithm failed: True if the maximum number of iterations was reached error_estimate: approximate bounds of the rounding error. This module uses the method of Fornberg to compute the derivatives of a complex analytic function along with error bounds. The method uses a Fast Fourier Transform to invert function evaluations around a circle into Taylor series coefficients, uses Richardson Extrapolation to improve and bound the estimate, then multiplies by a factorial to compute the derivatives. Unlike real-valued finite differences, the method searches for a desirable radius and so is reasonably insensitive to the initial radius-to within a number of orders of magnitude at least. For most cases, the default configuration is likely to succeed. Restrictions The method uses the coefficients themselves to control the truncation error, so the error will not be properly bounded for functions like low-order polynomials whose Taylor series coefficients are nearly zero. If the error cannot be bounded, degenerate flag will be set to true, and an answer will still be computed and returned but should be used with caution. Examples -------- To compute the first five derivatives of 1 / (1 - z) at z = 0: Compute the first 6 taylor derivatives of 1 / (1 - z) at z0 = 0: >>> import numdifftools.fornberg as ndf >>> import numpy as np >>> def fun(x): ... return 1./(1-x) >>> c, info = ndf.derivative(fun, z0=0, n=6, full_output=True) >>> np.allclose(c, [1, 1, 2, 6, 24, 120, 720, 5040]) True >>> np.all(info.error_estimate < 1e-9*c.real) True >>> (info.function_count, info.iterations, info.failed) == (144, 18, False) True References ---------- [1] Fornberg, B. (1981). Numerical Differentiation of Analytic Functions. ACM Transactions on Mathematical Software (TOMS), 7(4), 512-526. http://doi.org/10.1145/355972.355979 """ result = taylor(fun, z0, n=n, **kwds) # convert taylor series --> actual derivatives. m = _num_taylor_coefficients(n) fact = factorial(np.arange(m)) if kwds.get('full_output'): coefs, info_ = result info = _INFO(info_.error_estimate * fact, *info_[1:]) return coefs * fact, info return result * fact
python
def derivative(fun, z0, n=1, **kwds): """ Calculate n-th derivative of complex analytic function using FFT Parameters ---------- fun : callable function to differentiate z0 : real or complex scalar at which to evaluate the derivatives n : scalar integer, default 1 Number of derivatives to compute where 0 represents the value of the function and n represents the nth derivative. Maximum number is 100. r : real scalar, default 0.0061 Initial radius at which to evaluate. For well-behaved functions, the computation should be insensitive to the initial radius to within about four orders of magnitude. max_iter : scalar integer, default 30 Maximum number of iterations min_iter : scalar integer, default max_iter // 2 Minimum number of iterations before the solution may be deemed degenerate. A larger number allows the algorithm to correct a bad initial radius. step_ratio : real scalar, default 1.6 Initial grow/shrinking factor for finding the best radius. num_extrap : scalar integer, default 3 number of extrapolation steps used in the calculation full_output : bool, optional If `full_output` is False, only the derivative is returned (default). If `full_output` is True, then (der, status) is returned `der` is the derivative, and `status` is a Results object. Returns ------- der : ndarray array of derivatives status: Optional object into which output information is written. Fields: degenerate: True if the algorithm was unable to bound the error iterations: Number of iterations executed function_count: Number of function calls final_radius: Ending radius of the algorithm failed: True if the maximum number of iterations was reached error_estimate: approximate bounds of the rounding error. This module uses the method of Fornberg to compute the derivatives of a complex analytic function along with error bounds. The method uses a Fast Fourier Transform to invert function evaluations around a circle into Taylor series coefficients, uses Richardson Extrapolation to improve and bound the estimate, then multiplies by a factorial to compute the derivatives. Unlike real-valued finite differences, the method searches for a desirable radius and so is reasonably insensitive to the initial radius-to within a number of orders of magnitude at least. For most cases, the default configuration is likely to succeed. Restrictions The method uses the coefficients themselves to control the truncation error, so the error will not be properly bounded for functions like low-order polynomials whose Taylor series coefficients are nearly zero. If the error cannot be bounded, degenerate flag will be set to true, and an answer will still be computed and returned but should be used with caution. Examples -------- To compute the first five derivatives of 1 / (1 - z) at z = 0: Compute the first 6 taylor derivatives of 1 / (1 - z) at z0 = 0: >>> import numdifftools.fornberg as ndf >>> import numpy as np >>> def fun(x): ... return 1./(1-x) >>> c, info = ndf.derivative(fun, z0=0, n=6, full_output=True) >>> np.allclose(c, [1, 1, 2, 6, 24, 120, 720, 5040]) True >>> np.all(info.error_estimate < 1e-9*c.real) True >>> (info.function_count, info.iterations, info.failed) == (144, 18, False) True References ---------- [1] Fornberg, B. (1981). Numerical Differentiation of Analytic Functions. ACM Transactions on Mathematical Software (TOMS), 7(4), 512-526. http://doi.org/10.1145/355972.355979 """ result = taylor(fun, z0, n=n, **kwds) # convert taylor series --> actual derivatives. m = _num_taylor_coefficients(n) fact = factorial(np.arange(m)) if kwds.get('full_output'): coefs, info_ = result info = _INFO(info_.error_estimate * fact, *info_[1:]) return coefs * fact, info return result * fact
[ "def", "derivative", "(", "fun", ",", "z0", ",", "n", "=", "1", ",", "*", "*", "kwds", ")", ":", "result", "=", "taylor", "(", "fun", ",", "z0", ",", "n", "=", "n", ",", "*", "*", "kwds", ")", "# convert taylor series --> actual derivatives.", "m", ...
Calculate n-th derivative of complex analytic function using FFT Parameters ---------- fun : callable function to differentiate z0 : real or complex scalar at which to evaluate the derivatives n : scalar integer, default 1 Number of derivatives to compute where 0 represents the value of the function and n represents the nth derivative. Maximum number is 100. r : real scalar, default 0.0061 Initial radius at which to evaluate. For well-behaved functions, the computation should be insensitive to the initial radius to within about four orders of magnitude. max_iter : scalar integer, default 30 Maximum number of iterations min_iter : scalar integer, default max_iter // 2 Minimum number of iterations before the solution may be deemed degenerate. A larger number allows the algorithm to correct a bad initial radius. step_ratio : real scalar, default 1.6 Initial grow/shrinking factor for finding the best radius. num_extrap : scalar integer, default 3 number of extrapolation steps used in the calculation full_output : bool, optional If `full_output` is False, only the derivative is returned (default). If `full_output` is True, then (der, status) is returned `der` is the derivative, and `status` is a Results object. Returns ------- der : ndarray array of derivatives status: Optional object into which output information is written. Fields: degenerate: True if the algorithm was unable to bound the error iterations: Number of iterations executed function_count: Number of function calls final_radius: Ending radius of the algorithm failed: True if the maximum number of iterations was reached error_estimate: approximate bounds of the rounding error. This module uses the method of Fornberg to compute the derivatives of a complex analytic function along with error bounds. The method uses a Fast Fourier Transform to invert function evaluations around a circle into Taylor series coefficients, uses Richardson Extrapolation to improve and bound the estimate, then multiplies by a factorial to compute the derivatives. Unlike real-valued finite differences, the method searches for a desirable radius and so is reasonably insensitive to the initial radius-to within a number of orders of magnitude at least. For most cases, the default configuration is likely to succeed. Restrictions The method uses the coefficients themselves to control the truncation error, so the error will not be properly bounded for functions like low-order polynomials whose Taylor series coefficients are nearly zero. If the error cannot be bounded, degenerate flag will be set to true, and an answer will still be computed and returned but should be used with caution. Examples -------- To compute the first five derivatives of 1 / (1 - z) at z = 0: Compute the first 6 taylor derivatives of 1 / (1 - z) at z0 = 0: >>> import numdifftools.fornberg as ndf >>> import numpy as np >>> def fun(x): ... return 1./(1-x) >>> c, info = ndf.derivative(fun, z0=0, n=6, full_output=True) >>> np.allclose(c, [1, 1, 2, 6, 24, 120, 720, 5040]) True >>> np.all(info.error_estimate < 1e-9*c.real) True >>> (info.function_count, info.iterations, info.failed) == (144, 18, False) True References ---------- [1] Fornberg, B. (1981). Numerical Differentiation of Analytic Functions. ACM Transactions on Mathematical Software (TOMS), 7(4), 512-526. http://doi.org/10.1145/355972.355979
[ "Calculate", "n", "-", "th", "derivative", "of", "complex", "analytic", "function", "using", "FFT" ]
2c88878df732c9c6629febea56e7a91fd898398d
https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/fornberg.py#L566-L662
train
208,179
selectel/pyte
pyte/screens.py
Screen.default_char
def default_char(self): """An empty character with default foreground and background colors.""" reverse = mo.DECSCNM in self.mode return Char(data=" ", fg="default", bg="default", reverse=reverse)
python
def default_char(self): """An empty character with default foreground and background colors.""" reverse = mo.DECSCNM in self.mode return Char(data=" ", fg="default", bg="default", reverse=reverse)
[ "def", "default_char", "(", "self", ")", ":", "reverse", "=", "mo", ".", "DECSCNM", "in", "self", ".", "mode", "return", "Char", "(", "data", "=", "\" \"", ",", "fg", "=", "\"default\"", ",", "bg", "=", "\"default\"", ",", "reverse", "=", "reverse", ...
An empty character with default foreground and background colors.
[ "An", "empty", "character", "with", "default", "foreground", "and", "background", "colors", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L218-L221
train
208,180
selectel/pyte
pyte/screens.py
Screen.reset
def reset(self): """Reset the terminal to its initial state. * Scrolling margins are reset to screen boundaries. * Cursor is moved to home location -- ``(0, 0)`` and its attributes are set to defaults (see :attr:`default_char`). * Screen is cleared -- each character is reset to :attr:`default_char`. * Tabstops are reset to "every eight columns". * All lines are marked as :attr:`dirty`. .. note:: Neither VT220 nor VT102 manuals mention that terminal modes and tabstops should be reset as well, thanks to :manpage:`xterm` -- we now know that. """ self.dirty.update(range(self.lines)) self.buffer.clear() self.margins = None self.mode = set([mo.DECAWM, mo.DECTCEM]) self.title = "" self.icon_name = "" self.charset = 0 self.g0_charset = cs.LAT1_MAP self.g1_charset = cs.VT100_MAP # From ``man terminfo`` -- "... hardware tabs are initially # set every `n` spaces when the terminal is powered up. Since # we aim to support VT102 / VT220 and linux -- we use n = 8. self.tabstops = set(range(8, self.columns, 8)) self.cursor = Cursor(0, 0) self.cursor_position() self.saved_columns = None
python
def reset(self): """Reset the terminal to its initial state. * Scrolling margins are reset to screen boundaries. * Cursor is moved to home location -- ``(0, 0)`` and its attributes are set to defaults (see :attr:`default_char`). * Screen is cleared -- each character is reset to :attr:`default_char`. * Tabstops are reset to "every eight columns". * All lines are marked as :attr:`dirty`. .. note:: Neither VT220 nor VT102 manuals mention that terminal modes and tabstops should be reset as well, thanks to :manpage:`xterm` -- we now know that. """ self.dirty.update(range(self.lines)) self.buffer.clear() self.margins = None self.mode = set([mo.DECAWM, mo.DECTCEM]) self.title = "" self.icon_name = "" self.charset = 0 self.g0_charset = cs.LAT1_MAP self.g1_charset = cs.VT100_MAP # From ``man terminfo`` -- "... hardware tabs are initially # set every `n` spaces when the terminal is powered up. Since # we aim to support VT102 / VT220 and linux -- we use n = 8. self.tabstops = set(range(8, self.columns, 8)) self.cursor = Cursor(0, 0) self.cursor_position() self.saved_columns = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "dirty", ".", "update", "(", "range", "(", "self", ".", "lines", ")", ")", "self", ".", "buffer", ".", "clear", "(", ")", "self", ".", "margins", "=", "None", "self", ".", "mode", "=", "set", ...
Reset the terminal to its initial state. * Scrolling margins are reset to screen boundaries. * Cursor is moved to home location -- ``(0, 0)`` and its attributes are set to defaults (see :attr:`default_char`). * Screen is cleared -- each character is reset to :attr:`default_char`. * Tabstops are reset to "every eight columns". * All lines are marked as :attr:`dirty`. .. note:: Neither VT220 nor VT102 manuals mention that terminal modes and tabstops should be reset as well, thanks to :manpage:`xterm` -- we now know that.
[ "Reset", "the", "terminal", "to", "its", "initial", "state", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L251-L289
train
208,181
selectel/pyte
pyte/screens.py
Screen.resize
def resize(self, lines=None, columns=None): """Resize the screen to the given size. If the requested screen size has more lines than the existing screen, lines will be added at the bottom. If the requested size has less lines than the existing screen lines will be clipped at the top of the screen. Similarly, if the existing screen has less columns than the requested screen, columns will be added at the right, and if it has more -- columns will be clipped at the right. :param int lines: number of lines in the new screen. :param int columns: number of columns in the new screen. .. versionchanged:: 0.7.0 If the requested screen size is identical to the current screen size, the method does nothing. """ lines = lines or self.lines columns = columns or self.columns if lines == self.lines and columns == self.columns: return # No changes. self.dirty.update(range(lines)) if lines < self.lines: self.save_cursor() self.cursor_position(0, 0) self.delete_lines(self.lines - lines) # Drop from the top. self.restore_cursor() if columns < self.columns: for line in self.buffer.values(): for x in range(columns, self.columns): line.pop(x, None) self.lines, self.columns = lines, columns self.set_margins()
python
def resize(self, lines=None, columns=None): """Resize the screen to the given size. If the requested screen size has more lines than the existing screen, lines will be added at the bottom. If the requested size has less lines than the existing screen lines will be clipped at the top of the screen. Similarly, if the existing screen has less columns than the requested screen, columns will be added at the right, and if it has more -- columns will be clipped at the right. :param int lines: number of lines in the new screen. :param int columns: number of columns in the new screen. .. versionchanged:: 0.7.0 If the requested screen size is identical to the current screen size, the method does nothing. """ lines = lines or self.lines columns = columns or self.columns if lines == self.lines and columns == self.columns: return # No changes. self.dirty.update(range(lines)) if lines < self.lines: self.save_cursor() self.cursor_position(0, 0) self.delete_lines(self.lines - lines) # Drop from the top. self.restore_cursor() if columns < self.columns: for line in self.buffer.values(): for x in range(columns, self.columns): line.pop(x, None) self.lines, self.columns = lines, columns self.set_margins()
[ "def", "resize", "(", "self", ",", "lines", "=", "None", ",", "columns", "=", "None", ")", ":", "lines", "=", "lines", "or", "self", ".", "lines", "columns", "=", "columns", "or", "self", ".", "columns", "if", "lines", "==", "self", ".", "lines", "...
Resize the screen to the given size. If the requested screen size has more lines than the existing screen, lines will be added at the bottom. If the requested size has less lines than the existing screen lines will be clipped at the top of the screen. Similarly, if the existing screen has less columns than the requested screen, columns will be added at the right, and if it has more -- columns will be clipped at the right. :param int lines: number of lines in the new screen. :param int columns: number of columns in the new screen. .. versionchanged:: 0.7.0 If the requested screen size is identical to the current screen size, the method does nothing.
[ "Resize", "the", "screen", "to", "the", "given", "size", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L291-L330
train
208,182
selectel/pyte
pyte/screens.py
Screen.set_margins
def set_margins(self, top=None, bottom=None): """Select top and bottom margins for the scrolling region. :param int top: the smallest line number that is scrolled. :param int bottom: the biggest line number that is scrolled. """ # XXX 0 corresponds to the CSI with no parameters. if (top is None or top == 0) and bottom is None: self.margins = None return margins = self.margins or Margins(0, self.lines - 1) # Arguments are 1-based, while :attr:`margins` are zero # based -- so we have to decrement them by one. We also # make sure that both of them is bounded by [0, lines - 1]. if top is None: top = margins.top else: top = max(0, min(top - 1, self.lines - 1)) if bottom is None: bottom = margins.bottom else: bottom = max(0, min(bottom - 1, self.lines - 1)) # Even though VT102 and VT220 require DECSTBM to ignore # regions of width less than 2, some programs (like aptitude # for example) rely on it. Practicality beats purity. if bottom - top >= 1: self.margins = Margins(top, bottom) # The cursor moves to the home position when the top and # bottom margins of the scrolling region (DECSTBM) changes. self.cursor_position()
python
def set_margins(self, top=None, bottom=None): """Select top and bottom margins for the scrolling region. :param int top: the smallest line number that is scrolled. :param int bottom: the biggest line number that is scrolled. """ # XXX 0 corresponds to the CSI with no parameters. if (top is None or top == 0) and bottom is None: self.margins = None return margins = self.margins or Margins(0, self.lines - 1) # Arguments are 1-based, while :attr:`margins` are zero # based -- so we have to decrement them by one. We also # make sure that both of them is bounded by [0, lines - 1]. if top is None: top = margins.top else: top = max(0, min(top - 1, self.lines - 1)) if bottom is None: bottom = margins.bottom else: bottom = max(0, min(bottom - 1, self.lines - 1)) # Even though VT102 and VT220 require DECSTBM to ignore # regions of width less than 2, some programs (like aptitude # for example) rely on it. Practicality beats purity. if bottom - top >= 1: self.margins = Margins(top, bottom) # The cursor moves to the home position when the top and # bottom margins of the scrolling region (DECSTBM) changes. self.cursor_position()
[ "def", "set_margins", "(", "self", ",", "top", "=", "None", ",", "bottom", "=", "None", ")", ":", "# XXX 0 corresponds to the CSI with no parameters.", "if", "(", "top", "is", "None", "or", "top", "==", "0", ")", "and", "bottom", "is", "None", ":", "self",...
Select top and bottom margins for the scrolling region. :param int top: the smallest line number that is scrolled. :param int bottom: the biggest line number that is scrolled.
[ "Select", "top", "and", "bottom", "margins", "for", "the", "scrolling", "region", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L332-L365
train
208,183
selectel/pyte
pyte/screens.py
Screen.define_charset
def define_charset(self, code, mode): """Define ``G0`` or ``G1`` charset. :param str code: character set code, should be a character from ``"B0UK"``, otherwise ignored. :param str mode: if ``"("`` ``G0`` charset is defined, if ``")"`` -- we operate on ``G1``. .. warning:: User-defined charsets are currently not supported. """ if code in cs.MAPS: if mode == "(": self.g0_charset = cs.MAPS[code] elif mode == ")": self.g1_charset = cs.MAPS[code]
python
def define_charset(self, code, mode): """Define ``G0`` or ``G1`` charset. :param str code: character set code, should be a character from ``"B0UK"``, otherwise ignored. :param str mode: if ``"("`` ``G0`` charset is defined, if ``")"`` -- we operate on ``G1``. .. warning:: User-defined charsets are currently not supported. """ if code in cs.MAPS: if mode == "(": self.g0_charset = cs.MAPS[code] elif mode == ")": self.g1_charset = cs.MAPS[code]
[ "def", "define_charset", "(", "self", ",", "code", ",", "mode", ")", ":", "if", "code", "in", "cs", ".", "MAPS", ":", "if", "mode", "==", "\"(\"", ":", "self", ".", "g0_charset", "=", "cs", ".", "MAPS", "[", "code", "]", "elif", "mode", "==", "\"...
Define ``G0`` or ``G1`` charset. :param str code: character set code, should be a character from ``"B0UK"``, otherwise ignored. :param str mode: if ``"("`` ``G0`` charset is defined, if ``")"`` -- we operate on ``G1``. .. warning:: User-defined charsets are currently not supported.
[ "Define", "G0", "or", "G1", "charset", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L445-L459
train
208,184
selectel/pyte
pyte/screens.py
Screen.index
def index(self): """Move the cursor down one line in the same column. If the cursor is at the last line, create a new line at the bottom. """ top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == bottom: # TODO: mark only the lines within margins? self.dirty.update(range(self.lines)) for y in range(top, bottom): self.buffer[y] = self.buffer[y + 1] self.buffer.pop(bottom, None) else: self.cursor_down()
python
def index(self): """Move the cursor down one line in the same column. If the cursor is at the last line, create a new line at the bottom. """ top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == bottom: # TODO: mark only the lines within margins? self.dirty.update(range(self.lines)) for y in range(top, bottom): self.buffer[y] = self.buffer[y + 1] self.buffer.pop(bottom, None) else: self.cursor_down()
[ "def", "index", "(", "self", ")", ":", "top", ",", "bottom", "=", "self", ".", "margins", "or", "Margins", "(", "0", ",", "self", ".", "lines", "-", "1", ")", "if", "self", ".", "cursor", ".", "y", "==", "bottom", ":", "# TODO: mark only the lines wi...
Move the cursor down one line in the same column. If the cursor is at the last line, create a new line at the bottom.
[ "Move", "the", "cursor", "down", "one", "line", "in", "the", "same", "column", ".", "If", "the", "cursor", "is", "at", "the", "last", "line", "create", "a", "new", "line", "at", "the", "bottom", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L554-L566
train
208,185
selectel/pyte
pyte/screens.py
Screen.reverse_index
def reverse_index(self): """Move the cursor up one line in the same column. If the cursor is at the first line, create a new line at the top. """ top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == top: # TODO: mark only the lines within margins? self.dirty.update(range(self.lines)) for y in range(bottom, top, -1): self.buffer[y] = self.buffer[y - 1] self.buffer.pop(top, None) else: self.cursor_up()
python
def reverse_index(self): """Move the cursor up one line in the same column. If the cursor is at the first line, create a new line at the top. """ top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == top: # TODO: mark only the lines within margins? self.dirty.update(range(self.lines)) for y in range(bottom, top, -1): self.buffer[y] = self.buffer[y - 1] self.buffer.pop(top, None) else: self.cursor_up()
[ "def", "reverse_index", "(", "self", ")", ":", "top", ",", "bottom", "=", "self", ".", "margins", "or", "Margins", "(", "0", ",", "self", ".", "lines", "-", "1", ")", "if", "self", ".", "cursor", ".", "y", "==", "top", ":", "# TODO: mark only the lin...
Move the cursor up one line in the same column. If the cursor is at the first line, create a new line at the top.
[ "Move", "the", "cursor", "up", "one", "line", "in", "the", "same", "column", ".", "If", "the", "cursor", "is", "at", "the", "first", "line", "create", "a", "new", "line", "at", "the", "top", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L568-L580
train
208,186
selectel/pyte
pyte/screens.py
Screen.tab
def tab(self): """Move to the next tab space, or the end of the screen if there aren't anymore left. """ for stop in sorted(self.tabstops): if self.cursor.x < stop: column = stop break else: column = self.columns - 1 self.cursor.x = column
python
def tab(self): """Move to the next tab space, or the end of the screen if there aren't anymore left. """ for stop in sorted(self.tabstops): if self.cursor.x < stop: column = stop break else: column = self.columns - 1 self.cursor.x = column
[ "def", "tab", "(", "self", ")", ":", "for", "stop", "in", "sorted", "(", "self", ".", "tabstops", ")", ":", "if", "self", ".", "cursor", ".", "x", "<", "stop", ":", "column", "=", "stop", "break", "else", ":", "column", "=", "self", ".", "columns...
Move to the next tab space, or the end of the screen if there aren't anymore left.
[ "Move", "to", "the", "next", "tab", "space", "or", "the", "end", "of", "the", "screen", "if", "there", "aren", "t", "anymore", "left", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L591-L602
train
208,187
selectel/pyte
pyte/screens.py
Screen.save_cursor
def save_cursor(self): """Push the current cursor position onto the stack.""" self.savepoints.append(Savepoint(copy.copy(self.cursor), self.g0_charset, self.g1_charset, self.charset, mo.DECOM in self.mode, mo.DECAWM in self.mode))
python
def save_cursor(self): """Push the current cursor position onto the stack.""" self.savepoints.append(Savepoint(copy.copy(self.cursor), self.g0_charset, self.g1_charset, self.charset, mo.DECOM in self.mode, mo.DECAWM in self.mode))
[ "def", "save_cursor", "(", "self", ")", ":", "self", ".", "savepoints", ".", "append", "(", "Savepoint", "(", "copy", ".", "copy", "(", "self", ".", "cursor", ")", ",", "self", ".", "g0_charset", ",", "self", ".", "g1_charset", ",", "self", ".", "cha...
Push the current cursor position onto the stack.
[ "Push", "the", "current", "cursor", "position", "onto", "the", "stack", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L610-L617
train
208,188
selectel/pyte
pyte/screens.py
Screen.erase_in_line
def erase_in_line(self, how=0, private=False): """Erase a line in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of line, including cursor position. * ``1`` -- Erases from beginning of line to cursor, including cursor position. * ``2`` -- Erases complete line. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**. """ self.dirty.add(self.cursor.y) if how == 0: interval = range(self.cursor.x, self.columns) elif how == 1: interval = range(self.cursor.x + 1) elif how == 2: interval = range(self.columns) line = self.buffer[self.cursor.y] for x in interval: line[x] = self.cursor.attrs
python
def erase_in_line(self, how=0, private=False): """Erase a line in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of line, including cursor position. * ``1`` -- Erases from beginning of line to cursor, including cursor position. * ``2`` -- Erases complete line. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**. """ self.dirty.add(self.cursor.y) if how == 0: interval = range(self.cursor.x, self.columns) elif how == 1: interval = range(self.cursor.x + 1) elif how == 2: interval = range(self.columns) line = self.buffer[self.cursor.y] for x in interval: line[x] = self.cursor.attrs
[ "def", "erase_in_line", "(", "self", ",", "how", "=", "0", ",", "private", "=", "False", ")", ":", "self", ".", "dirty", ".", "add", "(", "self", ".", "cursor", ".", "y", ")", "if", "how", "==", "0", ":", "interval", "=", "range", "(", "self", ...
Erase a line in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of line, including cursor position. * ``1`` -- Erases from beginning of line to cursor, including cursor position. * ``2`` -- Erases complete line. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**.
[ "Erase", "a", "line", "in", "a", "specific", "way", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L744-L769
train
208,189
selectel/pyte
pyte/screens.py
Screen.erase_in_display
def erase_in_display(self, how=0, *args, **kwargs): """Erases display in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of screen, including cursor position. * ``1`` -- Erases from beginning of screen to cursor, including cursor position. * ``2`` and ``3`` -- Erases complete display. All lines are erased and changed to single-width. Cursor does not move. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**. .. versionchanged:: 0.8.1 The method accepts any number of positional arguments as some ``clear`` implementations include a ``;`` after the first parameter causing the stream to assume a ``0`` second parameter. """ if how == 0: interval = range(self.cursor.y + 1, self.lines) elif how == 1: interval = range(self.cursor.y) elif how == 2 or how == 3: interval = range(self.lines) self.dirty.update(interval) for y in interval: line = self.buffer[y] for x in line: line[x] = self.cursor.attrs if how == 0 or how == 1: self.erase_in_line(how)
python
def erase_in_display(self, how=0, *args, **kwargs): """Erases display in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of screen, including cursor position. * ``1`` -- Erases from beginning of screen to cursor, including cursor position. * ``2`` and ``3`` -- Erases complete display. All lines are erased and changed to single-width. Cursor does not move. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**. .. versionchanged:: 0.8.1 The method accepts any number of positional arguments as some ``clear`` implementations include a ``;`` after the first parameter causing the stream to assume a ``0`` second parameter. """ if how == 0: interval = range(self.cursor.y + 1, self.lines) elif how == 1: interval = range(self.cursor.y) elif how == 2 or how == 3: interval = range(self.lines) self.dirty.update(interval) for y in interval: line = self.buffer[y] for x in line: line[x] = self.cursor.attrs if how == 0 or how == 1: self.erase_in_line(how)
[ "def", "erase_in_display", "(", "self", ",", "how", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "how", "==", "0", ":", "interval", "=", "range", "(", "self", ".", "cursor", ".", "y", "+", "1", ",", "self", ".", "lines",...
Erases display in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of screen, including cursor position. * ``1`` -- Erases from beginning of screen to cursor, including cursor position. * ``2`` and ``3`` -- Erases complete display. All lines are erased and changed to single-width. Cursor does not move. :param bool private: when ``True`` only characters marked as eraseable are affected **not implemented**. .. versionchanged:: 0.8.1 The method accepts any number of positional arguments as some ``clear`` implementations include a ``;`` after the first parameter causing the stream to assume a ``0`` second parameter.
[ "Erases", "display", "in", "a", "specific", "way", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L771-L808
train
208,190
selectel/pyte
pyte/screens.py
Screen.clear_tab_stop
def clear_tab_stop(self, how=0): """Clear a horizontal tab stop. :param int how: defines a way the tab stop should be cleared: * ``0`` or nothing -- Clears a horizontal tab stop at cursor position. * ``3`` -- Clears all horizontal tab stops. """ if how == 0: # Clears a horizontal tab stop at cursor position, if it's # present, or silently fails if otherwise. self.tabstops.discard(self.cursor.x) elif how == 3: self.tabstops = set()
python
def clear_tab_stop(self, how=0): """Clear a horizontal tab stop. :param int how: defines a way the tab stop should be cleared: * ``0`` or nothing -- Clears a horizontal tab stop at cursor position. * ``3`` -- Clears all horizontal tab stops. """ if how == 0: # Clears a horizontal tab stop at cursor position, if it's # present, or silently fails if otherwise. self.tabstops.discard(self.cursor.x) elif how == 3: self.tabstops = set()
[ "def", "clear_tab_stop", "(", "self", ",", "how", "=", "0", ")", ":", "if", "how", "==", "0", ":", "# Clears a horizontal tab stop at cursor position, if it's", "# present, or silently fails if otherwise.", "self", ".", "tabstops", ".", "discard", "(", "self", ".", ...
Clear a horizontal tab stop. :param int how: defines a way the tab stop should be cleared: * ``0`` or nothing -- Clears a horizontal tab stop at cursor position. * ``3`` -- Clears all horizontal tab stops.
[ "Clear", "a", "horizontal", "tab", "stop", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L814-L828
train
208,191
selectel/pyte
pyte/screens.py
Screen.ensure_hbounds
def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
python
def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
[ "def", "ensure_hbounds", "(", "self", ")", ":", "self", ".", "cursor", ".", "x", "=", "min", "(", "max", "(", "0", ",", "self", ".", "cursor", ".", "x", ")", ",", "self", ".", "columns", "-", "1", ")" ]
Ensure the cursor is within horizontal screen bounds.
[ "Ensure", "the", "cursor", "is", "within", "horizontal", "screen", "bounds", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L830-L832
train
208,192
selectel/pyte
pyte/screens.py
Screen.ensure_vbounds
def ensure_vbounds(self, use_margins=None): """Ensure the cursor is within vertical screen bounds. :param bool use_margins: when ``True`` or when :data:`~pyte.modes.DECOM` is set, cursor is bounded by top and and bottom margins, instead of ``[0; lines - 1]``. """ if (use_margins or mo.DECOM in self.mode) and self.margins is not None: top, bottom = self.margins else: top, bottom = 0, self.lines - 1 self.cursor.y = min(max(top, self.cursor.y), bottom)
python
def ensure_vbounds(self, use_margins=None): """Ensure the cursor is within vertical screen bounds. :param bool use_margins: when ``True`` or when :data:`~pyte.modes.DECOM` is set, cursor is bounded by top and and bottom margins, instead of ``[0; lines - 1]``. """ if (use_margins or mo.DECOM in self.mode) and self.margins is not None: top, bottom = self.margins else: top, bottom = 0, self.lines - 1 self.cursor.y = min(max(top, self.cursor.y), bottom)
[ "def", "ensure_vbounds", "(", "self", ",", "use_margins", "=", "None", ")", ":", "if", "(", "use_margins", "or", "mo", ".", "DECOM", "in", "self", ".", "mode", ")", "and", "self", ".", "margins", "is", "not", "None", ":", "top", ",", "bottom", "=", ...
Ensure the cursor is within vertical screen bounds. :param bool use_margins: when ``True`` or when :data:`~pyte.modes.DECOM` is set, cursor is bounded by top and and bottom margins, instead of ``[0; lines - 1]``.
[ "Ensure", "the", "cursor", "is", "within", "vertical", "screen", "bounds", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L834-L847
train
208,193
selectel/pyte
pyte/screens.py
Screen.cursor_position
def cursor_position(self, line=None, column=None): """Set the cursor to a specific `line` and `column`. Cursor is allowed to move out of the scrolling region only when :data:`~pyte.modes.DECOM` is reset, otherwise -- the position doesn't change. :param int line: line number to move the cursor to. :param int column: column number to move the cursor to. """ column = (column or 1) - 1 line = (line or 1) - 1 # If origin mode (DECOM) is set, line number are relative to # the top scrolling margin. if self.margins is not None and mo.DECOM in self.mode: line += self.margins.top # Cursor is not allowed to move out of the scrolling region. if not self.margins.top <= line <= self.margins.bottom: return self.cursor.x = column self.cursor.y = line self.ensure_hbounds() self.ensure_vbounds()
python
def cursor_position(self, line=None, column=None): """Set the cursor to a specific `line` and `column`. Cursor is allowed to move out of the scrolling region only when :data:`~pyte.modes.DECOM` is reset, otherwise -- the position doesn't change. :param int line: line number to move the cursor to. :param int column: column number to move the cursor to. """ column = (column or 1) - 1 line = (line or 1) - 1 # If origin mode (DECOM) is set, line number are relative to # the top scrolling margin. if self.margins is not None and mo.DECOM in self.mode: line += self.margins.top # Cursor is not allowed to move out of the scrolling region. if not self.margins.top <= line <= self.margins.bottom: return self.cursor.x = column self.cursor.y = line self.ensure_hbounds() self.ensure_vbounds()
[ "def", "cursor_position", "(", "self", ",", "line", "=", "None", ",", "column", "=", "None", ")", ":", "column", "=", "(", "column", "or", "1", ")", "-", "1", "line", "=", "(", "line", "or", "1", ")", "-", "1", "# If origin mode (DECOM) is set, line nu...
Set the cursor to a specific `line` and `column`. Cursor is allowed to move out of the scrolling region only when :data:`~pyte.modes.DECOM` is reset, otherwise -- the position doesn't change. :param int line: line number to move the cursor to. :param int column: column number to move the cursor to.
[ "Set", "the", "cursor", "to", "a", "specific", "line", "and", "column", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L908-L933
train
208,194
selectel/pyte
pyte/screens.py
Screen.cursor_to_line
def cursor_to_line(self, line=None): """Move cursor to a specific line in the current column. :param int line: line number to move the cursor to. """ self.cursor.y = (line or 1) - 1 # If origin mode (DECOM) is set, line number are relative to # the top scrolling margin. if mo.DECOM in self.mode: self.cursor.y += self.margins.top # FIXME: should we also restrict the cursor to the scrolling # region? self.ensure_vbounds()
python
def cursor_to_line(self, line=None): """Move cursor to a specific line in the current column. :param int line: line number to move the cursor to. """ self.cursor.y = (line or 1) - 1 # If origin mode (DECOM) is set, line number are relative to # the top scrolling margin. if mo.DECOM in self.mode: self.cursor.y += self.margins.top # FIXME: should we also restrict the cursor to the scrolling # region? self.ensure_vbounds()
[ "def", "cursor_to_line", "(", "self", ",", "line", "=", "None", ")", ":", "self", ".", "cursor", ".", "y", "=", "(", "line", "or", "1", ")", "-", "1", "# If origin mode (DECOM) is set, line number are relative to", "# the top scrolling margin.", "if", "mo", ".",...
Move cursor to a specific line in the current column. :param int line: line number to move the cursor to.
[ "Move", "cursor", "to", "a", "specific", "line", "in", "the", "current", "column", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L943-L958
train
208,195
selectel/pyte
pyte/screens.py
Screen.alignment_display
def alignment_display(self): """Fills screen with uppercase E's for screen focus and alignment.""" self.dirty.update(range(self.lines)) for y in range(self.lines): for x in range(self.columns): self.buffer[y][x] = self.buffer[y][x]._replace(data="E")
python
def alignment_display(self): """Fills screen with uppercase E's for screen focus and alignment.""" self.dirty.update(range(self.lines)) for y in range(self.lines): for x in range(self.columns): self.buffer[y][x] = self.buffer[y][x]._replace(data="E")
[ "def", "alignment_display", "(", "self", ")", ":", "self", ".", "dirty", ".", "update", "(", "range", "(", "self", ".", "lines", ")", ")", "for", "y", "in", "range", "(", "self", ".", "lines", ")", ":", "for", "x", "in", "range", "(", "self", "."...
Fills screen with uppercase E's for screen focus and alignment.
[ "Fills", "screen", "with", "uppercase", "E", "s", "for", "screen", "focus", "and", "alignment", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L965-L970
train
208,196
selectel/pyte
pyte/screens.py
Screen.select_graphic_rendition
def select_graphic_rendition(self, *attrs): """Set display attributes. :param list attrs: a list of display attributes to set. """ replace = {} # Fast path for resetting all attributes. if not attrs or attrs == (0, ): self.cursor.attrs = self.default_char return else: attrs = list(reversed(attrs)) while attrs: attr = attrs.pop() if attr == 0: # Reset all attributes. replace.update(self.default_char._asdict()) elif attr in g.FG_ANSI: replace["fg"] = g.FG_ANSI[attr] elif attr in g.BG: replace["bg"] = g.BG_ANSI[attr] elif attr in g.TEXT: attr = g.TEXT[attr] replace[attr[1:]] = attr.startswith("+") elif attr in g.FG_AIXTERM: replace.update(fg=g.FG_AIXTERM[attr], bold=True) elif attr in g.BG_AIXTERM: replace.update(bg=g.BG_AIXTERM[attr], bold=True) elif attr in (g.FG_256, g.BG_256): key = "fg" if attr == g.FG_256 else "bg" try: n = attrs.pop() if n == 5: # 256. m = attrs.pop() replace[key] = g.FG_BG_256[m] elif n == 2: # 24bit. # This is somewhat non-standard but is nonetheless # supported in quite a few terminals. See discussion # here https://gist.github.com/XVilka/8346728. replace[key] = "{0:02x}{1:02x}{2:02x}".format( attrs.pop(), attrs.pop(), attrs.pop()) except IndexError: pass self.cursor.attrs = self.cursor.attrs._replace(**replace)
python
def select_graphic_rendition(self, *attrs): """Set display attributes. :param list attrs: a list of display attributes to set. """ replace = {} # Fast path for resetting all attributes. if not attrs or attrs == (0, ): self.cursor.attrs = self.default_char return else: attrs = list(reversed(attrs)) while attrs: attr = attrs.pop() if attr == 0: # Reset all attributes. replace.update(self.default_char._asdict()) elif attr in g.FG_ANSI: replace["fg"] = g.FG_ANSI[attr] elif attr in g.BG: replace["bg"] = g.BG_ANSI[attr] elif attr in g.TEXT: attr = g.TEXT[attr] replace[attr[1:]] = attr.startswith("+") elif attr in g.FG_AIXTERM: replace.update(fg=g.FG_AIXTERM[attr], bold=True) elif attr in g.BG_AIXTERM: replace.update(bg=g.BG_AIXTERM[attr], bold=True) elif attr in (g.FG_256, g.BG_256): key = "fg" if attr == g.FG_256 else "bg" try: n = attrs.pop() if n == 5: # 256. m = attrs.pop() replace[key] = g.FG_BG_256[m] elif n == 2: # 24bit. # This is somewhat non-standard but is nonetheless # supported in quite a few terminals. See discussion # here https://gist.github.com/XVilka/8346728. replace[key] = "{0:02x}{1:02x}{2:02x}".format( attrs.pop(), attrs.pop(), attrs.pop()) except IndexError: pass self.cursor.attrs = self.cursor.attrs._replace(**replace)
[ "def", "select_graphic_rendition", "(", "self", ",", "*", "attrs", ")", ":", "replace", "=", "{", "}", "# Fast path for resetting all attributes.", "if", "not", "attrs", "or", "attrs", "==", "(", "0", ",", ")", ":", "self", ".", "cursor", ".", "attrs", "="...
Set display attributes. :param list attrs: a list of display attributes to set.
[ "Set", "display", "attributes", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L972-L1018
train
208,197
selectel/pyte
pyte/screens.py
Screen.report_device_attributes
def report_device_attributes(self, mode=0, **kwargs): """Report terminal identity. .. versionadded:: 0.5.0 .. versionchanged:: 0.7.0 If ``private`` keyword argument is set, the method does nothing. This behaviour is consistent with VT220 manual. """ # We only implement "primary" DA which is the only DA request # VT102 understood, see ``VT102ID`` in ``linux/drivers/tty/vt.c``. if mode == 0 and not kwargs.get("private"): self.write_process_input(ctrl.CSI + "?6c")
python
def report_device_attributes(self, mode=0, **kwargs): """Report terminal identity. .. versionadded:: 0.5.0 .. versionchanged:: 0.7.0 If ``private`` keyword argument is set, the method does nothing. This behaviour is consistent with VT220 manual. """ # We only implement "primary" DA which is the only DA request # VT102 understood, see ``VT102ID`` in ``linux/drivers/tty/vt.c``. if mode == 0 and not kwargs.get("private"): self.write_process_input(ctrl.CSI + "?6c")
[ "def", "report_device_attributes", "(", "self", ",", "mode", "=", "0", ",", "*", "*", "kwargs", ")", ":", "# We only implement \"primary\" DA which is the only DA request", "# VT102 understood, see ``VT102ID`` in ``linux/drivers/tty/vt.c``.", "if", "mode", "==", "0", "and", ...
Report terminal identity. .. versionadded:: 0.5.0 .. versionchanged:: 0.7.0 If ``private`` keyword argument is set, the method does nothing. This behaviour is consistent with VT220 manual.
[ "Report", "terminal", "identity", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L1020-L1033
train
208,198
selectel/pyte
pyte/screens.py
Screen.report_device_status
def report_device_status(self, mode): """Report terminal status or cursor position. :param int mode: if 5 -- terminal status, 6 -- cursor position, otherwise a noop. .. versionadded:: 0.5.0 """ if mode == 5: # Request for terminal status. self.write_process_input(ctrl.CSI + "0n") elif mode == 6: # Request for cursor position. x = self.cursor.x + 1 y = self.cursor.y + 1 # "Origin mode (DECOM) selects line numbering." if mo.DECOM in self.mode: y -= self.margins.top self.write_process_input(ctrl.CSI + "{0};{1}R".format(y, x))
python
def report_device_status(self, mode): """Report terminal status or cursor position. :param int mode: if 5 -- terminal status, 6 -- cursor position, otherwise a noop. .. versionadded:: 0.5.0 """ if mode == 5: # Request for terminal status. self.write_process_input(ctrl.CSI + "0n") elif mode == 6: # Request for cursor position. x = self.cursor.x + 1 y = self.cursor.y + 1 # "Origin mode (DECOM) selects line numbering." if mo.DECOM in self.mode: y -= self.margins.top self.write_process_input(ctrl.CSI + "{0};{1}R".format(y, x))
[ "def", "report_device_status", "(", "self", ",", "mode", ")", ":", "if", "mode", "==", "5", ":", "# Request for terminal status.", "self", ".", "write_process_input", "(", "ctrl", ".", "CSI", "+", "\"0n\"", ")", "elif", "mode", "==", "6", ":", "# Request for...
Report terminal status or cursor position. :param int mode: if 5 -- terminal status, 6 -- cursor position, otherwise a noop. .. versionadded:: 0.5.0
[ "Report", "terminal", "status", "or", "cursor", "position", "." ]
8adad489f86da1788a7995720c344a2fa44f244e
https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L1035-L1052
train
208,199