repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
rghe/ansible
lib/ansible/modules/network/avi/avi_certificatemanagementprofile.py
20
3783
#!/usr/bin/python # # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # Avi Version: 17.1.1 # # Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_certificatemanagementprofile author: Gaurav Rastogi (grastogi@avinetworks.com) short_description: Module for setup of CertificateManagementProfile Avi RESTful Object description: - This module is used to configure CertificateManagementProfile object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.3" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent", "present"] avi_api_update_method: description: - Default method for object update is HTTP PUT. - Setting to patch will override that behavior to use HTTP PATCH. version_added: "2.5" default: put choices: ["put", "patch"] avi_api_patch_op: description: - Patch operation to use when using avi_api_update_method as patch. version_added: "2.5" choices: ["add", "replace", "delete"] name: description: - Name of the pki profile. required: true script_params: description: - List of customparams. script_path: description: - Script_path of certificatemanagementprofile. required: true tenant_ref: description: - It is a reference to an object of type tenant. url: description: - Avi controller URL of the object. uuid: description: - Unique object identifier of the object. extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Example to create CertificateManagementProfile object avi_certificatemanagementprofile: controller: 10.10.25.42 username: admin password: something state: present name: sample_certificatemanagementprofile """ RETURN = ''' obj: description: CertificateManagementProfile (api/certificatemanagementprofile) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.avi import ( avi_common_argument_spec, HAS_AVI, avi_ansible_api) except ImportError: HAS_AVI = False def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), name=dict(type='str', required=True), script_params=dict(type='list',), script_path=dict(type='str', required=True), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'certificatemanagementprofile', set([])) if __name__ == '__main__': main()
gpl-3.0
YtoTech/latex-on-http
latexonhttp/latexrun.py
1
77338
#!/usr/bin/env python3 # Copyright (c) 2013, 2014 Austin Clements # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys import os import errno import argparse import shlex import json import subprocess import re import collections import hashlib import shutil import curses import filecmp import io import traceback import time try: import fcntl except ImportError: # Non-UNIX platform fcntl = None def debug(string, *args): if debug.enabled: print(string.format(*args), file=sys.stderr) debug.enabled = False def debug_exc(): if debug.enabled: traceback.print_exc() def main(): # Parse command-line arg_parser = argparse.ArgumentParser( description="""A 21st century LaTeX wrapper, %(prog)s runs latex (and bibtex) the right number of times so you don't have to, strips the log spew to make errors visible, and plays well with standard build tools.""" ) arg_parser.add_argument( "-o", metavar="FILE", dest="output", default=None, help="Output file name (default: derived from input file)", ) arg_parser.add_argument( "--latex-cmd", metavar="CMD", default="pdflatex", help="Latex command (default: %(default)s)", ) arg_parser.add_argument( "--latex-args", metavar="ARGS", type=arg_parser_shlex, help="Additional command-line arguments for latex." " This will be parsed and split using POSIX shell rules.", ) arg_parser.add_argument( "--bibtex-cmd", metavar="CMD", default="bibtex", help="Bibtex command (default: %(default)s)", ) arg_parser.add_argument( "--bibtex-args", metavar="ARGS", type=arg_parser_shlex, help="Additional command-line arguments for bibtex", ) arg_parser.add_argument( "--max-iterations", metavar="N", type=int, default=10, help="Max number of times to run latex before giving up" " (default: %(default)s)", ) arg_parser.add_argument( "-W", metavar="(no-)CLASS", action=ArgParserWarnAction, dest="nowarns", default=set(["underfull"]), help="Enable/disable warning from CLASS, which can be any package name, " "LaTeX warning class (e.g., font), bad box type " '(underfull, overfull, loose, tight), or "all"', ) arg_parser.add_argument( "-O", metavar="DIR", dest="obj_dir", default="latex.out", help="Directory for intermediate files and control database " "(default: %(default)s)", ) arg_parser.add_argument( "--color", choices=("auto", "always", "never"), default="auto", help="When to colorize messages", ) arg_parser.add_argument( "--verbose-cmds", action="store_true", default=False, help="Print commands as they are executed", ) arg_parser.add_argument( "--debug", action="store_true", help="Enable detailed debug output" ) actions = arg_parser.add_argument_group("actions") actions.add_argument("--clean-all", action="store_true", help="Delete output files") actions.add_argument("file", nargs="?", help=".tex file to compile") args = arg_parser.parse_args() if not any([args.clean_all, args.file]): arg_parser.error("at least one action is required") args.latex_args = args.latex_args or [] args.bibtex_args = args.bibtex_args or [] verbose_cmd.enabled = args.verbose_cmds debug.enabled = args.debug # A note about encodings: POSIX encoding is a mess; TeX encoding # is a disaster. Our goal is to make things no worse, so we want # byte-accurate round-tripping of TeX messages. Since TeX # messages are *basically* text, we use strings and # surrogateescape'ing for both input and output. I'm not fond of # setting surrogateescape globally, but it's far easier than # dealing with every place we pass TeX output through. # Conveniently, JSON can round-trip surrogateescape'd strings, so # our control database doesn't need special handling. sys.stdout = io.TextIOWrapper( sys.stdout.buffer, encoding=sys.stdout.encoding, errors="surrogateescape", line_buffering=sys.stdout.line_buffering, ) sys.stderr = io.TextIOWrapper( sys.stderr.buffer, encoding=sys.stderr.encoding, errors="surrogateescape", line_buffering=sys.stderr.line_buffering, ) Message.setup_color(args.color) # Open control database. dbpath = os.path.join(args.obj_dir, ".latexrun.db") if not os.path.exists(dbpath) and os.path.exists(".latexrun.db"): # The control database used to live in the source directory. # Support this for backwards compatibility. dbpath = ".latexrun.db" try: db = DB(dbpath) except (ValueError, OSError) as e: print( "error opening {}: {}".format( e.filename if hasattr(e, "filename") else dbpath, e ), file=sys.stderr, ) debug_exc() sys.exit(1) # Clean if args.clean_all: try: db.do_clean(args.obj_dir) except OSError as e: print(e, file=sys.stderr) debug_exc() sys.exit(1) # Build if not args.file: return task_commit = None try: task_latex = LaTeX( db, args.file, args.latex_cmd, args.latex_args, args.obj_dir, args.nowarns ) task_commit = LaTeXCommit(db, task_latex, args.output) task_bibtex = BibTeX( db, task_latex, args.bibtex_cmd, args.bibtex_args, args.nowarns, args.obj_dir, ) tasks = [task_latex, task_commit, task_bibtex] stable = run_tasks(tasks, args.max_iterations) # Print final task output and gather exit status status = 0 for task in tasks: status = max(task.report(), status) if not stable: print( "error: files are still changing after {} iterations; giving up".format( args.max_iterations ), file=sys.stderr, ) status = max(status, 1) except TaskError as e: print(str(e), file=sys.stderr) debug_exc() status = 1 # Report final status, if interesting fstatus = "There were errors" if task_commit is None else task_commit.status if fstatus: output = args.output if output is None: if task_latex.get_outname() is not None: output = os.path.basename(task_latex.get_outname()) else: output = "output" if Message._color: terminfo.send("bold", ("setaf", 1)) print("{}; {} not updated".format(fstatus, output)) if Message._color: terminfo.send("sgr0") sys.exit(status) def arg_parser_shlex(string): """Argument parser for shell token lists.""" try: return shlex.split(string) except ValueError as e: raise argparse.ArgumentTypeError(str(e)) from None class ArgParserWarnAction(argparse.Action): def __call__(self, parser, namespace, value, option_string=None): nowarn = getattr(namespace, self.dest) if value == "all": nowarn.clear() elif value.startswith("no-"): nowarn.add(value[3:]) else: nowarn.discard(value) setattr(namespace, self.dest, nowarn) def verbose_cmd(args, cwd=None, env=None): if verbose_cmd.enabled: cmd = " ".join(map(shlex.quote, args)) if cwd is not None: cmd = "(cd {} && {})".format(shlex.quote(cwd), cmd) if env is not None: for k, v in env.items(): if os.environ.get(k) != v: cmd = "{}={} {}".format(k, shlex.quote(v), cmd) print(cmd, file=sys.stderr) verbose_cmd.enabled = False def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise class DB: """A latexrun control database.""" _VERSION = "latexrun-db-v2" def __init__(self, filename): self.__filename = filename # Make sure database directory exists if os.path.dirname(self.__filename): os.makedirs(os.path.dirname(self.__filename), exist_ok=True) # Lock the database if possible. We don't release this lock # until the process exits. lockpath = self.__filename + ".lock" if fcntl is not None: lockfd = os.open(lockpath, os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC, 0o666) # Note that this is actually an fcntl lock, not a lockf # lock. Don't be fooled. fcntl.lockf(lockfd, fcntl.LOCK_EX, 1) try: fp = open(filename, "r") except FileNotFoundError: debug("creating new database") self.__val = {"version": DB._VERSION} else: debug("loading database") self.__val = json.load(fp) if "version" not in self.__val: raise ValueError( "file exists, but does not appear to be a latexrun database".format( filename ) ) if self.__val["version"] != DB._VERSION: raise ValueError( "unknown database version {!r}".format(self.__val["version"]) ) def commit(self): debug("committing database") # Atomically commit database tmp_filename = self.__filename + ".tmp" with open(tmp_filename, "w") as fp: json.dump(self.__val, fp, indent=2, separators=(",", ": ")) fp.flush() os.fsync(fp.fileno()) os.rename(tmp_filename, self.__filename) def get_summary(self, task_id): """Return the recorded summary for the given task or None.""" return self.__val.get("tasks", {}).get(task_id) def set_summary(self, task_id, summary): """Set the summary for the given task.""" self.__val.setdefault("tasks", {})[task_id] = summary def add_clean(self, filename): """Add an output file to be cleaned. Unlike the output files recorded in the task summaries, cleanable files strictly accumulate until a clean is performed. """ self.__val.setdefault("clean", {})[filename] = hash_cache.get(filename) def do_clean(self, obj_dir=None): """Remove output files and delete database. If obj_dir is not None and it is empty after all files are removed, it will also be removed. """ for f, want_hash in self.__val.get("clean", {}).items(): have_hash = hash_cache.get(f) if have_hash is not None: if want_hash == have_hash: debug("unlinking {}", f) hash_cache.invalidate(f) os.unlink(f) else: print( "warning: {} has changed; not removing".format(f), file=sys.stderr, ) self.__val = {"version": DB._VERSION} try: os.unlink(self.__filename) except FileNotFoundError: pass if obj_dir is not None: try: os.rmdir(obj_dir) except OSError: pass class HashCache: """Cache of file hashes. As latexrun reaches fixed-point, it hashes the same files over and over, many of which never change. Since hashing is somewhat expensive, we keep a simple cache of these hashes. """ def __init__(self): self.__cache = {} def get(self, filename): """Return the hash of filename, or * if it was clobbered.""" try: with open(filename, "rb") as fp: st = os.fstat(fp.fileno()) key = (st.st_dev, st.st_ino) if key in self.__cache: return self.__cache[key] debug("hashing {}", filename) h = hashlib.sha256() while True: block = fp.read(256 * 1024) if not len(block): break h.update(block) self.__cache[key] = h.hexdigest() return self.__cache[key] except (FileNotFoundError, IsADirectoryError): return None def clobber(self, filename): """If filename's hash is not known, record an invalid hash. This can be used when filename was overwritten before we were necessarily able to obtain its hash. filename must exist. """ st = os.stat(filename) key = (st.st_dev, st.st_ino) if key not in self.__cache: self.__cache[key] = "*" def invalidate(self, filename): try: st = os.stat(filename) except OSError as e: # Pessimistically wipe the whole cache debug("wiping hash cache ({})", e) self.__cache.clear() else: key = (st.st_dev, st.st_ino) if key in self.__cache: del self.__cache[key] hash_cache = HashCache() class _Terminfo: def __init__(self): self.__tty = os.isatty(sys.stdout.fileno()) if self.__tty: curses.setupterm() self.__ti = {} def __ensure(self, cap): if cap not in self.__ti: if not self.__tty: string = None else: string = curses.tigetstr(cap) if string is None or b"$<" in string: # Don't have this capability or it has a pause string = None self.__ti[cap] = string return self.__ti[cap] def has(self, *caps): return all(self.__ensure(cap) is not None for cap in caps) def send(self, *caps): # Flush TextIOWrapper to the binary IO buffer sys.stdout.flush() for cap in caps: # We should use curses.putp here, but it's broken in # Python3 because it writes directly to C's buffered # stdout and there's no way to flush that. if isinstance(cap, tuple): s = curses.tparm(self.__ensure(cap[0]), *cap[1:]) else: s = self.__ensure(cap) sys.stdout.buffer.write(s) terminfo = _Terminfo() class Progress: _enabled = None def __init__(self, prefix): self.__prefix = prefix if Progress._enabled is None: Progress._enabled = (not debug.enabled) and terminfo.has( "cr", "el", "rmam", "smam" ) def __enter__(self): self.last = "" self.update("") return self def __exit__(self, typ, value, traceback): if Progress._enabled: # Beginning of line and clear terminfo.send("cr", "el") sys.stdout.flush() def update(self, msg): if not Progress._enabled: return out = "[" + self.__prefix + "]" if msg: out += " " + msg if out != self.last: # Beginning of line, clear line, disable wrap terminfo.send("cr", "el", "rmam") sys.stdout.write(out) # Enable wrap terminfo.send("smam") self.last = out sys.stdout.flush() class Message(collections.namedtuple("Message", "typ filename lineno msg")): def emit(self): if self.filename: if self.filename.startswith("./"): finfo = self.filename[2:] else: finfo = self.filename else: finfo = "<no file>" if self.lineno is not None: finfo += ":" + str(self.lineno) finfo += ": " if self._color: terminfo.send("bold") sys.stdout.write(finfo) if self.typ != "info": if self._color: terminfo.send(("setaf", 5 if self.typ == "warning" else 1)) sys.stdout.write(self.typ + ": ") if self._color: terminfo.send("sgr0") sys.stdout.write(self.msg + "\n") @classmethod def setup_color(cls, state): if state == "never": cls._color = False elif state == "always": cls._color = True elif state == "auto": cls._color = terminfo.has("setaf", "bold", "sgr0") else: raise ValueError("Illegal color state {:r}".format(state)) ################################################################## # Task framework # terminate_task_loop = False start_time = time.time() def run_tasks(tasks, max_iterations): """Execute tasks in round-robin order until all are stable. This will also exit if terminate_task_loop is true. Tasks may use this to terminate after a fatal error (even if that fatal error doesn't necessarily indicate stability; as long as re-running the task will never eliminate the fatal error). Return True if fixed-point is reached or terminate_task_loop is set within max_iterations iterations. """ global terminate_task_loop terminate_task_loop = False nstable = 0 for iteration in range(max_iterations): for task in tasks: if task.stable(): nstable += 1 if nstable == len(tasks): debug("fixed-point reached") return True else: task.run() nstable = 0 if terminate_task_loop: debug("terminate_task_loop set") return True debug("fixed-point not reached") return False class TaskError(Exception): pass class Task: """A deterministic computation whose inputs and outputs can be captured.""" def __init__(self, db, task_id): self.__db = db self.__task_id = task_id def __debug(self, string, *args): if debug.enabled: debug("task {}: {}", self.__task_id, string.format(*args)) def stable(self): """Return True if running this task will not affect system state. Functionally, let f be the task, and s be the system state. Then s' = f(s). If it must be that s' == s (that is, f has reached a fixed point), then this function must return True. """ last_summary = self.__db.get_summary(self.__task_id) if last_summary is None: # Task has never run, so running it will modify system # state changed = "never run" else: # If any of the inputs have changed since the last run of # this task, the result may change, so re-run the task. # Also, it's possible something else changed an output # file, in which case we also want to re-run the task, so # check the outputs, too. changed = self.__summary_changed(last_summary) if changed: self.__debug("unstable (changed: {})", changed) return False else: self.__debug("stable") return True def __summary_changed(self, summary): """Test if any inputs changed from summary. Returns a string describing the changed input, or None. """ for dep in summary["deps"]: fn, args, val = dep method = getattr(self, "_input_" + fn, None) if method is None: return "unknown dependency method {}".format(fn) if method == self._input_unstable or method(*args) != val: return "{}{}".format(fn, tuple(args)) return None def _input(self, name, *args): """Register an input for this run. This calls self._input_<name>(*args) to get the value of this input. This function should run quickly and return some projection of system state that affects the result of this computation. Both args and the return value must be JSON serializable. """ method = getattr(self, "_input_" + name) val = method(*args) if [name, args, val] not in self.__deps: self.__deps.append([name, args, val]) return val def run(self): # Before we run the task, pre-hash any files that were output # files in the last run. These may be input by this run and # then clobbered, at which point it will be too late to get an # input hash. Ideally we would only hash files that were # *both* input and output files, but latex doesn't tell us # about input files that didn't exist, so if we start from a # clean slate, we often require an extra run because we don't # know a file is input/output until after the second run. last_summary = self.__db.get_summary(self.__task_id) if last_summary is not None: for io_filename in last_summary["output_files"]: self.__debug("pre-hashing {}", io_filename) hash_cache.get(io_filename) # Run the task self.__debug("running") self.__deps = [] result = self._execute() # Clear cached output file hashes for filename in result.output_filenames: hash_cache.invalidate(filename) # If the output files change, then the computation needs to be # re-run, so record them as inputs for filename in result.output_filenames: self._input("file", filename) # Update task summary in database self.__db.set_summary(self.__task_id, self.__make_summary(self.__deps, result)) del self.__deps # Add output files to be cleaned for f in result.output_filenames: self.__db.add_clean(f) try: self.__db.commit() except OSError as e: raise TaskError( "error committing control database {}: {}".format( getattr(e, "filename", "<unknown path>"), e ) ) from e def __make_summary(self, deps, run_result): """Construct a new task summary.""" return { "deps": deps, "output_files": {f: hash_cache.get(f) for f in run_result.output_filenames}, "extra": run_result.extra, } def _execute(self): """Abstract: Execute this task. Subclasses should implement this method to execute this task. This method must return a RunResult giving the inputs that were used by the task and the outputs it produced. """ raise NotImplementedError("Task._execute is abstract") def _get_result_extra(self): """Return the 'extra' result from the previous run, or None.""" summary = self.__db.get_summary(self.__task_id) if summary is None: return None return summary["extra"] def report(self): """Report the task's results to stdout and return exit status. This may be called when the task has never executed. Subclasses should override this. The default implementation reports nothing and returns 0. """ return 0 # Standard input functions def _input_env(self, var): return os.environ.get(var) def _input_file(self, path): return hash_cache.get(path) def _input_unstable(self): """Mark this run as unstable, regardless of other inputs.""" return None def _input_unknown_input(self): """An unknown input that may change after latexrun exits. This conservatively marks some unknown input that definitely won't change while latexrun is running, but may change before the user next runs latexrun. This allows the task to stabilize during this invocation, but will cause the task to re-run on the next invocation. """ return start_time class RunResult(collections.namedtuple("RunResult", "output_filenames extra")): """The result of a single task execution. This captures all files written by the task, and task-specific results that need to be persisted between runs (for example, to enable reporting of a task's results). """ pass ################################################################## # LaTeX task # def normalize_input_path(path): # Resolve the directory of the input path, but leave the file # component alone because it affects TeX's behavior. head, tail = os.path.split(path) npath = os.path.join(os.path.realpath(head), tail) return os.path.relpath(path) class LaTeX(Task): def __init__(self, db, tex_filename, cmd, cmd_args, obj_dir, nowarns): super().__init__(db, "latex::" + normalize_input_path(tex_filename)) self.__tex_filename = tex_filename self.__cmd = cmd self.__cmd_args = cmd_args self.__obj_dir = obj_dir self.__nowarns = nowarns self.__pass = 0 def _input_args(self): # If filename starts with a character the tex command-line # treats specially, then tweak it so it doesn't. filename = self.__tex_filename if filename.startswith(("-", "&", "\\")): filename = "./" + filename # XXX Put these at the beginning in case the provided # arguments are malformed. Might want to do a best-effort # check for incompatible user-provided arguments (note: # arguments can be given with one or two dashes and those with # values can use an equals or a space). return ( [self.__cmd] + self.__cmd_args + [ "-interaction", "nonstopmode", "-recorder", "-output-directory", self.__obj_dir, filename, ] ) def _execute(self): # Run latex self.__pass += 1 args = self._input("args") debug("running {}", args) try: os.makedirs(self.__obj_dir, exist_ok=True) except OSError as e: raise TaskError("failed to create %s: " % self.__obj_dir + str(e)) from e try: verbose_cmd(args) p = subprocess.Popen( args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) stdout, has_errors, missing_includes = self.__feed_terminal(p.stdout) status = p.wait() except OSError as e: raise TaskError("failed to execute latex task: " + str(e)) from e # Register environment variable inputs for env_var in [ "TEXMFOUTPUT", "TEXINPUTS", "TEXFORMATS", "TEXPOOL", "TFMFONTS", "PATH", ]: self._input("env", env_var) jobname, outname = self.__parse_jobname(stdout) inputs, outputs = self.__parse_recorder(jobname) # LaTeX overwrites its own inputs. Mark its output files as # clobbered before we hash its input files. for path in outputs: # In some abort cases (e.g., >=100 errors), LaTeX claims # output files that don't actually exist. if os.path.exists(path): hash_cache.clobber(path) # Depend on input files. Task.run pre-hashed outputs from the # previous run, so if this isn't the first run and as long as # the set of outputs didn't change, we'll be able to get the # input hashes, even if they were clobbered. for path in inputs: self._input("file", path) if missing_includes: # Missing \includes are tricky. Ideally we'd depend on # the absence of some file, but in fact we'd have to # depend on the failure of a whole kpathsea lookup. # Rather than try to be clever, just mark this as an # unknown input so we'll run at least once on the next # invocation. self._input("unknown_input") if not self.__create_outdirs(stdout) and has_errors: # LaTeX reported unrecoverable errors (other than output # directory errors, which we just fixed). We could # continue to stabilize the document, which may change # some of the other problems reported (but not the # unrecoverable errors), or we can just abort now and get # back to the user quickly with the major errors. We opt # for the latter. global terminate_task_loop terminate_task_loop = True # This error could depend on something we failed to track. # It would be really confusing if we continued to report # the error after the user fixed it, so be conservative # and force a re-run next time. self._input("unknown_input") return RunResult( outputs, {"jobname": jobname, "outname": outname, "status": status} ) def __feed_terminal(self, stdout): prefix = "latex" if self.__pass > 1: prefix += " ({})".format(self.__pass) with Progress(prefix) as progress: buf = [] filt = LaTeXFilter() while True: # Use os.read to read only what's available on the pipe, # without waiting to fill a buffer data = os.read(stdout.fileno(), 4096) if not data: break # See "A note about encoding" above data = data.decode("ascii", errors="surrogateescape") buf.append(data) filt.feed(data) file_stack = filt.get_file_stack() if file_stack: tos = file_stack[-1] if tos.startswith("./"): tos = tos[2:] progress.update(">" * len(file_stack) + " " + tos) else: progress.update("") # Were there unrecoverable errors? has_errors = any(msg.typ == "error" for msg in filt.get_messages()) return "".join(buf), has_errors, filt.has_missing_includes() def __parse_jobname(self, stdout): """Extract the job name and output name from latex's output. We get these from latex because they depend on complicated file name parsing rules, are affected by arguments like -output-directory, and may be just "texput" if things fail really early. The output name may be None if there were no pages of output. """ jobname = outname = None for m in re.finditer( r'^Transcript written on "?(.*)\.log"?\.$', stdout, re.MULTILINE | re.DOTALL ): jobname = m.group(1).replace("\n", "") if jobname is None: print(stdout, file=sys.stderr) raise TaskError("failed to extract job name from latex log") for m in re.finditer( r'^Output written on "?(.*\.[^ ."]+)"? \([0-9]+ page', stdout, re.MULTILINE | re.DOTALL, ): outname = m.group(1).replace("\n", "") if outname is None and not re.search( r"^No pages of output\.$|^! Emergency stop\.$" r"|^! ==> Fatal error occurred, no output PDF file produced!$", stdout, re.MULTILINE, ): print(stdout, file=sys.stderr) raise TaskError("failed to extract output name from latex log") # LuaTeX (0.76.0) doesn't include the output directory in the # logged transcript or output file name. if os.path.basename(jobname) == jobname and os.path.exists( os.path.join(self.__obj_dir, jobname + ".log") ): jobname = os.path.join(self.__obj_dir, jobname) if outname is not None: outname = os.path.join(self.__obj_dir, outname) return jobname, outname def __parse_recorder(self, jobname): """Parse file recorder output.""" # XXX If latex fails because a file isn't found, that doesn't # go into the .fls file, but creating that file will affect # the computation, so it should be included as an input. # Though it's generally true that files can be added earlier # in search paths and will affect the output without us knowing. # # XXX This is a serious problem for bibtex, since the first # run won't depend on the .bbl file! But maybe the .aux file # will always cause a re-run, at which point the .bbl will # exist? filename = jobname + ".fls" try: recorder = open(filename) except OSError as e: raise TaskError("failed to open file recorder output: " + str(e)) from e pwd, inputs, outputs = "", set(), set() for linenum, line in enumerate(recorder): parts = line.rstrip("\n").split(" ", 1) if parts[0] == "PWD": pwd = parts[1] elif parts[0] in ("INPUT", "OUTPUT"): if parts[1].startswith("/"): path = parts[1] else: # Try to make "nice" paths, especially for clean path = os.path.relpath(os.path.join(pwd, parts[1])) if parts[0] == "INPUT": inputs.add(path) else: outputs.add(path) else: raise TaskError( "syntax error on line {} of {}".format(linenum, filename) ) # Ironically, latex omits the .fls file itself outputs.add(filename) return inputs, outputs def __create_outdirs(self, stdout): # In some cases, such as \include'ing a file from a # subdirectory, TeX will attempt to create files in # subdirectories of the output directory that don't exist. # Detect this, create the output directory, and re-run. m = re.search("^! I can't write on file `(.*)'\\.$", stdout, re.M) if m and m.group(1).find("/") > 0 and "../" not in m.group(1): debug("considering creating output sub-directory for {}".format(m.group(1))) subdir = os.path.dirname(m.group(1)) newdir = os.path.join(self.__obj_dir, subdir) if os.path.isdir(subdir) and not os.path.isdir(newdir): debug("creating output subdirectory {}".format(newdir)) try: mkdir_p(newdir) except OSError as e: raise TaskError( "failed to create output subdirectory: " + str(e) ) from e self._input("unstable") return True def report(self): extra = self._get_result_extra() if extra is None: return 0 # Parse the log logfile = open(extra["jobname"] + ".log", "rt", errors="surrogateescape") for msg in self.__clean_messages( LaTeXFilter(self.__nowarns).feed(logfile.read(), True).get_messages() ): msg.emit() # Return LaTeX's exit status return extra["status"] def __clean_messages(self, msgs): """Make some standard log messages more user-friendly.""" have_undefined_reference = False for msg in msgs: if msg.msg == "==> Fatal error occurred, no output PDF file produced!": msg = msg._replace( typ="info", msg="Fatal error (no output file produced)" ) if msg.msg.startswith("[LaTeX] "): # Strip unnecessary package name msg = msg._replace(msg=msg.msg.split(" ", 1)[1]) if re.match(r"Reference .* undefined", msg.msg): have_undefined_reference = True if have_undefined_reference and re.match( r"There were undefined references", msg.msg ): # LaTeX prints this at the end so the user knows it's # worthwhile looking back at the log. Since latexrun # makes the earlier messages obvious, this is # redundant. continue yield msg def get_tex_filename(self): return self.__tex_filename def get_jobname(self): extra = self._get_result_extra() if extra is None: return None return extra["jobname"] def get_outname(self): extra = self._get_result_extra() if extra is None: return None return extra["outname"] def get_status(self): extra = self._get_result_extra() if extra is None: return None return extra["status"] class LaTeXCommit(Task): def __init__(self, db, latex_task, output_path): super().__init__( db, "latex_commit::" + normalize_input_path(latex_task.get_tex_filename()) ) self.__latex_task = latex_task self.__output_path = output_path self.status = "There were errors" def _input_latex(self): return self.__latex_task.get_status(), self.__latex_task.get_outname() def _execute(self): self.status = "There were errors" # If latex succeeded with output, atomically commit the output status, outname = self._input("latex") if status != 0 or outname is None: debug("not committing (status {}, outname {})", status, outname) if outname is None: self.status = "No pages of output" return RunResult([], None) commit = self.__output_path or os.path.basename(outname) if os.path.abspath(commit) == os.path.abspath(outname): debug("skipping commit (outname is commit name)") self.status = None return RunResult([], None) try: if os.path.exists(commit) and filecmp.cmp(outname, commit): debug("skipping commit ({} and {} are identical)", outname, commit) # To avoid confusion, touch the output file open(outname, "r+b").close() else: debug("commiting {} to {}", outname, commit) shutil.copy(outname, outname + "~") os.rename(outname + "~", commit) except OSError as e: raise TaskError("error committing latex output: {}".format(e)) from e self._input("file", outname) self.status = None return RunResult([commit], None) class LaTeXFilter: TRACE = False # Set to enable detailed parse tracing def __init__(self, nowarns=[]): self.__data = "" self.__restart_pos = 0 self.__restart_file_stack = [] self.__restart_messages_len = 0 self.__messages = [] self.__first_file = None self.__fatal_error = False self.__missing_includes = False self.__pageno = 1 self.__restart_pageno = 1 self.__suppress = {cls: 0 for cls in nowarns} def feed(self, data, eof=False): """Feed LaTeX log data to the parser. The log data can be from LaTeX's standard output, or from the log file. If there will be no more data, set eof to True. """ self.__data += data self.__data_complete = eof # Reset to last known-good restart point self.__pos = self.__restart_pos self.__file_stack = self.__restart_file_stack.copy() self.__messages = self.__messages[: self.__restart_messages_len] self.__lstart = self.__lend = -1 self.__pageno = self.__restart_pageno # Parse forward while self.__pos < len(self.__data): self.__noise() # Handle suppressed warnings if eof: msgs = [ "%d %s warning%s" % (count, cls, "s" if count > 1 else "") for cls, count in self.__suppress.items() if count ] if msgs: self.__message( "info", None, "%s not shown (use -Wall to show them)" % ", ".join(msgs), filename=self.__first_file, ) if eof and len(self.__file_stack) and not self.__fatal_error: # Fatal errors generally cause TeX to "succumb" without # closing the file stack, so don't complain in that case. self.__message( "warning", None, "unbalanced `(' in log; file names may be wrong" ) return self def get_messages(self): """Return a list of warning and error Messages.""" return self.__messages def get_file_stack(self): """Return the file stack for the data that has been parsed. This results a list from outermost file to innermost file. The list may be empty. """ return self.__file_stack def has_missing_includes(self): """Return True if the log reported missing \\include files.""" return self.__missing_includes def __save_restart_point(self): """Save the current state as a known-good restart point. On the next call to feed, the parser will reset to this point. """ self.__restart_pos = self.__pos self.__restart_file_stack = self.__file_stack.copy() self.__restart_messages_len = len(self.__messages) self.__restart_pageno = self.__pageno def __message(self, typ, lineno, msg, cls=None, filename=None): if cls is not None and cls in self.__suppress: self.__suppress[cls] += 1 return filename = filename or ( self.__file_stack[-1] if self.__file_stack else self.__first_file ) self.__messages.append(Message(typ, filename, lineno, msg)) def __ensure_line(self): """Update lstart and lend.""" if self.__lstart <= self.__pos < self.__lend: return self.__lstart = self.__data.rfind("\n", 0, self.__pos) + 1 self.__lend = self.__data.find("\n", self.__pos) + 1 if self.__lend == 0: self.__lend = len(self.__data) @property def __col(self): """The 0-based column number of __pos.""" self.__ensure_line() return self.__pos - self.__lstart @property def __avail(self): return self.__pos < len(self.__data) def __lookingat(self, needle): return self.__data.startswith(needle, self.__pos) def __lookingatre(self, regexp, flags=0): return re.compile(regexp, flags=flags).match(self.__data, self.__pos) def __skip_line(self): self.__ensure_line() self.__pos = self.__lend def __consume_line(self, unwrap=False): self.__ensure_line() data = self.__data[self.__pos : self.__lend] self.__pos = self.__lend if unwrap: # TeX helpfully wraps all terminal output at 79 columns # (max_print_line). If requested, unwrap it. There's # simply no way to do this perfectly, since there could be # a line that happens to be 79 columns. # # We check for >=80 because a bug in LuaTeX causes it to # wrap at 80 columns instead of 79 (LuaTeX #900). while self.__lend - self.__lstart >= 80: if self.TRACE: print("<{}> wrapping".format(self.__pos)) self.__ensure_line() data = data[:-1] + self.__data[self.__pos : self.__lend] self.__pos = self.__lend return data # Parser productions def __noise(self): # Most of TeX's output is line noise that combines error # messages, warnings, file names, user errors and warnings, # and echos of token lists and other input. This attempts to # tease these apart, paying particular attention to all of the # places where TeX echos input so that parens in the input do # not confuse the file name scanner. There are three # functions in TeX that echo input: show_token_list (used by # runaway and show_context, which is used by print_err), # short_display (used by overfull/etc h/vbox), and show_print # (used in issue_message and the same places as # show_token_list). lookingat, lookingatre = self.__lookingat, self.__lookingatre if self.__col == 0: # The following messages are always preceded by a newline if lookingat("! "): return self.__errmessage() if lookingat("!pdfTeX error: "): return self.__pdftex_fail() if lookingat("Runaway "): return self.__runaway() if lookingatre(r"(Overfull|Underfull|Loose|Tight) \\[hv]box \("): return self.__bad_box() if lookingatre("(Package |Class |LaTeX |pdfTeX )?(\w+ )?warning: ", re.I): return self.__generic_warning() if lookingatre("No file .*\\.tex\\.$", re.M): # This happens with \includes of missing files. For # whatever reason, LaTeX doesn't consider this even # worth a warning, but I do! self.__message( "warning", None, self.__simplify_message(self.__consume_line(unwrap=True).strip()), ) self.__missing_includes = True return # Other things that are common and irrelevant if lookingatre(r"(Package|Class|LaTeX) (\w+ )?info: ", re.I): return self.__generic_info() if lookingatre(r"(Document Class|File|Package): "): # Output from "\ProvidesX" return self.__consume_line(unwrap=True) if lookingatre(r"\\\w+=\\[a-z]+\d+\n"): # Output from "\new{count,dimen,skip,...}" return self.__consume_line(unwrap=True) # print(self.__data[self.__lstart:self.__lend].rstrip()) # self.__pos = self.__lend # return # Now that we've substantially reduced the spew and hopefully # eliminated all input echoing, we're left with the file name # stack, page outs, and random other messages from both TeX # and various packages. We'll assume at this point that all # parentheses belong to the file name stack or, if they're in # random other messages, they're at least balanced and nothing # interesting happens between them. For page outs, ship_out # prints a space if not at the beginning of a line, then a # "[", then the page number being shipped out (this is # usually, but not always, followed by "]"). m = re.compile(r"[(){}\n]|(?<=[\n ])\[\d+", re.M).search( self.__data, self.__pos ) if m is None: self.__pos = len(self.__data) return self.__pos = m.start() + 1 ch = self.__data[m.start()] if ch == "\n": # Save this as a known-good restart point for incremental # parsing, since we definitely didn't match any of the # known message types above. self.__save_restart_point() elif ch == "[": # This is printed at the end of a page, so we're beginning # page n+1. self.__pageno = int(self.__lookingatre(r"\d+").group(0)) + 1 elif ( self.__data.startswith("`", m.start() - 1) or self.__data.startswith("`\\", m.start() - 2) ) and self.__data.startswith("'", m.start() + 1): # (, ), {, and } sometimes appear in TeX's error # descriptions, but they're always in `'s (and sometimes # backslashed) return elif ch == "(": # XXX Check that the stack doesn't drop to empty and then re-grow first = self.__first_file is None and self.__col == 1 filename = self.__filename() self.__file_stack.append(filename) if first: self.__first_file = filename if self.TRACE: print( "<{}>{}enter {}".format( m.start(), " " * len(self.__file_stack), filename ) ) elif ch == ")": if len(self.__file_stack): if self.TRACE: print( "<{}>{}exit {}".format( m.start(), " " * len(self.__file_stack), self.__file_stack[-1], ) ) self.__file_stack.pop() else: self.__message( "warning", None, "extra `)' in log; file names may be wrong " ) elif ch == "{": # TeX uses this for various things we want to ignore, like # file names and print_mark. Consume up to the '}' epos = self.__data.find("}", self.__pos) if epos != -1: self.__pos = epos + 1 else: self.__message( "warning", None, "unbalanced `{' in log; file names may be wrong" ) elif ch == "}": self.__message("warning", None, "extra `}' in log; file names may be wrong") def __filename(self): initcol = self.__col first = True name = "" # File names may wrap, but if they do, TeX will always print a # newline before the open paren while first or (initcol == 1 and self.__lookingat("\n") and self.__col >= 79): if not first: self.__pos += 1 m = self.__lookingatre(r"[^(){} \n]*") name += m.group() self.__pos = m.end() first = False return name def __simplify_message(self, msg): msg = re.sub( r"^(?:Package |Class |LaTeX |pdfTeX )?([^ ]+) (?:Error|Warning): ", r"[\1] ", msg, flags=re.I, ) msg = re.sub(r"\.$", "", msg) msg = re.sub(r"has occurred (while \\output is active)", r"\1", msg) return msg def __errmessage(self): # Procedure print_err (including \errmessage, itself used by # LaTeX's \GenericError and all of its callers), as well as # fatal_error. Prints "\n! " followed by error text # ("Emergency stop" in the case of fatal_error). print_err is # always followed by a call to error, which prints a period, # and a newline... msg = self.__consume_line(unwrap=True)[1:].strip() is_fatal_error = msg == "Emergency stop." msg = self.__simplify_message(msg) # ... and then calls show_context, which prints the input # stack as pairs of lines giving the context. These context # lines are truncated so they never wrap. Each pair of lines # will start with either "<something> " if the context is a # token list, "<*> " for terminal input (or command line), # "<read ...>" for stream reads, something like "\macroname # #1->" for macros (though everything after \macroname is # subject to being elided as "..."), or "l.[0-9]+ " if it's a # file. This is followed by the errant input with a line # break where the error occurred. lineno = None found_context = False stack = [] while self.__avail: m1 = self.__lookingatre(r"<([a-z ]+|\*|read [^ >]*)> |\\.*(->|...)") m2 = self.__lookingatre("l\.[0-9]+ ") if m1: found_context = True pre = self.__consume_line().rstrip("\n") stack.append(pre) elif m2: found_context = True pre = self.__consume_line().rstrip("\n") info, rest = pre.split(" ", 1) lineno = int(info[2:]) stack.append(rest) elif found_context: # Done with context break if found_context: # Consume the second context line post = self.__consume_line().rstrip("\n") # Clean up goofy trailing ^^M TeX sometimes includes post = re.sub(r"\^\^M$", "", post) if post[: len(pre)].isspace() and not post.isspace(): stack.append(len(stack[-1])) stack[-2] += post[len(pre) :] else: # If we haven't found the context, skip the line. self.__skip_line() stack_msg = "" for i, trace in enumerate(stack): stack_msg += ( "\n " + (" " * trace) + "^" if isinstance(trace, int) else "\n at " + trace.rstrip() if i == 0 else "\n from " + trace.rstrip() ) if is_fatal_error: # fatal_error always prints one additional line of message info = self.__consume_line().strip() if info.startswith("*** "): info = info[4:] msg += ": " + info.lstrip("(").rstrip(")") self.__message("error", lineno, msg + stack_msg) self.__fatal_error = True def __pdftex_fail(self): # Procedure pdftex_fail. Prints "\n!pdfTeX error: ", the # message, and a newline. Unlike print_err, there's never # context. msg = self.__consume_line(unwrap=True)[1:].strip() msg = self.__simplify_message(msg) self.__message("error", None, msg) def __runaway(self): # Procedure runaway. Prints "\nRunaway ...\n" possibly # followed by token list (user text). Always followed by a # call to print_err, so skip lines until we see the print_err. self.__skip_line() # Skip "Runaway ...\n" if not self.__lookingat("! ") and self.__avail: # Skip token list, which is limited to one line self.__skip_line() def __bad_box(self): # Function hpack and vpack. hpack prints a warning, a # newline, then a short_display of the offending text. # Unfortunately, there's nothing indicating the end of the # offending text, but it should be on one (possible wrapped) # line. vpack prints a warning and then, *unless output is # active*, a newline. The missing newline is probably a bug, # but it sure makes our lives harder. origpos = self.__pos msg = self.__consume_line() m = re.search( r" in (?:paragraph|alignment) at lines ([0-9]+)--([0-9]+)", msg ) or re.search(r" detected at line ([0-9]+)", msg) if m: # Sometimes TeX prints crazy line ranges like "at lines # 8500--250". The lower number seems roughly sane, so use # that. I'm not sure what causes this, but it may be # related to shipout routines messing up line registers. lineno = min(int(m.group(1)), int(m.groups()[-1])) msg = msg[: m.start()] else: m = re.search(r" while \\output is active", msg) if m: lineno = None msg = msg[: m.end()] else: self.__message("warning", None, "malformed bad box message in log") return # Back up to the end of the known message text self.__pos = origpos + m.end() if self.__lookingat("\n"): # We have a newline, so consume it and look for the # offending text. self.__pos += 1 # If there is offending text, it will start with a font # name, which will start with a \. if "hbox" in msg and self.__lookingat("\\"): self.__consume_line(unwrap=True) msg = self.__simplify_message(msg) + " (page {})".format(self.__pageno) cls = msg.split(None, 1)[0].lower() self.__message("warning", lineno, msg, cls=cls) def __generic_warning(self): # Warnings produced by LaTeX's \GenericWarning (which is # called by \{Package,Class}Warning and \@latex@warning), # warnings produced by pdftex_warn, and other random warnings. msg, cls = self.__generic_info() # Most warnings include an input line emitted by \on@line m = re.search(" on input line ([0-9]+)", msg) if m: lineno = int(m.group(1)) msg = msg[: m.start()] else: lineno = None msg = self.__simplify_message(msg) self.__message("warning", lineno, msg, cls=cls) def __generic_info(self): # Messages produced by LaTeX's \Generic{Error,Warning,Info} # and things that look like them msg = self.__consume_line(unwrap=True).strip() # Package and class messages are continued with lines # containing '(package name) ' pkg_name = msg.split(" ", 2)[1] prefix = "(" + pkg_name + ") " while self.__lookingat(prefix): # Collect extra lines. It's important that we keep these # because they may contain context information like line # numbers. extra = self.__consume_line(unwrap=True) msg += " " + extra[len(prefix) :].strip() return msg, pkg_name.lower() ################################################################## # BibTeX task # class BibTeX(Task): def __init__(self, db, latex_task, cmd, cmd_args, nowarns, obj_dir): super().__init__( db, "bibtex::" + normalize_input_path(latex_task.get_tex_filename()) ) self.__latex_task = latex_task self.__cmd = cmd self.__cmd_args = cmd_args self.__obj_dir = obj_dir def stable(self): # If bibtex doesn't have its inputs, then it's stable because # it has no effect on system state. jobname = self.__latex_task.get_jobname() if jobname is None: # We don't know where the .aux file is until latex has run return True if not os.path.exists(jobname + ".aux"): # Input isn't ready, so bibtex will simply fail without # affecting system state. Hence, this task is trivially # stable. return True if not self.__find_bib_cmds(os.path.dirname(jobname), jobname + ".aux"): # The tex file doesn't refer to any bibliographic data, so # don't run bibtex. return True return super().stable() def __find_bib_cmds(self, basedir, auxname, stack=()): debug("scanning for bib commands in {}".format(auxname)) if auxname in stack: raise TaskError(".aux file loop") stack = stack + (auxname,) try: aux_data = open(auxname, errors="surrogateescape").read() except FileNotFoundError: # The aux file may not exist if latex aborted return False if re.search(r"^\\bibstyle\{", aux_data, flags=re.M) or re.search( r"^\\bibdata\{", aux_data, flags=re.M ): return True if re.search(r"^\\abx@aux@cite\{", aux_data, flags=re.M): # biber citation return True # Recurse into included aux files (see aux_input_command), in # case \bibliography appears in an \included file. for m in re.finditer(r"^\\@input\{([^}]*)\}", aux_data, flags=re.M): if self.__find_bib_cmds(basedir, os.path.join(basedir, m.group(1)), stack): return True return False def _input_args(self): if self.__is_biber(): aux_name = os.path.basename(self.__latex_task.get_jobname()) else: aux_name = os.path.basename(self.__latex_task.get_jobname()) + ".aux" return [self.__cmd] + self.__cmd_args + [aux_name] def _input_cwd(self): return os.path.dirname(self.__latex_task.get_jobname()) def _input_auxfile(self, auxname): # We don't consider the .aux files regular inputs. # Instead, we extract just the bit that BibTeX cares about # and depend on that. See get_aux_command_and_process in # bibtex.web. debug("hashing filtered aux file {}", auxname) try: with open(auxname, "rb") as aux: h = hashlib.sha256() for line in aux: if line.startswith( ( b"\\citation{", b"\\bibdata{", b"\\bibstyle{", b"\\@input{", b"\\abx@aux@cite{", ) ): h.update(line) return h.hexdigest() except FileNotFoundError: debug("{} does not exist", auxname) return None def __path_join(self, first, rest): if rest is None: # Append ':' to keep the default search path return first + ":" return first + ":" + rest def __is_biber(self): return "biber" in self.__cmd def _execute(self): # This gets complicated when \include is involved. \include # switches to a different aux file and records its path in the # main aux file. However, BibTeX does not consider this path # to be relative to the location of the main aux file, so we # have to run BibTeX *in the output directory* for it to # follow these includes (there's no way to tell BibTeX other # locations to search). Unfortunately, this means BibTeX will # no longer be able to find local bib or bst files, but so we # tell it where to look by setting BIBINPUTS and BSTINPUTS # (luckily we can control this search). We have to pass this # same environment down to Kpathsea when we resolve the paths # in BibTeX's log. args, cwd = self._input("args"), self._input("cwd") debug("running {} in {}", args, cwd) env = os.environ.copy() env["BIBINPUTS"] = self.__path_join(os.getcwd(), env.get("BIBINPUTS")) env["BSTINPUTS"] = self.__path_join(os.getcwd(), env.get("BSTINPUTS")) try: verbose_cmd(args, cwd, env) p = subprocess.Popen( args, cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) stdout = self.__feed_terminal(p.stdout) status = p.wait() except OSError as e: raise TaskError("failed to execute bibtex task: " + str(e)) from e inputs, auxnames, outbase = self.__parse_inputs(stdout, cwd, env) if not inputs and not auxnames: # BibTeX failed catastrophically. print(stdout, file=sys.stderr) raise TaskError("failed to execute bibtex task") # Register environment variable inputs for env_var in ["TEXMFOUTPUT", "BSTINPUTS", "BIBINPUTS", "PATH"]: self._input("env", env_var) # Register file inputs for path in auxnames: self._input("auxfile", path) for path in inputs: self._input("file", path) if self.__is_biber(): outbase = os.path.join(cwd, outbase) outputs = [outbase + ".bbl", outbase + ".blg"] return RunResult( outputs, {"outbase": outbase, "status": status, "inputs": inputs} ) def __feed_terminal(self, stdout): with Progress("bibtex") as progress: buf, linebuf = [], "" while True: data = os.read(stdout.fileno(), 4096) if not data: break # See "A note about encoding" above data = data.decode("ascii", errors="surrogateescape") buf.append(data) linebuf += data while "\n" in linebuf: line, _, linebuf = linebuf.partition("\n") if line.startswith("Database file"): progress.update(line.split(": ", 1)[1]) return "".join(buf) def __parse_inputs(self, log, cwd, env): # BibTeX conveniently logs every file that it opens, and its # log is actually sensible (see calls to a_open_in in # bibtex.web.) The only trick is that these file names are # pre-kpathsea lookup and may be relative to the directory we # ran BibTeX in. # # Because BibTeX actually depends on very little in the .aux # file (and it's likely other things will change in the .aux # file), we don't count the whole .aux file as an input, but # instead depend only on the lines that matter to BibTeX. kpathsea = Kpathsea("bibtex") inputs = [] auxnames = [] outbase = None for line in log.splitlines(): m = re.match( "(?:The top-level auxiliary file:" "|A level-[0-9]+ auxiliary file:) (.*)", line, ) if m: auxnames.append(os.path.join(cwd, m.group(1))) continue m = re.match("(?:(The style file:)|(Database file #[0-9]+:)) (.*)", line) if m: filename = m.group(3) if m.group(1): filename = kpathsea.find_file(filename, "bst", cwd, env) elif m.group(2): filename = kpathsea.find_file(filename, "bib", cwd, env) # If this path is relative to the source directory, # clean it up for error reporting and portability of # the dependency DB if filename.startswith("/"): relname = os.path.relpath(filename) if "../" not in relname: filename = relname inputs.append(filename) # biber output m = re.search("Found BibTeX data source '(.*?)'", line) if m: filename = m.group(1) inputs.append(filename) m = re.search("Logfile is '(.*?)'", line) if m: outbase = m.group(1)[:-4] if outbase is None: outbase = auxnames[0][:-4] return inputs, auxnames, outbase def report(self): extra = self._get_result_extra() if extra is None: return 0 # Parse and pretty-print the log log = open(extra["outbase"] + ".blg", "rt").read() inputs = extra["inputs"] for msg in BibTeXFilter(log, inputs).get_messages(): msg.emit() # BibTeX exits with 1 if there are warnings, 2 if there are # errors, and 3 if there are fatal errors (sysdep.h). # Translate to a normal UNIX exit status. if extra["status"] >= 2: return 1 return 0 class BibTeXFilter: def __init__(self, data, inputs): self.__inputs = inputs self.__key_locs = None self.__messages = [] prev_line = "" for line in data.splitlines(): msg = self.__process_line(prev_line, line) if msg is not None: self.__messages.append(Message(*msg)) prev_line = line def get_messages(self): """Return a list of warning and error Messages.""" # BibTeX reports most errors in no particular order. Sort by # file and line. return sorted( self.__messages, key=lambda msg: (msg.filename or "", msg.lineno or 0) ) def __process_line(self, prev_line, line): m = None def match(regexp): nonlocal m m = re.match(regexp, line) return m # BibTeX has many error paths, but luckily the set is closed, # so we can find all of them. This first case is the # workhorse format. # # AUX errors: aux_err/aux_err_return/aux_err_print # # BST errors: bst_ln_num_print/bst_err/ # bst_err_print_and_look_for_blank_line_return/ # bst_warn_print/bst_warn/ # skip_token/skip_token_print/ # bst_ext_warn/bst_ext_warn_print/ # bst_ex_warn/bst_ex_warn_print/ # bst_mild_ex_warn/bst_mild_ex_warn_print/ # bst_string_size_exceeded # # BIB errors: bib_ln_num_print/ # bib_err_print/bib_err/ # bib_warn_print/bib_warn/ # bib_one_of_two_expected_err/macro_name_warning/ if match("(.*?)---?line ([0-9]+) of file (.*)"): # Sometimes the real error is printed on the previous line if m.group(1) == "while executing": # bst_ex_warn. The real message is on the previous line text = prev_line else: text = m.group(1) or prev_line typ, msg = self.__canonicalize(text) return (typ, m.group(3), int(m.group(2)), msg) # overflow/print_overflow if match("Sorry---you've exceeded BibTeX's (.*)"): return ("error", None, None, "capacity exceeded: " + m.group(1)) # confusion/print_confusion if match("(.*)---this can't happen$"): return ("error", None, None, "internal error: " + m.group(1)) # aux_end_err if match("I found (no .*)---while reading file (.*)"): return ("error", m.group(2), None, m.group(1)) # bad_cross_reference_print/ # nonexistent_cross_reference_error/ # @<Complain about a nested cross reference@> # # This is split across two lines. Match the second. if match('^refers to entry "'): typ, msg = self.__canonicalize(prev_line + " " + line) msg = re.sub("^a (bad cross reference)", "\\1", msg) # Try to give this key a location filename = lineno = None m2 = re.search(r'--entry "[^"]"', prev_line) if m2: filename, lineno = self.__find_key(m2.group(1)) return (typ, filename, lineno, msg) # print_missing_entry if match('Warning--I didn\'t find a database entry for (".*")'): return ("warning", None, None, "no database entry for " + m.group(1)) # x_warning if match("Warning--(.*)"): # Most formats give warnings about "something in <key>". # Try to match it up. filename = lineno = None for m2 in reversed(list(re.finditer(r" in ([^, \t\n]+)\b", line))): if m2: filename, lineno = self.__find_key(m2.group(1)) if filename: break return ("warning", filename, lineno, m.group(1)) # @<Clean up and leave@> if match("Aborted at line ([0-9]+) of file (.*)"): return ("info", m.group(2), int(m.group(1)), "aborted") # biber type errors if match("^.*> WARN - (.*)$"): print("warning", None, None, m.group(1)) m2 = re.match("(.*) in file '(.*?)', skipping ...", m.group(1)) if m2: return ("warning", m2.group(2), "0", m2.group(1)) return ("warning", None, None, m.group(1)) if match("^.*> ERROR - (.*)$"): m2 = re.match("BibTeX subsystem: (.*?), line (\d+), (.*)$", m.group(1)) if m2: return ("error", m2.group(1), m2.group(2), m2.group(3)) return ("error", None, None, m.group(1)) def __canonicalize(self, msg): if msg.startswith("Warning"): msg = re.sub("^Warning-*", "", msg) typ = "warning" else: typ = "error" msg = re.sub("^I('m| was)? ", "", msg) msg = msg[:1].lower() + msg[1:] return typ, msg def __find_key(self, key): if self.__key_locs is None: p = BibTeXKeyParser() self.__key_locs = {} for filename in self.__inputs: data = open(filename, "rt", errors="surrogateescape").read() for pkey, lineno in p.parse(data): self.__key_locs.setdefault(pkey, (filename, lineno)) return self.__key_locs.get(key, (None, None)) class BibTeXKeyParser: """Just enough of a BibTeX parser to find keys.""" def parse(self, data): IDENT_RE = "(?![0-9])([^\x00-\x20\x80-\xff \t\"#%'(),={}]+)" self.__pos, self.__data = 0, data # Find the next entry while self.__consume("[^@]*@[ \t\n]*"): # What type of entry? if not self.__consume(IDENT_RE + "[ \t\n]*"): continue typ = self.__m.group(1) if typ == "comment": continue start = self.__pos if not self.__consume("([{(])[ \t\n]*"): continue closing, key_re = {"{": ("}", "([^, \t\n}]*)"), "(": (")", "([^, \t\n]*)")}[ self.__m.group(1) ] if typ not in ("preamble", "string"): # Regular entry; get key if self.__consume(key_re): yield self.__m.group(1), self.__lineno() # Consume body of entry self.__pos = start self.__balanced(closing) def __consume(self, regexp): self.__m = re.compile(regexp).match(self.__data, self.__pos) if self.__m: self.__pos = self.__m.end() return self.__m def __lineno(self): return self.__data.count("\n", 0, self.__pos) + 1 def __balanced(self, closing): self.__pos += 1 level = 0 skip = re.compile("[{}" + closing + "]") while True: m = skip.search(self.__data, self.__pos) if not m: break self.__pos = m.end() ch = m.group(0) if level == 0 and ch == closing: break elif ch == "{": level += 1 elif ch == "}": level -= 1 class Kpathsea: def __init__(self, program_name): self.__progname = program_name def find_file(self, name, format, cwd=None, env=None): """Return the resolved path of 'name' or None.""" args = ["kpsewhich", "-progname", self.__progname, "-format", format, name] try: verbose_cmd(args, cwd, env) path = subprocess.check_output( args, cwd=cwd, env=env, universal_newlines=True ).strip() except subprocess.CalledProcessError as e: if e.returncode != 1: raise return None if cwd is None: return path return os.path.join(cwd, path) if __name__ == "__main__": main()
agpl-3.0
longaccess/bigstash-python
setup.py
1
2160
import os import versioneer versioneer.VCS = 'git' versioneer.versionfile_source = 'BigStash/version.py' versioneer.versionfile_build = 'BigStash/version.py' versioneer.tag_prefix = '' versioneer.parentdir_prefix = 'bigstash-' from setuptools import setup, find_packages def pep386adapt(version): if version is not None and '-' in version: # adapt git-describe version to be in line with PEP 386 parts = version.split('-') parts[-2] = 'post'+parts[-2] version = '.'.join(parts[:-1]) return version install_requires = [ 'six>=1.9, <2.0', 'requests>=2.5.1, <2.6', 'retrying', 'wrapt', 'boto3', 'cached_property', 'docopt', 'inflect' ] dev_requires = [ 'flake8', ] def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except IOError: return '' setup(version=pep386adapt(versioneer.get_version()), name="bigstash", description=read('DESCRIPTION'), long_description=read('README.rst'), url='http://github.com/longaccess/bigstash-python/', license='Apache', packages=find_packages(exclude=['features*', '*.t']), tests_require=['testtools'], test_suite="BigStash.t", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Information Technology', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Archiving', 'Topic :: Utilities', ], cmdclass=versioneer.get_cmdclass(), install_requires=install_requires, extras_require={ 'dev': dev_requires }, entry_points={ 'console_scripts': ['bgst=BigStash.upload:main'] } )
apache-2.0
iCHAIT/whats-fresh-api
whats_fresh/whats_fresh_api/views/vendor.py
2
3915
from django.http import (HttpResponse, HttpResponseNotFound) from django.contrib.gis.measure import D from whats_fresh.whats_fresh_api.models import Vendor from whats_fresh.whats_fresh_api.functions import get_lat_long_prox import json from .serializer import FreshSerializer def vendor_list(request): """ */vendors/* List all vendors in the database. There is no order to this list, only whatever is returned by the database. """ error = { 'status': False, 'name': None, 'text': None, 'level': None, 'debug': None } data = {} point, proximity, limit, error = get_lat_long_prox(request, error) if point: vendor_list = Vendor.objects.filter( location__distance_lte=(point, D(mi=proximity)))[:limit] else: vendor_list = Vendor.objects.all()[:limit] if not vendor_list: error = { "status": True, "name": "No Vendors", "text": "No Vendors found", "level": "Information", "debug": "" } serializer = FreshSerializer() data = { "vendors": json.loads(serializer.serialize(vendor_list)), "error": error } return HttpResponse(json.dumps(data), content_type="application/json") def vendors_products(request, id=None): """ */vendors/products/<id>* List all vendors in the database that sell product <id>. There is no order to this list, only whatever is returned by the database. """ error = { 'status': False, 'name': None, 'text': None, 'level': None, 'debug': None } data = {} point, proximity, limit, error = get_lat_long_prox(request, error) try: if point: vendor_list = Vendor.objects.filter( vendorproduct__product_preparation__product__id__exact=id, location__distance_lte=(point, D(mi=proximity)))[:limit] else: vendor_list = Vendor.objects.filter( vendorproduct__product_preparation__product__id__exact=id )[:limit] except Exception as e: error = { 'status': True, 'name': 'Invalid product', 'text': 'Product id is invalid', 'level': 'Error', 'debug': "{0}: {1}".format(type(e).__name__, str(e)) } return HttpResponseNotFound( json.dumps(data), content_type="application/json" ) if not vendor_list: error = { "status": True, "name": "No Vendors", "text": "No Vendors found for product %s" % id, "level": "Information", "debug": "" } serializer = FreshSerializer() data = { "vendors": json.loads(serializer.serialize(vendor_list)), "error": error } return HttpResponse(json.dumps(data), content_type="application/json") def vendor_details(request, id=None): """ */vendors/<id>* Returns the vendor data for vendor <id>. """ data = {} error = { 'status': False, 'name': None, 'text': None, 'level': None, 'debug': None } try: vendor = Vendor.objects.get(id=id) except Exception as e: data['error'] = { 'status': True, 'name': 'Vendor Not Found', 'text': 'Vendor id %s was not found.' % id, 'level': 'Error', 'debug': "{0}: {1}".format(type(e).__name__, str(e)) } return HttpResponseNotFound( json.dumps(data), content_type="application/json" ) serializer = FreshSerializer() data = json.loads(serializer.serialize(vendor)) data['error'] = error return HttpResponse(json.dumps(data), content_type="application/json")
apache-2.0
eusi/MissionPlanerHM
Lib/site-packages/numpy/oldnumeric/mlab.py
77
3459
# This module is for compatibility only. All functions are defined elsewhere. __all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] import numpy.oldnumeric.linear_algebra as LinearAlgebra import numpy.oldnumeric.random_array as RandomArray from numpy import tril, trapz as _Ntrapz, hanning, rot90, triu, diff, \ angle, roots, ptp as _Nptp, kaiser, cumprod as _Ncumprod, \ diag, msort, prod as _Nprod, std as _Nstd, hamming, flipud, \ amax as _Nmax, amin as _Nmin, blackman, bartlett, \ squeeze, sinc, median, fliplr, mean as _Nmean, transpose from numpy.linalg import eig, svd from numpy.random import rand, randn import numpy as np from typeconv import convtypecode def eye(N, M=None, k=0, typecode=None, dtype=None): """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, and everything else is zeros. """ dtype = convtypecode(typecode, dtype) if M is None: M = N m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) def tri(N, M=None, k=0, typecode=None, dtype=None): """ returns a N-by-M array where all the diagonals starting from lower left corner up to the k-th are all ones. """ dtype = convtypecode(typecode, dtype) if M is None: M = N m = np.greater_equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) def trapz(y, x=None, axis=-1): return _Ntrapz(y, x, axis=axis) def ptp(x, axis=0): return _Nptp(x, axis) def cumprod(x, axis=0): return _Ncumprod(x, axis) def max(x, axis=0): return _Nmax(x, axis) def min(x, axis=0): return _Nmin(x, axis) def prod(x, axis=0): return _Nprod(x, axis) def std(x, axis=0): N = asarray(x).shape[axis] return _Nstd(x, axis)*sqrt(N/(N-1.)) def mean(x, axis=0): return _Nmean(x, axis) # This is exactly the same cov function as in MLab def cov(m, y=None, rowvar=0, bias=0): if y is None: y = m else: y = y if rowvar: m = transpose(m) y = transpose(y) if (m.shape[0] == 1): m = transpose(m) if (y.shape[0] == 1): y = transpose(y) N = m.shape[0] if (y.shape[0] != N): raise ValueError, "x and y must have the same number "\ "of observations" m = m - _Nmean(m,axis=0) y = y - _Nmean(y,axis=0) if bias: fact = N*1.0 else: fact = N-1.0 return squeeze(dot(transpose(m), conjugate(y)) / fact) from numpy import sqrt, multiply def corrcoef(x, y=None): c = cov(x, y) d = diag(c) return c/sqrt(multiply.outer(d,d)) from compat import * from functions import * from precision import * from ufuncs import * from misc import * import compat import precision import functions import misc import ufuncs import numpy __version__ = numpy.__version__ del numpy __all__ += ['__version__'] __all__ += compat.__all__ __all__ += precision.__all__ __all__ += functions.__all__ __all__ += ufuncs.__all__ __all__ += misc.__all__ del compat del functions del precision del ufuncs del misc
gpl-3.0
chrsrds/scikit-learn
doc/tutorial/text_analytics/data/languages/fetch_data.py
33
3758
# simple python script to collect text paragraphs from various languages on the # same topic namely the Wikipedia encyclopedia itself import os from urllib.request import Request, build_opener import lxml.html from lxml.etree import ElementTree import numpy as np import codecs pages = { 'ar': 'http://ar.wikipedia.org/wiki/%D9%88%D9%8A%D9%83%D9%8A%D8%A8%D9%8A%D8%AF%D9%8A%D8%A7', # noqa: E501 'de': 'http://de.wikipedia.org/wiki/Wikipedia', 'en': 'https://en.wikipedia.org/wiki/Wikipedia', 'es': 'http://es.wikipedia.org/wiki/Wikipedia', 'fr': 'http://fr.wikipedia.org/wiki/Wikip%C3%A9dia', 'it': 'http://it.wikipedia.org/wiki/Wikipedia', 'ja': 'http://ja.wikipedia.org/wiki/Wikipedia', 'nl': 'http://nl.wikipedia.org/wiki/Wikipedia', 'pl': 'http://pl.wikipedia.org/wiki/Wikipedia', 'pt': 'http://pt.wikipedia.org/wiki/Wikip%C3%A9dia', 'ru': 'http://ru.wikipedia.org/wiki/%D0%92%D0%B8%D0%BA%D0%B8%D0%BF%D0%B5%D0%B4%D0%B8%D1%8F', # noqa: E501 # u'zh': u'http://zh.wikipedia.org/wiki/Wikipedia', } html_folder = 'html' text_folder = 'paragraphs' short_text_folder = 'short_paragraphs' n_words_per_short_text = 5 if not os.path.exists(html_folder): os.makedirs(html_folder) for lang, page in pages.items(): text_lang_folder = os.path.join(text_folder, lang) if not os.path.exists(text_lang_folder): os.makedirs(text_lang_folder) short_text_lang_folder = os.path.join(short_text_folder, lang) if not os.path.exists(short_text_lang_folder): os.makedirs(short_text_lang_folder) opener = build_opener() html_filename = os.path.join(html_folder, lang + '.html') if not os.path.exists(html_filename): print("Downloading %s" % page) request = Request(page) # change the User Agent to avoid being blocked by Wikipedia # downloading a couple of articles should not be considered abusive request.add_header('User-Agent', 'OpenAnything/1.0') html_content = opener.open(request).read() open(html_filename, 'wb').write(html_content) # decode the payload explicitly as UTF-8 since lxml is confused for some # reason with codecs.open(html_filename,'r','utf-8') as html_file: html_content = html_file.read() tree = ElementTree(lxml.html.document_fromstring(html_content)) i = 0 j = 0 for p in tree.findall('//p'): content = p.text_content() if len(content) < 100: # skip paragraphs that are too short - probably too noisy and not # representative of the actual language continue text_filename = os.path.join(text_lang_folder, '%s_%04d.txt' % (lang, i)) print("Writing %s" % text_filename) open(text_filename, 'wb').write(content.encode('utf-8', 'ignore')) i += 1 # split the paragraph into fake smaller paragraphs to make the # problem harder e.g. more similar to tweets if lang in ('zh', 'ja'): # FIXME: whitespace tokenizing does not work on chinese and japanese continue words = content.split() n_groups = len(words) / n_words_per_short_text if n_groups < 1: continue groups = np.array_split(words, n_groups) for group in groups: small_content = " ".join(group) short_text_filename = os.path.join(short_text_lang_folder, '%s_%04d.txt' % (lang, j)) print("Writing %s" % short_text_filename) open(short_text_filename, 'wb').write( small_content.encode('utf-8', 'ignore')) j += 1 if j >= 1000: break
bsd-3-clause
tysonholub/twilio-python
twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py
1
12851
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import serialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.page import Page class WorkersCumulativeStatisticsList(ListResource): """ """ def __init__(self, version, workspace_sid): """ Initialize the WorkersCumulativeStatisticsList :param Version version: Version that contains the resource :param workspace_sid: The SID of the Workspace that contains the Workers :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList """ super(WorkersCumulativeStatisticsList, self).__init__(version) # Path Solution self._solution = {'workspace_sid': workspace_sid, } def get(self): """ Constructs a WorkersCumulativeStatisticsContext :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext """ return WorkersCumulativeStatisticsContext( self._version, workspace_sid=self._solution['workspace_sid'], ) def __call__(self): """ Constructs a WorkersCumulativeStatisticsContext :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext """ return WorkersCumulativeStatisticsContext( self._version, workspace_sid=self._solution['workspace_sid'], ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Taskrouter.V1.WorkersCumulativeStatisticsList>' class WorkersCumulativeStatisticsPage(Page): """ """ def __init__(self, version, response, solution): """ Initialize the WorkersCumulativeStatisticsPage :param Version version: Version that contains the resource :param Response response: Response from the API :param workspace_sid: The SID of the Workspace that contains the Workers :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsPage :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsPage """ super(WorkersCumulativeStatisticsPage, self).__init__(version, response) # Path Solution self._solution = solution def get_instance(self, payload): """ Build an instance of WorkersCumulativeStatisticsInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance """ return WorkersCumulativeStatisticsInstance( self._version, payload, workspace_sid=self._solution['workspace_sid'], ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Taskrouter.V1.WorkersCumulativeStatisticsPage>' class WorkersCumulativeStatisticsContext(InstanceContext): """ """ def __init__(self, version, workspace_sid): """ Initialize the WorkersCumulativeStatisticsContext :param Version version: Version that contains the resource :param workspace_sid: The SID of the Workspace with the resource to fetch :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext """ super(WorkersCumulativeStatisticsContext, self).__init__(version) # Path Solution self._solution = {'workspace_sid': workspace_sid, } self._uri = '/Workspaces/{workspace_sid}/Workers/CumulativeStatistics'.format(**self._solution) def fetch(self, end_date=values.unset, minutes=values.unset, start_date=values.unset, task_channel=values.unset): """ Fetch a WorkersCumulativeStatisticsInstance :param datetime end_date: Only calculate statistics from on or before this date :param unicode minutes: Only calculate statistics since this many minutes in the past :param datetime start_date: Only calculate statistics from on or after this date :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel :returns: Fetched WorkersCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance """ params = values.of({ 'EndDate': serialize.iso8601_datetime(end_date), 'Minutes': minutes, 'StartDate': serialize.iso8601_datetime(start_date), 'TaskChannel': task_channel, }) payload = self._version.fetch( 'GET', self._uri, params=params, ) return WorkersCumulativeStatisticsInstance( self._version, payload, workspace_sid=self._solution['workspace_sid'], ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Taskrouter.V1.WorkersCumulativeStatisticsContext {}>'.format(context) class WorkersCumulativeStatisticsInstance(InstanceResource): """ """ def __init__(self, version, payload, workspace_sid): """ Initialize the WorkersCumulativeStatisticsInstance :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance """ super(WorkersCumulativeStatisticsInstance, self).__init__(version) # Marshaled Properties self._properties = { 'account_sid': payload.get('account_sid'), 'start_time': deserialize.iso8601_datetime(payload.get('start_time')), 'end_time': deserialize.iso8601_datetime(payload.get('end_time')), 'activity_durations': payload.get('activity_durations'), 'reservations_created': deserialize.integer(payload.get('reservations_created')), 'reservations_accepted': deserialize.integer(payload.get('reservations_accepted')), 'reservations_rejected': deserialize.integer(payload.get('reservations_rejected')), 'reservations_timed_out': deserialize.integer(payload.get('reservations_timed_out')), 'reservations_canceled': deserialize.integer(payload.get('reservations_canceled')), 'reservations_rescinded': deserialize.integer(payload.get('reservations_rescinded')), 'workspace_sid': payload.get('workspace_sid'), 'url': payload.get('url'), } # Context self._context = None self._solution = {'workspace_sid': workspace_sid, } @property def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext """ if self._context is None: self._context = WorkersCumulativeStatisticsContext( self._version, workspace_sid=self._solution['workspace_sid'], ) return self._context @property def account_sid(self): """ :returns: The SID of the Account that created the resource :rtype: unicode """ return self._properties['account_sid'] @property def start_time(self): """ :returns: The beginning of the interval during which these statistics were calculated :rtype: datetime """ return self._properties['start_time'] @property def end_time(self): """ :returns: The end of the interval during which these statistics were calculated :rtype: datetime """ return self._properties['end_time'] @property def activity_durations(self): """ :returns: The minimum, average, maximum, and total time that Workers spent in each Activity :rtype: dict """ return self._properties['activity_durations'] @property def reservations_created(self): """ :returns: The total number of Reservations that were created :rtype: unicode """ return self._properties['reservations_created'] @property def reservations_accepted(self): """ :returns: The total number of Reservations that were accepted :rtype: unicode """ return self._properties['reservations_accepted'] @property def reservations_rejected(self): """ :returns: The total number of Reservations that were rejected :rtype: unicode """ return self._properties['reservations_rejected'] @property def reservations_timed_out(self): """ :returns: The total number of Reservations that were timed out :rtype: unicode """ return self._properties['reservations_timed_out'] @property def reservations_canceled(self): """ :returns: The total number of Reservations that were canceled :rtype: unicode """ return self._properties['reservations_canceled'] @property def reservations_rescinded(self): """ :returns: The total number of Reservations that were rescinded :rtype: unicode """ return self._properties['reservations_rescinded'] @property def workspace_sid(self): """ :returns: The SID of the Workspace that contains the Workers :rtype: unicode """ return self._properties['workspace_sid'] @property def url(self): """ :returns: The absolute URL of the Workers statistics resource :rtype: unicode """ return self._properties['url'] def fetch(self, end_date=values.unset, minutes=values.unset, start_date=values.unset, task_channel=values.unset): """ Fetch a WorkersCumulativeStatisticsInstance :param datetime end_date: Only calculate statistics from on or before this date :param unicode minutes: Only calculate statistics since this many minutes in the past :param datetime start_date: Only calculate statistics from on or after this date :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel :returns: Fetched WorkersCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance """ return self._proxy.fetch( end_date=end_date, minutes=minutes, start_date=start_date, task_channel=task_channel, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Taskrouter.V1.WorkersCumulativeStatisticsInstance {}>'.format(context)
mit
phire/fifoci
frontend/fifoci/models.py
1
1895
# This file is part of the FifoCI project. # Copyright (c) 2014 Pierre Bourdon <delroth@dolphin-emu.org> # Licensing information: see $REPO_ROOT/LICENSE from django.db import models class FifoTest(models.Model): file = models.FileField(upload_to="dff/", max_length=256) name = models.CharField(max_length=128) shortname = models.CharField(max_length=32, db_index=True) active = models.BooleanField(default=True, db_index=True) description = models.TextField(blank=True) @models.permalink def get_absolute_url(self): return ('dff-view', [self.shortname]) def __str__(self): return self.shortname class Version(models.Model): hash = models.CharField(max_length=40, db_index=True) name = models.CharField(max_length=64, db_index=True) parent = models.ForeignKey('self', null=True, blank=True, db_index=True) parent_hash = models.CharField(max_length=40) submitted = models.BooleanField(default=False, db_index=True) ts = models.DateTimeField(auto_now_add=True, blank=True, db_index=True) @models.permalink def get_absolute_url(self): return ('version-view', [self.hash]) def __str__(self): return '%s (%s)' % (self.name, self.hash[:8]) class Result(models.Model): dff = models.ForeignKey(FifoTest) ver = models.ForeignKey(Version, related_name='results') type = models.CharField(max_length=64, db_index=True) has_change = models.BooleanField(default=False, db_index=True) first_result = models.BooleanField(default=False, db_index=True) # Format: "h1,h2,h3,...,hN" hashes = models.TextField() @models.permalink def get_absolute_url(self): return ('result-view', [self.id]) @property def hashes_list(self): return self.hashes.split(',') def __str__(self): return '%s / %s / %s' % (self.dff, self.ver, self.type)
bsd-2-clause
Gateworks/platform-external-chromium_org
tools/deep_memory_profiler/lib/dump.py
23
15351
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import copy import datetime import logging import os import re import time from lib.bucket import BUCKET_ID from lib.exceptions import EmptyDumpException, InvalidDumpException from lib.exceptions import ObsoleteDumpVersionException, ParsingException from lib.pageframe import PageFrame from lib.range_dict import ExclusiveRangeDict from lib.symbol import procfs LOGGER = logging.getLogger('dmprof') # Heap Profile Dump versions # DUMP_DEEP_[1-4] are obsolete. # DUMP_DEEP_2+ distinct mmap regions and malloc chunks. # DUMP_DEEP_3+ don't include allocation functions in their stack dumps. # DUMP_DEEP_4+ support comments with '#' and global stats "nonprofiled-*". # DUMP_DEEP_[1-2] should be processed by POLICY_DEEP_1. # DUMP_DEEP_[3-4] should be processed by POLICY_DEEP_2 or POLICY_DEEP_3. DUMP_DEEP_1 = 'DUMP_DEEP_1' DUMP_DEEP_2 = 'DUMP_DEEP_2' DUMP_DEEP_3 = 'DUMP_DEEP_3' DUMP_DEEP_4 = 'DUMP_DEEP_4' DUMP_DEEP_OBSOLETE = (DUMP_DEEP_1, DUMP_DEEP_2, DUMP_DEEP_3, DUMP_DEEP_4) # DUMP_DEEP_5 doesn't separate sections for malloc and mmap. # malloc and mmap are identified in bucket files. # DUMP_DEEP_5 should be processed by POLICY_DEEP_4. DUMP_DEEP_5 = 'DUMP_DEEP_5' # DUMP_DEEP_6 adds a mmap list to DUMP_DEEP_5. DUMP_DEEP_6 = 'DUMP_DEEP_6' class Dump(object): """Represents a heap profile dump.""" _PATH_PATTERN = re.compile(r'^(.*)\.([0-9]+)\.([0-9]+)\.heap$') _HOOK_PATTERN = re.compile( r'^ ([ \(])([a-f0-9]+)([ \)])-([ \(])([a-f0-9]+)([ \)])\s+' r'(hooked|unhooked)\s+(.+)$', re.IGNORECASE) _HOOKED_PATTERN = re.compile(r'(?P<TYPE>.+ )?(?P<COMMITTED>[0-9]+) / ' '(?P<RESERVED>[0-9]+) @ (?P<BUCKETID>[0-9]+)') _UNHOOKED_PATTERN = re.compile(r'(?P<TYPE>.+ )?(?P<COMMITTED>[0-9]+) / ' '(?P<RESERVED>[0-9]+)') _OLD_HOOKED_PATTERN = re.compile(r'(?P<TYPE>.+) @ (?P<BUCKETID>[0-9]+)') _OLD_UNHOOKED_PATTERN = re.compile(r'(?P<TYPE>.+) (?P<COMMITTED>[0-9]+)') _TIME_PATTERN_FORMAT = re.compile( r'^Time: ([0-9]+/[0-9]+/[0-9]+ [0-9]+:[0-9]+:[0-9]+)(\.[0-9]+)?') _TIME_PATTERN_SECONDS = re.compile(r'^Time: ([0-9]+)$') def __init__(self, path, modified_time): self._path = path matched = self._PATH_PATTERN.match(path) self._pid = int(matched.group(2)) self._count = int(matched.group(3)) self._time = modified_time self._map = {} self._procmaps = ExclusiveRangeDict(ProcMapsEntryAttribute) self._stacktrace_lines = [] self._global_stats = {} # used only in apply_policy self._run_id = '' self._pagesize = 4096 self._pageframe_length = 0 self._pageframe_encoding = '' self._has_pagecount = False self._version = '' self._lines = [] @property def path(self): return self._path @property def count(self): return self._count @property def time(self): return self._time @property def iter_map(self): for region in sorted(self._map.iteritems()): yield region[0], region[1] def iter_procmaps(self): for begin, end, attr in self._map.iter_range(): yield begin, end, attr @property def iter_stacktrace(self): for line in self._stacktrace_lines: yield line def global_stat(self, name): return self._global_stats[name] @property def run_id(self): return self._run_id @property def pagesize(self): return self._pagesize @property def pageframe_length(self): return self._pageframe_length @property def pageframe_encoding(self): return self._pageframe_encoding @property def has_pagecount(self): return self._has_pagecount @staticmethod def load(path, log_header='Loading a heap profile dump: '): """Loads a heap profile dump. Args: path: A file path string to load. log_header: A preceding string for log messages. Returns: A loaded Dump object. Raises: ParsingException for invalid heap profile dumps. """ dump = Dump(path, os.stat(path).st_mtime) with open(path, 'r') as f: dump.load_file(f, log_header) return dump def load_file(self, f, log_header): self._lines = [line for line in f if line and not line.startswith('#')] try: self._version, ln = self._parse_version() self._parse_meta_information() if self._version == DUMP_DEEP_6: self._parse_mmap_list() self._parse_global_stats() self._extract_stacktrace_lines(ln) except EmptyDumpException: LOGGER.info('%s%s ...ignored an empty dump.' % (log_header, self._path)) except ParsingException, e: LOGGER.error('%s%s ...error %s' % (log_header, self._path, e)) raise else: LOGGER.info('%s%s (version:%s)' % (log_header, self._path, self._version)) def _parse_version(self): """Parses a version string in self._lines. Returns: A pair of (a string representing a version of the stacktrace dump, and an integer indicating a line number next to the version string). Raises: ParsingException for invalid dump versions. """ version = '' # Skip until an identifiable line. headers = ('STACKTRACES:\n', 'MMAP_STACKTRACES:\n', 'heap profile: ') if not self._lines: raise EmptyDumpException('Empty heap dump file.') (ln, found) = skip_while( 0, len(self._lines), lambda n: not self._lines[n].startswith(headers)) if not found: raise InvalidDumpException('No version header.') # Identify a version. if self._lines[ln].startswith('heap profile: '): version = self._lines[ln][13:].strip() if version in (DUMP_DEEP_5, DUMP_DEEP_6): (ln, _) = skip_while( ln, len(self._lines), lambda n: self._lines[n] != 'STACKTRACES:\n') elif version in DUMP_DEEP_OBSOLETE: raise ObsoleteDumpVersionException(version) else: raise InvalidDumpException('Invalid version: %s' % version) elif self._lines[ln] == 'STACKTRACES:\n': raise ObsoleteDumpVersionException(DUMP_DEEP_1) elif self._lines[ln] == 'MMAP_STACKTRACES:\n': raise ObsoleteDumpVersionException(DUMP_DEEP_2) return (version, ln) def _parse_global_stats(self): """Parses lines in self._lines as global stats.""" (ln, _) = skip_while( 0, len(self._lines), lambda n: self._lines[n] != 'GLOBAL_STATS:\n') global_stat_names = [ 'total', 'absent', 'file-exec', 'file-nonexec', 'anonymous', 'stack', 'other', 'nonprofiled-absent', 'nonprofiled-anonymous', 'nonprofiled-file-exec', 'nonprofiled-file-nonexec', 'nonprofiled-stack', 'nonprofiled-other', 'profiled-mmap', 'profiled-malloc'] for prefix in global_stat_names: (ln, _) = skip_while( ln, len(self._lines), lambda n: self._lines[n].split()[0] != prefix) words = self._lines[ln].split() self._global_stats[prefix + '_virtual'] = int(words[-2]) self._global_stats[prefix + '_committed'] = int(words[-1]) def _parse_meta_information(self): """Parses lines in self._lines for meta information.""" (ln, found) = skip_while( 0, len(self._lines), lambda n: self._lines[n] != 'META:\n') if not found: return ln += 1 while True: if self._lines[ln].startswith('Time:'): matched_seconds = self._TIME_PATTERN_SECONDS.match(self._lines[ln]) matched_format = self._TIME_PATTERN_FORMAT.match(self._lines[ln]) if matched_format: self._time = time.mktime(datetime.datetime.strptime( matched_format.group(1), '%Y/%m/%d %H:%M:%S').timetuple()) if matched_format.group(2): self._time += float(matched_format.group(2)[1:]) / 1000.0 elif matched_seconds: self._time = float(matched_seconds.group(1)) elif self._lines[ln].startswith('Reason:'): pass # Nothing to do for 'Reason:' elif self._lines[ln].startswith('PageSize: '): self._pagesize = int(self._lines[ln][10:]) elif self._lines[ln].startswith('CommandLine:'): pass elif (self._lines[ln].startswith('PageFrame: ') or self._lines[ln].startswith('PFN: ')): if self._lines[ln].startswith('PageFrame: '): words = self._lines[ln][11:].split(',') else: words = self._lines[ln][5:].split(',') for word in words: if word == '24': self._pageframe_length = 24 elif word == 'Base64': self._pageframe_encoding = 'base64' elif word == 'PageCount': self._has_pagecount = True elif self._lines[ln].startswith('RunID: '): self._run_id = self._lines[ln][7:].strip() elif (self._lines[ln].startswith('MMAP_LIST:') or self._lines[ln].startswith('GLOBAL_STATS:')): # Skip until "MMAP_LIST:" or "GLOBAL_STATS" is found. break else: pass ln += 1 def _parse_mmap_list(self): """Parses lines in self._lines as a mmap list.""" (ln, found) = skip_while( 0, len(self._lines), lambda n: self._lines[n] != 'MMAP_LIST:\n') if not found: return {} ln += 1 self._map = {} current_vma = {} pageframe_list = [] while True: entry = procfs.ProcMaps.parse_line(self._lines[ln]) if entry: current_vma = {} for _, _, attr in self._procmaps.iter_range(entry.begin, entry.end): for key, value in entry.as_dict().iteritems(): attr[key] = value current_vma[key] = value ln += 1 continue if self._lines[ln].startswith(' PF: '): for pageframe in self._lines[ln][5:].split(): pageframe_list.append(PageFrame.parse(pageframe, self._pagesize)) ln += 1 continue matched = self._HOOK_PATTERN.match(self._lines[ln]) if not matched: break # 2: starting address # 5: end address # 7: hooked or unhooked # 8: additional information if matched.group(7) == 'hooked': submatched = self._HOOKED_PATTERN.match(matched.group(8)) if not submatched: submatched = self._OLD_HOOKED_PATTERN.match(matched.group(8)) elif matched.group(7) == 'unhooked': submatched = self._UNHOOKED_PATTERN.match(matched.group(8)) if not submatched: submatched = self._OLD_UNHOOKED_PATTERN.match(matched.group(8)) else: assert matched.group(7) in ['hooked', 'unhooked'] submatched_dict = submatched.groupdict() region_info = { 'vma': current_vma } if submatched_dict.get('TYPE'): region_info['type'] = submatched_dict['TYPE'].strip() if submatched_dict.get('COMMITTED'): region_info['committed'] = int(submatched_dict['COMMITTED']) if submatched_dict.get('RESERVED'): region_info['reserved'] = int(submatched_dict['RESERVED']) if submatched_dict.get('BUCKETID'): region_info['bucket_id'] = int(submatched_dict['BUCKETID']) if matched.group(1) == '(': start = current_vma['begin'] else: start = int(matched.group(2), 16) if matched.group(4) == '(': end = current_vma['end'] else: end = int(matched.group(5), 16) if pageframe_list and pageframe_list[0].start_truncated: pageframe_list[0].set_size( pageframe_list[0].size - start % self._pagesize) if pageframe_list and pageframe_list[-1].end_truncated: pageframe_list[-1].set_size( pageframe_list[-1].size - (self._pagesize - end % self._pagesize)) region_info['pageframe'] = pageframe_list pageframe_list = [] self._map[(start, end)] = (matched.group(7), region_info) ln += 1 def _extract_stacktrace_lines(self, line_number): """Extracts the position of stacktrace lines. Valid stacktrace lines are stored into self._stacktrace_lines. Args: line_number: A line number to start parsing in lines. Raises: ParsingException for invalid dump versions. """ if self._version in (DUMP_DEEP_5, DUMP_DEEP_6): (line_number, _) = skip_while( line_number, len(self._lines), lambda n: not self._lines[n].split()[0].isdigit()) stacktrace_start = line_number (line_number, _) = skip_while( line_number, len(self._lines), lambda n: self._check_stacktrace_line(self._lines[n])) self._stacktrace_lines = self._lines[stacktrace_start:line_number] elif self._version in DUMP_DEEP_OBSOLETE: raise ObsoleteDumpVersionException(self._version) else: raise InvalidDumpException('Invalid version: %s' % self._version) @staticmethod def _check_stacktrace_line(stacktrace_line): """Checks if a given stacktrace_line is valid as stacktrace. Args: stacktrace_line: A string to be checked. Returns: True if the given stacktrace_line is valid. """ words = stacktrace_line.split() if len(words) < BUCKET_ID + 1: return False if words[BUCKET_ID - 1] != '@': return False return True class DumpList(object): """Represents a sequence of heap profile dumps.""" def __init__(self, dump_list): self._dump_list = dump_list @staticmethod def load(path_list): LOGGER.info('Loading heap dump profiles.') dump_list = [] for path in path_list: dump_list.append(Dump.load(path, ' ')) return DumpList(dump_list) def __len__(self): return len(self._dump_list) def __iter__(self): for dump in self._dump_list: yield dump def __getitem__(self, index): return self._dump_list[index] class ProcMapsEntryAttribute(ExclusiveRangeDict.RangeAttribute): """Represents an entry of /proc/maps in range_dict.ExclusiveRangeDict.""" _DUMMY_ENTRY = procfs.ProcMapsEntry( 0, # begin 0, # end '-', # readable '-', # writable '-', # executable '-', # private 0, # offset '00', # major '00', # minor 0, # inode '' # name ) def __init__(self): super(ProcMapsEntryAttribute, self).__init__() self._entry = self._DUMMY_ENTRY.as_dict() def __str__(self): return str(self._entry) def __repr__(self): return 'ProcMapsEntryAttribute' + str(self._entry) def __getitem__(self, key): return self._entry[key] def __setitem__(self, key, value): if key not in self._entry: raise KeyError(key) self._entry[key] = value def copy(self): new_entry = ProcMapsEntryAttribute() for key, value in self._entry.iteritems(): new_entry[key] = copy.deepcopy(value) return new_entry def skip_while(index, max_index, skipping_condition): """Increments |index| until |skipping_condition|(|index|) is False. Returns: A pair of an integer indicating a line number after skipped, and a boolean value which is True if found a line which skipping_condition is False for. """ while skipping_condition(index): index += 1 if index >= max_index: return index, False return index, True
bsd-3-clause
lmorchard/whuru
vendor-local/src/south/south/db/generic.py
1
44434
import re import sys from django.core.management.color import no_style from django.db import transaction, models from django.db.utils import DatabaseError from django.db.backends.util import truncate_name from django.db.backends.creation import BaseDatabaseCreation from django.db.models.fields import NOT_PROVIDED from django.dispatch import dispatcher from django.conf import settings from django.utils.datastructures import SortedDict try: from django.utils.functional import cached_property except ImportError: class cached_property(object): """ Decorator that creates converts a method with a single self argument into a property cached on the instance. """ def __init__(self, func): self.func = func def __get__(self, instance, type): res = instance.__dict__[self.func.__name__] = self.func(instance) return res from south.logger import get_logger def alias(attrname): """ Returns a function which calls 'attrname' - for function aliasing. We can't just use foo = bar, as this breaks subclassing. """ def func(self, *args, **kwds): return getattr(self, attrname)(*args, **kwds) return func def invalidate_table_constraints(func): def _cache_clear(self, table, *args, **opts): self._set_cache(table, value=INVALID) return func(self, table, *args, **opts) return _cache_clear def delete_column_constraints(func): def _column_rm(self, table, column, *args, **opts): self._set_cache(table, column, value=[]) return func(self, table, column, *args, **opts) return _column_rm def copy_column_constraints(func): def _column_cp(self, table, column_old, column_new, *args, **opts): db_name = self._get_setting('NAME') self._set_cache(table, column_new, value=self.lookup_constraint(db_name, table, column_old)) return func(self, table, column_old, column_new, *args, **opts) return _column_cp class INVALID(Exception): def __repr__(self): return 'INVALID' class DryRunError(ValueError): pass class DatabaseOperations(object): """ Generic SQL implementation of the DatabaseOperations. Some of this code comes from Django Evolution. """ alter_string_set_type = 'ALTER COLUMN %(column)s TYPE %(type)s' alter_string_set_null = 'ALTER COLUMN %(column)s DROP NOT NULL' alter_string_drop_null = 'ALTER COLUMN %(column)s SET NOT NULL' delete_check_sql = 'ALTER TABLE %(table)s DROP CONSTRAINT %(constraint)s' add_column_string = 'ALTER TABLE %s ADD COLUMN %s;' delete_unique_sql = "ALTER TABLE %s DROP CONSTRAINT %s" delete_foreign_key_sql = 'ALTER TABLE %(table)s DROP CONSTRAINT %(constraint)s' max_index_name_length = 63 drop_index_string = 'DROP INDEX %(index_name)s' delete_column_string = 'ALTER TABLE %s DROP COLUMN %s CASCADE;' create_primary_key_string = "ALTER TABLE %(table)s ADD CONSTRAINT %(constraint)s PRIMARY KEY (%(columns)s)" delete_primary_key_sql = "ALTER TABLE %(table)s DROP CONSTRAINT %(constraint)s" add_check_constraint_fragment = "ADD CONSTRAINT %(constraint)s CHECK (%(check)s)" rename_table_sql = "ALTER TABLE %s RENAME TO %s;" backend_name = None default_schema_name = "public" # Features allows_combined_alters = True supports_foreign_keys = True has_check_constraints = True has_booleans = True @cached_property def has_ddl_transactions(self): """ Tests the database using feature detection to see if it has transactional DDL support. """ self._possibly_initialise() connection = self._get_connection() if hasattr(connection.features, "confirm") and not connection.features._confirmed: connection.features.confirm() # Django 1.3's MySQLdb backend doesn't raise DatabaseError exceptions = (DatabaseError, ) try: from MySQLdb import OperationalError exceptions += (OperationalError, ) except ImportError: pass # Now do the test if getattr(connection.features, 'supports_transactions', True): cursor = connection.cursor() self.start_transaction() cursor.execute('CREATE TABLE DDL_TRANSACTION_TEST (X INT)') self.rollback_transaction() try: try: cursor.execute('CREATE TABLE DDL_TRANSACTION_TEST (X INT)') except exceptions: return False else: return True finally: cursor.execute('DROP TABLE DDL_TRANSACTION_TEST') else: return False def __init__(self, db_alias): self.debug = False self.deferred_sql = [] self.dry_run = False self.pending_transactions = 0 self.pending_create_signals = [] self.db_alias = db_alias self._constraint_cache = {} self._initialised = False def lookup_constraint(self, db_name, table_name, column_name=None): """ return a set() of constraints for db_name.table_name.column_name """ def _lookup(): table = self._constraint_cache[db_name][table_name] if table is INVALID: raise INVALID elif column_name is None: return table.items() else: return table[column_name] try: ret = _lookup() return ret except INVALID: del self._constraint_cache[db_name][table_name] self._fill_constraint_cache(db_name, table_name) except KeyError: if self._is_valid_cache(db_name, table_name): return [] self._fill_constraint_cache(db_name, table_name) return self.lookup_constraint(db_name, table_name, column_name) def _set_cache(self, table_name, column_name=None, value=INVALID): db_name = self._get_setting('NAME') try: if column_name is not None: self._constraint_cache[db_name][table_name][column_name] = value else: self._constraint_cache[db_name][table_name] = value except (LookupError, TypeError): pass def _is_valid_cache(self, db_name, table_name): # we cache per-table so if the table is there it is valid try: return self._constraint_cache[db_name][table_name] is not INVALID except KeyError: return False def _is_multidb(self): try: from django.db import connections connections # Prevents "unused import" warning except ImportError: return False else: return True def _get_connection(self): """ Returns a django connection for a given DB Alias """ if self._is_multidb(): from django.db import connections return connections[self.db_alias] else: from django.db import connection return connection def _get_setting(self, setting_name): """ Allows code to get a setting (like, for example, STORAGE_ENGINE) """ setting_name = setting_name.upper() connection = self._get_connection() if self._is_multidb(): # Django 1.2 and above return connection.settings_dict[setting_name] else: # Django 1.1 and below return getattr(settings, "DATABASE_%s" % setting_name) def _has_setting(self, setting_name): """ Existence-checking version of _get_setting. """ try: self._get_setting(setting_name) except (KeyError, AttributeError): return False else: return True def _get_schema_name(self): try: return self._get_setting('schema') except (KeyError, AttributeError): return self.default_schema_name def _possibly_initialise(self): if not self._initialised: self.connection_init() self._initialised = True def connection_init(self): """ Run before any SQL to let database-specific config be sent as a command, e.g. which storage engine (MySQL) or transaction serialisability level. """ pass def quote_name(self, name): """ Uses the database backend to quote the given table/column name. """ return self._get_connection().ops.quote_name(name) def execute(self, sql, params=[]): """ Executes the given SQL statement, with optional parameters. If the instance's debug attribute is True, prints out what it executes. """ self._possibly_initialise() cursor = self._get_connection().cursor() if self.debug: print " = %s" % sql, params if self.dry_run: return [] get_logger().debug('execute "%s" with params "%s"' % (sql, params)) try: cursor.execute(sql, params) except DatabaseError, e: print >> sys.stderr, 'FATAL ERROR - The following SQL query failed: %s' % sql print >> sys.stderr, 'The error was: %s' % e raise try: return cursor.fetchall() except: return [] def execute_many(self, sql, regex=r"(?mx) ([^';]* (?:'[^']*'[^';]*)*)", comment_regex=r"(?mx) (?:^\s*$)|(?:--.*$)"): """ Takes a SQL file and executes it as many separate statements. (Some backends, such as Postgres, don't work otherwise.) """ # Be warned: This function is full of dark magic. Make sure you really # know regexes before trying to edit it. # First, strip comments sql = "\n".join([x.strip().replace("%", "%%") for x in re.split(comment_regex, sql) if x.strip()]) # Now execute each statement for st in re.split(regex, sql)[1:][::2]: self.execute(st) def add_deferred_sql(self, sql): """ Add a SQL statement to the deferred list, that won't be executed until this instance's execute_deferred_sql method is run. """ self.deferred_sql.append(sql) def execute_deferred_sql(self): """ Executes all deferred SQL, resetting the deferred_sql list """ for sql in self.deferred_sql: self.execute(sql) self.deferred_sql = [] def clear_deferred_sql(self): """ Resets the deferred_sql list to empty. """ self.deferred_sql = [] def clear_run_data(self, pending_creates = None): """ Resets variables to how they should be before a run. Used for dry runs. If you want, pass in an old panding_creates to reset to. """ self.clear_deferred_sql() self.pending_create_signals = pending_creates or [] def get_pending_creates(self): return self.pending_create_signals @invalidate_table_constraints def create_table(self, table_name, fields): """ Creates the table 'table_name'. 'fields' is a tuple of fields, each repsented by a 2-part tuple of field name and a django.db.models.fields.Field object """ if len(table_name) > 63: print " ! WARNING: You have a table name longer than 63 characters; this will not fully work on PostgreSQL or MySQL." # avoid default values in CREATE TABLE statements (#925) for field_name, field in fields: field._suppress_default = True columns = [ self.column_sql(table_name, field_name, field) for field_name, field in fields ] self.execute('CREATE TABLE %s (%s);' % ( self.quote_name(table_name), ', '.join([col for col in columns if col]), )) add_table = alias('create_table') # Alias for consistency's sake @invalidate_table_constraints def rename_table(self, old_table_name, table_name): """ Renames the table 'old_table_name' to 'table_name'. """ if old_table_name == table_name: # Short-circuit out. return params = (self.quote_name(old_table_name), self.quote_name(table_name)) self.execute(self.rename_table_sql % params) # Invalidate the not-yet-indexed table self._set_cache(table_name, value=INVALID) @invalidate_table_constraints def delete_table(self, table_name, cascade=True): """ Deletes the table 'table_name'. """ params = (self.quote_name(table_name), ) if cascade: self.execute('DROP TABLE %s CASCADE;' % params) else: self.execute('DROP TABLE %s;' % params) drop_table = alias('delete_table') @invalidate_table_constraints def clear_table(self, table_name): """ Deletes all rows from 'table_name'. """ params = (self.quote_name(table_name), ) self.execute('DELETE FROM %s;' % params) @invalidate_table_constraints def add_column(self, table_name, name, field, keep_default=True): """ Adds the column 'name' to the table 'table_name'. Uses the 'field' paramater, a django.db.models.fields.Field instance, to generate the necessary sql @param table_name: The name of the table to add the column to @param name: The name of the column to add @param field: The field to use """ sql = self.column_sql(table_name, name, field) if sql: params = ( self.quote_name(table_name), sql, ) sql = self.add_column_string % params self.execute(sql) # Now, drop the default if we need to if not keep_default and field.default is not None: field.default = NOT_PROVIDED self.alter_column(table_name, name, field, explicit_name=False, ignore_constraints=True) def _db_type_for_alter_column(self, field): """ Returns a field's type suitable for ALTER COLUMN. By default it just returns field.db_type(). To be overriden by backend specific subclasses @param field: The field to generate type for """ try: return field.db_type(connection=self._get_connection()) except TypeError: return field.db_type() def _alter_add_column_mods(self, field, name, params, sqls): """ Subcommand of alter_column that modifies column definitions beyond the type string -- e.g. adding constraints where they cannot be specified as part of the type (overrideable) """ pass def _alter_set_defaults(self, field, name, params, sqls): "Subcommand of alter_column that sets default values (overrideable)" # Next, set any default if not field.null and field.has_default(): default = field.get_default() sqls.append(('ALTER COLUMN %s SET DEFAULT %%s ' % (self.quote_name(name),), [default])) else: sqls.append(('ALTER COLUMN %s DROP DEFAULT' % (self.quote_name(name),), [])) @invalidate_table_constraints def alter_column(self, table_name, name, field, explicit_name=True, ignore_constraints=False): """ Alters the given column name so it will match the given field. Note that conversion between the two by the database must be possible. Will not automatically add _id by default; to have this behavour, pass explicit_name=False. @param table_name: The name of the table to add the column to @param name: The name of the column to alter @param field: The new field definition to use """ if self.dry_run: if self.debug: print ' - no dry run output for alter_column() due to dynamic DDL, sorry' return # hook for the field to do any resolution prior to it's attributes being queried if hasattr(field, 'south_init'): field.south_init() # Add _id or whatever if we need to field.set_attributes_from_name(name) if not explicit_name: name = field.column else: field.column = name if not ignore_constraints: # Drop all check constraints. Note that constraints will be added back # with self.alter_string_set_type and self.alter_string_drop_null. if self.has_check_constraints: check_constraints = self._constraints_affecting_columns(table_name, [name], "CHECK") for constraint in check_constraints: self.execute(self.delete_check_sql % { 'table': self.quote_name(table_name), 'constraint': self.quote_name(constraint), }) # Drop all foreign key constraints try: self.delete_foreign_key(table_name, name) except ValueError: # There weren't any pass # First, change the type params = { "column": self.quote_name(name), "type": self._db_type_for_alter_column(field), "table_name": table_name } # SQLs is a list of (SQL, values) pairs. sqls = [] # Only alter the column if it has a type (Geometry ones sometimes don't) if params["type"] is not None: sqls.append((self.alter_string_set_type % params, [])) # Add any field- and backend- specific modifications self._alter_add_column_mods(field, name, params, sqls) # Next, nullity if field.null: sqls.append((self.alter_string_set_null % params, [])) else: sqls.append((self.alter_string_drop_null % params, [])) # Next, set any default self._alter_set_defaults(field, name, params, sqls) # Finally, actually change the column if self.allows_combined_alters: sqls, values = zip(*sqls) self.execute( "ALTER TABLE %s %s;" % (self.quote_name(table_name), ", ".join(sqls)), flatten(values), ) else: # Databases like e.g. MySQL don't like more than one alter at once. for sql, values in sqls: self.execute("ALTER TABLE %s %s;" % (self.quote_name(table_name), sql), values) if not ignore_constraints: # Add back FK constraints if needed if field.rel and self.supports_foreign_keys: self.execute( self.foreign_key_sql( table_name, field.column, field.rel.to._meta.db_table, field.rel.to._meta.get_field(field.rel.field_name).column ) ) def _fill_constraint_cache(self, db_name, table_name): schema = self._get_schema_name() ifsc_tables = ["constraint_column_usage", "key_column_usage"] self._constraint_cache.setdefault(db_name, {}) self._constraint_cache[db_name][table_name] = {} for ifsc_table in ifsc_tables: rows = self.execute(""" SELECT kc.constraint_name, kc.column_name, c.constraint_type FROM information_schema.%s AS kc JOIN information_schema.table_constraints AS c ON kc.table_schema = c.table_schema AND kc.table_name = c.table_name AND kc.constraint_name = c.constraint_name WHERE kc.table_schema = %%s AND kc.table_name = %%s """ % ifsc_table, [schema, table_name]) for constraint, column, kind in rows: self._constraint_cache[db_name][table_name].setdefault(column, set()) self._constraint_cache[db_name][table_name][column].add((kind, constraint)) return def _constraints_affecting_columns(self, table_name, columns, type="UNIQUE"): """ Gets the names of the constraints affecting the given columns. If columns is None, returns all constraints of the type on the table. """ if self.dry_run: raise DryRunError("Cannot get constraints for columns.") if columns is not None: columns = set(map(lambda s: s.lower(), columns)) db_name = self._get_setting('NAME') cnames = {} for col, constraints in self.lookup_constraint(db_name, table_name): for kind, cname in constraints: if kind == type: cnames.setdefault(cname, set()) cnames[cname].add(col.lower()) for cname, cols in cnames.items(): if cols == columns or columns is None: yield cname @invalidate_table_constraints def create_unique(self, table_name, columns): """ Creates a UNIQUE constraint on the columns on the given table. """ if not isinstance(columns, (list, tuple)): columns = [columns] name = self.create_index_name(table_name, columns, suffix="_uniq") cols = ", ".join(map(self.quote_name, columns)) self.execute("ALTER TABLE %s ADD CONSTRAINT %s UNIQUE (%s)" % ( self.quote_name(table_name), self.quote_name(name), cols, )) return name @invalidate_table_constraints def delete_unique(self, table_name, columns): """ Deletes a UNIQUE constraint on precisely the columns on the given table. """ if not isinstance(columns, (list, tuple)): columns = [columns] # Dry runs mean we can't do anything. if self.dry_run: if self.debug: print ' - no dry run output for delete_unique_column() due to dynamic DDL, sorry' return constraints = list(self._constraints_affecting_columns(table_name, columns)) if not constraints: raise ValueError("Cannot find a UNIQUE constraint on table %s, columns %r" % (table_name, columns)) for constraint in constraints: self.execute(self.delete_unique_sql % ( self.quote_name(table_name), self.quote_name(constraint), )) def column_sql(self, table_name, field_name, field, tablespace='', with_name=True, field_prepared=False): """ Creates the SQL snippet for a column. Used by add_column and add_table. """ # If the field hasn't already been told its attribute name, do so. if not field_prepared: field.set_attributes_from_name(field_name) # hook for the field to do any resolution prior to it's attributes being queried if hasattr(field, 'south_init'): field.south_init() # Possible hook to fiddle with the fields (e.g. defaults & TEXT on MySQL) field = self._field_sanity(field) try: sql = field.db_type(connection=self._get_connection()) except TypeError: sql = field.db_type() if sql: # Some callers, like the sqlite stuff, just want the extended type. if with_name: field_output = [self.quote_name(field.column), sql] else: field_output = [sql] field_output.append('%sNULL' % (not field.null and 'NOT ' or '')) if field.primary_key: field_output.append('PRIMARY KEY') elif field.unique: # Just use UNIQUE (no indexes any more, we have delete_unique) field_output.append('UNIQUE') tablespace = field.db_tablespace or tablespace if tablespace and getattr(self._get_connection().features, "supports_tablespaces", False) and field.unique: # We must specify the index tablespace inline, because we # won't be generating a CREATE INDEX statement for this field. field_output.append(self._get_connection().ops.tablespace_sql(tablespace, inline=True)) sql = ' '.join(field_output) sqlparams = () # if the field is "NOT NULL" and a default value is provided, create the column with it # this allows the addition of a NOT NULL field to a table with existing rows if not getattr(field, '_suppress_default', False): if field.has_default(): default = field.get_default() # If the default is actually None, don't add a default term if default is not None: # If the default is a callable, then call it! if callable(default): default = default() default = field.get_db_prep_save(default, connection=self._get_connection()) default = self._default_value_workaround(default) # Now do some very cheap quoting. TODO: Redesign return values to avoid this. if isinstance(default, basestring): default = "'%s'" % default.replace("'", "''") # Escape any % signs in the output (bug #317) if isinstance(default, basestring): default = default.replace("%", "%%") # Add it in sql += " DEFAULT %s" sqlparams = (default) elif (not field.null and field.blank) or (field.get_default() == ''): if field.empty_strings_allowed and self._get_connection().features.interprets_empty_strings_as_nulls: sql += " DEFAULT ''" # Error here would be nice, but doesn't seem to play fair. #else: # raise ValueError("Attempting to add a non null column that isn't character based without an explicit default value.") if field.rel and self.supports_foreign_keys: self.add_deferred_sql( self.foreign_key_sql( table_name, field.column, field.rel.to._meta.db_table, field.rel.to._meta.get_field(field.rel.field_name).column ) ) # Things like the contrib.gis module fields have this in 1.1 and below if hasattr(field, 'post_create_sql'): for stmt in field.post_create_sql(no_style(), table_name): self.add_deferred_sql(stmt) # In 1.2 and above, you have to ask the DatabaseCreation stuff for it. # This also creates normal indexes in 1.1. if hasattr(self._get_connection().creation, "sql_indexes_for_field"): # Make a fake model to pass in, with only db_table model = self.mock_model("FakeModelForGISCreation", table_name) for stmt in self._get_connection().creation.sql_indexes_for_field(model, field, no_style()): self.add_deferred_sql(stmt) if sql: return sql % sqlparams else: return None def _field_sanity(self, field): """ Placeholder for DBMS-specific field alterations (some combos aren't valid, e.g. DEFAULT and TEXT on MySQL) """ return field def _default_value_workaround(self, value): """ DBMS-specific value alterations (this really works around missing functionality in Django backends) """ if isinstance(value, bool) and not self.has_booleans: return int(value) else: return value def foreign_key_sql(self, from_table_name, from_column_name, to_table_name, to_column_name): """ Generates a full SQL statement to add a foreign key constraint """ constraint_name = '%s_refs_%s_%x' % (from_column_name, to_column_name, abs(hash((from_table_name, to_table_name)))) return 'ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s;' % ( self.quote_name(from_table_name), self.quote_name(self.shorten_name(constraint_name)), self.quote_name(from_column_name), self.quote_name(to_table_name), self.quote_name(to_column_name), self._get_connection().ops.deferrable_sql() # Django knows this ) @invalidate_table_constraints def delete_foreign_key(self, table_name, column): """ Drop a foreign key constraint """ if self.dry_run: if self.debug: print ' - no dry run output for delete_foreign_key() due to dynamic DDL, sorry' return # We can't look at the DB to get the constraints constraints = self._find_foreign_constraints(table_name, column) if not constraints: raise ValueError("Cannot find a FOREIGN KEY constraint on table %s, column %s" % (table_name, column)) for constraint_name in constraints: self.execute(self.delete_foreign_key_sql % { "table": self.quote_name(table_name), "constraint": self.quote_name(constraint_name), }) drop_foreign_key = alias('delete_foreign_key') def _find_foreign_constraints(self, table_name, column_name=None): constraints = self._constraints_affecting_columns( table_name, [column_name], "FOREIGN KEY") primary_key_columns = self._find_primary_key_columns(table_name) if len(primary_key_columns) > 1: # Composite primary keys cannot be referenced by a foreign key return list(constraints) else: primary_key_columns.add(column_name) recursive_constraints = set(self._constraints_affecting_columns( table_name, primary_key_columns, "FOREIGN KEY")) return list(recursive_constraints.union(constraints)) def _digest(self, *args): """ Use django.db.backends.creation.BaseDatabaseCreation._digest to create index name in Django style. An evil hack :( """ if not hasattr(self, '_django_db_creation'): self._django_db_creation = BaseDatabaseCreation(self._get_connection()) return self._django_db_creation._digest(*args) def shorten_name(self, name): return truncate_name(name, self._get_connection().ops.max_name_length()) def create_index_name(self, table_name, column_names, suffix=""): """ Generate a unique name for the index """ # If there is just one column in the index, use a default algorithm from Django if len(column_names) == 1 and not suffix: return self.shorten_name( '%s_%s' % (table_name, self._digest(column_names[0])) ) # Else generate the name for the index by South table_name = table_name.replace('"', '').replace('.', '_') index_unique_name = '_%x' % abs(hash((table_name, ','.join(column_names)))) # If the index name is too long, truncate it index_name = ('%s_%s%s%s' % (table_name, column_names[0], index_unique_name, suffix)).replace('"', '').replace('.', '_') if len(index_name) > self.max_index_name_length: part = ('_%s%s%s' % (column_names[0], index_unique_name, suffix)) index_name = '%s%s' % (table_name[:(self.max_index_name_length - len(part))], part) return index_name def create_index_sql(self, table_name, column_names, unique=False, db_tablespace=''): """ Generates a create index statement on 'table_name' for a list of 'column_names' """ if not column_names: print "No column names supplied on which to create an index" return '' connection = self._get_connection() if db_tablespace and connection.features.supports_tablespaces: tablespace_sql = ' ' + connection.ops.tablespace_sql(db_tablespace) else: tablespace_sql = '' index_name = self.create_index_name(table_name, column_names) return 'CREATE %sINDEX %s ON %s (%s)%s;' % ( unique and 'UNIQUE ' or '', self.quote_name(index_name), self.quote_name(table_name), ','.join([self.quote_name(field) for field in column_names]), tablespace_sql ) @invalidate_table_constraints def create_index(self, table_name, column_names, unique=False, db_tablespace=''): """ Executes a create index statement """ sql = self.create_index_sql(table_name, column_names, unique, db_tablespace) self.execute(sql) @invalidate_table_constraints def delete_index(self, table_name, column_names, db_tablespace=''): """ Deletes an index created with create_index. This is possible using only columns due to the deterministic index naming function which relies on column names. """ if isinstance(column_names, (str, unicode)): column_names = [column_names] name = self.create_index_name(table_name, column_names) sql = self.drop_index_string % { "index_name": self.quote_name(name), "table_name": self.quote_name(table_name), } self.execute(sql) drop_index = alias('delete_index') @delete_column_constraints def delete_column(self, table_name, name): """ Deletes the column 'column_name' from the table 'table_name'. """ params = (self.quote_name(table_name), self.quote_name(name)) self.execute(self.delete_column_string % params, []) drop_column = alias('delete_column') def rename_column(self, table_name, old, new): """ Renames the column 'old' from the table 'table_name' to 'new'. """ raise NotImplementedError("rename_column has no generic SQL syntax") @invalidate_table_constraints def delete_primary_key(self, table_name): """ Drops the old primary key. """ # Dry runs mean we can't do anything. if self.dry_run: if self.debug: print ' - no dry run output for delete_primary_key() due to dynamic DDL, sorry' return constraints = list(self._constraints_affecting_columns(table_name, None, type="PRIMARY KEY")) if not constraints: raise ValueError("Cannot find a PRIMARY KEY constraint on table %s" % (table_name,)) for constraint in constraints: self.execute(self.delete_primary_key_sql % { "table": self.quote_name(table_name), "constraint": self.quote_name(constraint), }) drop_primary_key = alias('delete_primary_key') @invalidate_table_constraints def create_primary_key(self, table_name, columns): """ Creates a new primary key on the specified columns. """ if not isinstance(columns, (list, tuple)): columns = [columns] self.execute(self.create_primary_key_string % { "table": self.quote_name(table_name), "constraint": self.quote_name(table_name + "_pkey"), "columns": ", ".join(map(self.quote_name, columns)), }) def _find_primary_key_columns(self, table_name): """ Find all columns of the primary key of the specified table """ db_name = self._get_setting('NAME') primary_key_columns = set() for col, constraints in self.lookup_constraint(db_name, table_name): for kind, cname in constraints: if kind == 'PRIMARY KEY': primary_key_columns.add(col.lower()) return primary_key_columns def start_transaction(self): """ Makes sure the following commands are inside a transaction. Must be followed by a (commit|rollback)_transaction call. """ if self.dry_run: self.pending_transactions += 1 transaction.commit_unless_managed(using=self.db_alias) transaction.enter_transaction_management(using=self.db_alias) transaction.managed(True, using=self.db_alias) def commit_transaction(self): """ Commits the current transaction. Must be preceded by a start_transaction call. """ if self.dry_run: return transaction.commit(using=self.db_alias) transaction.leave_transaction_management(using=self.db_alias) def rollback_transaction(self): """ Rolls back the current transaction. Must be preceded by a start_transaction call. """ if self.dry_run: self.pending_transactions -= 1 transaction.rollback(using=self.db_alias) transaction.leave_transaction_management(using=self.db_alias) def rollback_transactions_dry_run(self): """ Rolls back all pending_transactions during this dry run. """ if not self.dry_run: return while self.pending_transactions > 0: self.rollback_transaction() if transaction.is_dirty(using=self.db_alias): # Force an exception, if we're still in a dirty transaction. # This means we are missing a COMMIT/ROLLBACK. transaction.leave_transaction_management(using=self.db_alias) def send_create_signal(self, app_label, model_names): self.pending_create_signals.append((app_label, model_names)) def send_pending_create_signals(self, verbosity=0, interactive=False): # Group app_labels together signals = SortedDict() for (app_label, model_names) in self.pending_create_signals: try: signals[app_label].extend(model_names) except KeyError: signals[app_label] = list(model_names) # Send only one signal per app. for (app_label, model_names) in signals.iteritems(): self.really_send_create_signal(app_label, list(set(model_names)), verbosity=verbosity, interactive=interactive) self.pending_create_signals = [] def really_send_create_signal(self, app_label, model_names, verbosity=0, interactive=False): """ Sends a post_syncdb signal for the model specified. If the model is not found (perhaps it's been deleted?), no signal is sent. TODO: The behavior of django.contrib.* apps seems flawed in that they don't respect created_models. Rather, they blindly execute over all models within the app sending the signal. This is a patch we should push Django to make For now, this should work. """ if self.debug: print " - Sending post_syncdb signal for %s: %s" % (app_label, model_names) app = models.get_app(app_label) if not app: return created_models = [] for model_name in model_names: model = models.get_model(app_label, model_name) if model: created_models.append(model) if created_models: if hasattr(dispatcher, "send"): # Older djangos dispatcher.send(signal=models.signals.post_syncdb, sender=app, app=app, created_models=created_models, verbosity=verbosity, interactive=interactive) else: if self._is_multidb(): # Django 1.2+ models.signals.post_syncdb.send( sender=app, app=app, created_models=created_models, verbosity=verbosity, interactive=interactive, db=self.db_alias, ) else: # Django 1.1 - 1.0 models.signals.post_syncdb.send( sender=app, app=app, created_models=created_models, verbosity=verbosity, interactive=interactive, ) def mock_model(self, model_name, db_table, db_tablespace='', pk_field_name='id', pk_field_type=models.AutoField, pk_field_args=[], pk_field_kwargs={}): """ Generates a MockModel class that provides enough information to be used by a foreign key/many-to-many relationship. Migrations should prefer to use these rather than actual models as models could get deleted over time, but these can remain in migration files forever. Depreciated. """ class MockOptions(object): def __init__(self): self.db_table = db_table self.db_tablespace = db_tablespace or settings.DEFAULT_TABLESPACE self.object_name = model_name self.module_name = model_name.lower() if pk_field_type == models.AutoField: pk_field_kwargs['primary_key'] = True self.pk = pk_field_type(*pk_field_args, **pk_field_kwargs) self.pk.set_attributes_from_name(pk_field_name) self.abstract = False def get_field_by_name(self, field_name): # we only care about the pk field return (self.pk, self.model, True, False) def get_field(self, name): # we only care about the pk field return self.pk class MockModel(object): _meta = None # We need to return an actual class object here, not an instance MockModel._meta = MockOptions() MockModel._meta.model = MockModel return MockModel def _db_positive_type_for_alter_column(self, klass, field): """ A helper for subclasses overriding _db_type_for_alter_column: Remove the check constraint from the type string for PositiveInteger and PositiveSmallInteger fields. @param klass: The type of the child (required to allow this to be used when it is subclassed) @param field: The field to generate type for """ super_result = super(klass, self)._db_type_for_alter_column(field) if isinstance(field, (models.PositiveSmallIntegerField, models.PositiveIntegerField)): return super_result.split(" ", 1)[0] return super_result def _alter_add_positive_check(self, klass, field, name, params, sqls): """ A helper for subclasses overriding _alter_add_column_mods: Add a check constraint verifying positivity to PositiveInteger and PositiveSmallInteger fields. """ super(klass, self)._alter_add_column_mods(field, name, params, sqls) if isinstance(field, (models.PositiveSmallIntegerField, models.PositiveIntegerField)): uniq_hash = abs(hash(tuple(params.values()))) d = dict( constraint = "CK_%s_PSTV_%s" % (name, hex(uniq_hash)[2:]), check = "%s >= 0" % self.quote_name(name)) sqls.append((self.add_check_constraint_fragment % d, [])) # Single-level flattening of lists def flatten(ls): nl = [] for l in ls: nl += l return nl
bsd-3-clause
jacquesd/indico
indico/modules/rb/controllers/admin/rooms.py
2
7437
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from flask import request, flash from wtforms import StringField from wtforms.validators import DataRequired from indico.core.db import db from indico.modules.rb.controllers.admin import RHRoomBookingAdminBase from indico.modules.rb.forms.rooms import RoomForm from indico.modules.rb.models.equipment import EquipmentType from indico.modules.rb.models.room_attributes import RoomAttributeAssociation, RoomAttribute from indico.modules.rb.controllers.decorators import requires_location, requires_room from indico.modules.rb.models.room_bookable_hours import BookableHours from indico.modules.rb.models.room_nonbookable_periods import NonBookablePeriod from indico.modules.rb.models.rooms import Room from indico.modules.rb.models.photos import Photo from indico.modules.rb.views.admin import rooms as room_views from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.forms.validators import IndicoEmail from MaKaC.common.cache import GenericCache from MaKaC.webinterface import urlHandlers as UH _cache = GenericCache('Rooms') class RHRoomBookingDeleteRoom(RHRoomBookingAdminBase): CSRF_ENABLED = True def _checkParams(self): self._room = Room.get(request.view_args['roomID']) self._target = self._room def _process(self): if self._room.has_live_reservations(): flash(_(u'Cannot delete room with live bookings'), 'error') self._redirect(UH.UHRoomBookingRoomDetails.getURL(self._room)) else: db.session.delete(self._room) flash(_(u'Room deleted'), 'success') self._redirect(url_for('rooms_admin.roomBooking-adminLocation', self._room.location)) class RHRoomBookingCreateModifyRoomBase(RHRoomBookingAdminBase): def _make_form(self): room = self._room # New class so we can safely extend it form_class = type('RoomFormWithAttributes', (RoomForm,), {}) # Default values defaults = None if room.id is not None: skip_name = set() if room.has_special_name else {'name'} defaults = FormDefaults(room, skip_attrs={'nonbookable_periods', 'bookable_hours'} | skip_name) for ra in room.attributes.all(): defaults['attribute_{}'.format(ra.attribute_id)] = ra.value # Custom attributes - new fields must be set on the class for attribute in self._location.attributes.order_by(RoomAttribute.parent_id).all(): validators = [DataRequired()] if attribute.is_required else [] if attribute.name == 'notification-email': validators.append(IndicoEmail(multi=True)) field_name = 'attribute_{}'.format(attribute.id) field = StringField(attribute.title, validators) setattr(form_class, field_name, field) # Create the form form = form_class(obj=defaults) # Default values, part 2 if not form.is_submitted() and room.id is not None: # This is ugly, but apparently FieldList+FormField does not work well with obj defaults for i, nbd in enumerate(room.nonbookable_periods.all()): if i >= len(form.nonbookable_periods.entries): form.nonbookable_periods.append_entry() form.nonbookable_periods[i].start.data = nbd.start_dt form.nonbookable_periods[i].end.data = nbd.end_dt for i, bt in enumerate(room.bookable_hours.all()): if i >= len(form.bookable_hours.entries): form.bookable_hours.append_entry() form.bookable_hours[i].start.data = bt.start_time form.bookable_hours[i].end.data = bt.end_time # Custom attributes, part 2 form._attribute_fields = [field_ for name, field_ in form._fields.iteritems() if name.startswith('attribute_')] # Equipment form.available_equipment.query = self._location.equipment_types.order_by(EquipmentType.name) return form def _save(self): room = self._room form = self._form # Simple fields form.populate_obj(room, skip=('bookable_hours', 'nonbookable_periods'), existing_only=True) room.update_name() # Photos if form.small_photo.data and form.large_photo.data: _cache.delete_multi('photo-{}-{}'.format(room.id, size) for size in {'small', 'large'}) room.photo = Photo(thumbnail=form.small_photo.data.read(), data=form.large_photo.data.read()) elif form.delete_photos.data: _cache.delete_multi('photo-{}-{}'.format(room.id, size) for size in {'small', 'large'}) room.photo = None # Custom attributes room.attributes = [RoomAttributeAssociation(value=form['attribute_{}'.format(attr.id)].data, attribute_id=attr.id) for attr in self._location.attributes.all() if form['attribute_{}'.format(attr.id)].data] # Bookable times room.bookable_hours = [BookableHours(start_time=bt['start'], end_time=bt['end']) for bt in form.bookable_hours.data if all(x is not None for x in bt.viewvalues())] # Nonbookable dates room.nonbookable_periods = [NonBookablePeriod(start_dt=nbd['start'], end_dt=nbd['end']) for nbd in form.nonbookable_periods.data if all(nbd.viewvalues())] def _process(self): if self._form.validate_on_submit(): self._save() self._redirect(UH.UHRoomBookingRoomDetails.getURL(self._room)) else: return room_views.WPRoomBookingRoomForm(self, form=self._form, room=self._room, location=self._location, errors=self._form.error_list).display() class RHRoomBookingModifyRoom(RHRoomBookingCreateModifyRoomBase): @requires_location(parameter_name='roomLocation') @requires_room def _checkParams(self): self._form = self._make_form() def _save(self): RHRoomBookingCreateModifyRoomBase._save(self) flash(_(u'Room updated'), 'success') class RHRoomBookingCreateRoom(RHRoomBookingCreateModifyRoomBase): @requires_location(parameter_name='roomLocation') def _checkParams(self): self._room = Room() self._form = self._make_form() def _save(self): self._room.location = self._location RHRoomBookingCreateModifyRoomBase._save(self) db.session.add(self._room) db.session.flush() flash(_(u'Room added'), 'success')
gpl-3.0
akx-repo/akx.repositorio
plugin.video.filmesonlinegratis2/xmltosrt.py
22
2242
#!/usr/bin/python # -*- encoding:utf-8 -*- import re, sys def cleanHtml(dirty): clean = re.sub('&quot;', '\"', dirty) clean = re.sub('&#039;', '\'', clean) clean = re.sub('&#215;', 'x', clean) clean = re.sub('&#038;', '&', clean) clean = re.sub('&#8216;', '\'', clean) clean = re.sub('&#8217;', '\'', clean) clean = re.sub('&#8211;', '-', clean) clean = re.sub('&#8220;', '\"', clean) clean = re.sub('&#8221;', '\"', clean) clean = re.sub('&#8212;', '-', clean) clean = re.sub('&amp;', '&', clean) clean = re.sub("`", '', clean) clean = re.sub('<em>', '[I]', clean) clean = re.sub('</em>', '[/I]', clean) return clean # Pattern to identify a subtitle and grab start, duration and text. pat = re.compile(r'<?text start="(\d+\.\d+)" dur="(\d+\.\d+)">(.*)</text>?') def parseLine(text): """Parse a subtitle.""" m = re.match(pat, text) if m: return (m.group(1), m.group(2), m.group(3)) else: return None def formatSrtTime(secTime): """Convert a time in seconds (google's transcript) to srt time format.""" sec, micro = str(secTime).split('.') m, s = divmod(int(sec), 60) h, m = divmod(m, 60) #return "{:02}:{:02}:{:02},{}".format(h,m,s,micro) return "%.0f:%.0f:%.0f,%.0f" % (h,m,s,float(micro)) def convertHtml(text): """A few HTML encodings replacements. &amp;#39; to ' &amp;quot; to " """ return cleanHtml(text.replace('&amp;#39;', "'").replace('&amp;quot;', '"')) def printSrtLine(i, elms): """Print a subtitle in srt format.""" return "%s\n%s --> %s\n%s\n\n" % (i, formatSrtTime(elms[0]), formatSrtTime(float(elms[0])+float(elms[1])), convertHtml(elms[2])) fileName = sys.argv[1] def main(fileName): """Parse google's transcript and write the converted data in srt format.""" with open(fileName, 'rb') as infile: buf = [] for line in infile: buf.append(line.rstrip('\n')) # Split the buffer to get one string per tag. buf = "".join(buf).split('><') i = 0 srtfileName = fileName.replace('.xml', '.srt') with open(srtfileName, 'w') as outfile: for text in buf: parsed = parseLine(text) if parsed: i += 1 outfile.write(printSrtLine(i, parsed)) print('DONE (%s)' % (srtfileName)) if __name__ == "__main__": main(fileName)
gpl-2.0
nvoron23/arangodb
3rdParty/V8-4.3.61/third_party/python_26/Lib/test/test_abc.py
58
7268
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Unit tests for abc.py.""" import unittest from test import test_support import abc from inspect import isabstract class TestABC(unittest.TestCase): def test_abstractmethod_basics(self): @abc.abstractmethod def foo(self): pass self.assertEqual(foo.__isabstractmethod__, True) def bar(self): pass self.assertEqual(hasattr(bar, "__isabstractmethod__"), False) def test_abstractproperty_basics(self): @abc.abstractproperty def foo(self): pass self.assertEqual(foo.__isabstractmethod__, True) def bar(self): pass self.assertEqual(hasattr(bar, "__isabstractmethod__"), False) class C: __metaclass__ = abc.ABCMeta @abc.abstractproperty def foo(self): return 3 class D(C): @property def foo(self): return super(D, self).foo self.assertEqual(D().foo, 3) def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty]: class C: __metaclass__ = abc.ABCMeta @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, C) # because foo is abstract self.assert_(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, D) # because foo is still abstract self.assert_(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.failIf(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, set(["bar"])) self.assertRaises(TypeError, F) # because bar is abstract now self.assert_(isabstract(F)) def test_subclass_oldstyle_class(self): class A: __metaclass__ = abc.ABCMeta class OldstyleClass: pass self.assertFalse(issubclass(OldstyleClass, A)) self.assertFalse(issubclass(A, OldstyleClass)) def test_isinstance_class(self): class A: __metaclass__ = abc.ABCMeta class OldstyleClass: pass self.assertFalse(isinstance(OldstyleClass, A)) self.assertTrue(isinstance(OldstyleClass, type(OldstyleClass))) self.assertFalse(isinstance(A, OldstyleClass)) # This raises a recursion depth error, but is low-priority: # self.assertTrue(isinstance(A, abc.ABCMeta)) def test_registration_basics(self): class A: __metaclass__ = abc.ABCMeta class B(object): pass b = B() self.assertEqual(issubclass(B, A), False) self.assertEqual(issubclass(B, (A,)), False) self.assertEqual(isinstance(b, A), False) self.assertEqual(isinstance(b, (A,)), False) A.register(B) self.assertEqual(issubclass(B, A), True) self.assertEqual(issubclass(B, (A,)), True) self.assertEqual(isinstance(b, A), True) self.assertEqual(isinstance(b, (A,)), True) class C(B): pass c = C() self.assertEqual(issubclass(C, A), True) self.assertEqual(issubclass(C, (A,)), True) self.assertEqual(isinstance(c, A), True) self.assertEqual(isinstance(c, (A,)), True) def test_isinstance_invalidation(self): class A: __metaclass__ = abc.ABCMeta class B(object): pass b = B() self.assertEqual(isinstance(b, A), False) self.assertEqual(isinstance(b, (A,)), False) A.register(B) self.assertEqual(isinstance(b, A), True) self.assertEqual(isinstance(b, (A,)), True) def test_registration_builtins(self): class A: __metaclass__ = abc.ABCMeta A.register(int) self.assertEqual(isinstance(42, A), True) self.assertEqual(isinstance(42, (A,)), True) self.assertEqual(issubclass(int, A), True) self.assertEqual(issubclass(int, (A,)), True) class B(A): pass B.register(basestring) self.assertEqual(isinstance("", A), True) self.assertEqual(isinstance("", (A,)), True) self.assertEqual(issubclass(str, A), True) self.assertEqual(issubclass(str, (A,)), True) def test_registration_edge_cases(self): class A: __metaclass__ = abc.ABCMeta A.register(A) # should pass silently class A1(A): pass self.assertRaises(RuntimeError, A1.register, A) # cycles not allowed class B(object): pass A1.register(B) # ok A1.register(B) # should pass silently class C(A): pass A.register(C) # should pass silently self.assertRaises(RuntimeError, C.register, A) # cycles not allowed C.register(B) # ok def test_registration_transitiveness(self): class A: __metaclass__ = abc.ABCMeta self.failUnless(issubclass(A, A)) self.failUnless(issubclass(A, (A,))) class B: __metaclass__ = abc.ABCMeta self.failIf(issubclass(A, B)) self.failIf(issubclass(A, (B,))) self.failIf(issubclass(B, A)) self.failIf(issubclass(B, (A,))) class C: __metaclass__ = abc.ABCMeta A.register(B) class B1(B): pass self.failUnless(issubclass(B1, A)) self.failUnless(issubclass(B1, (A,))) class C1(C): pass B1.register(C1) self.failIf(issubclass(C, B)) self.failIf(issubclass(C, (B,))) self.failIf(issubclass(C, B1)) self.failIf(issubclass(C, (B1,))) self.failUnless(issubclass(C1, A)) self.failUnless(issubclass(C1, (A,))) self.failUnless(issubclass(C1, B)) self.failUnless(issubclass(C1, (B,))) self.failUnless(issubclass(C1, B1)) self.failUnless(issubclass(C1, (B1,))) C1.register(int) class MyInt(int): pass self.failUnless(issubclass(MyInt, A)) self.failUnless(issubclass(MyInt, (A,))) self.failUnless(isinstance(42, A)) self.failUnless(isinstance(42, (A,))) def test_all_new_methods_are_called(self): class A: __metaclass__ = abc.ABCMeta class B(object): counter = 0 def __new__(cls): B.counter += 1 return super(B, cls).__new__(cls) class C(A, B): pass self.assertEqual(B.counter, 0) C() self.assertEqual(B.counter, 1) def test_main(): test_support.run_unittest(TestABC) if __name__ == "__main__": unittest.main()
apache-2.0
jhawkesworth/ansible
lib/ansible/modules/storage/netapp/na_ontap_motd.py
14
5114
#!/usr/bin/python # (c) 2018 Piotr Olczak <piotr.olczak@redhat.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = ''' module: na_ontap_motd author: Piotr Olczak (@dprts) <polczak@redhat.com> extends_documentation_fragment: - netapp.na_ontap short_description: Setup motd on cDOT description: - This module allows you to manipulate motd on cDOT version_added: "2.7" requirements: - netapp_lib options: state: description: - If C(state=present) sets MOTD given in I(message) C(state=absent) removes it. choices: ['present', 'absent'] default: present message: description: - MOTD Text message, required when C(state=present). vserver: description: - The name of the SVM motd should be set for. required: true show_cluster_motd: description: - Set to I(false) if Cluster-level Message of the Day should not be shown type: bool default: True ''' EXAMPLES = ''' - name: Set Cluster-Level MOTD na_ontap_motd: vserver: my_ontap_cluster message: "Cluster wide MOTD" hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" state: present https: true - name: Set MOTD for I(rhev_nfs_krb) SVM, do not show Cluster-Level MOTD na_ontap_motd: vserver: rhev_nfs_krb message: "Access to rhev_nfs_krb is also restricted" hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" state: present show_cluster_motd: False https: true ''' RETURN = ''' ''' import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native import ansible.module_utils.netapp as netapp_utils from ansible.module_utils.netapp_module import NetAppModule try: import xmltodict HAS_XMLTODICT_LIB = True except ImportError: HAS_XMLTODICT_LIB = False HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class CDotMotd(object): def __init__(self): argument_spec = netapp_utils.na_ontap_host_argument_spec() argument_spec.update(dict( state=dict(required=False, default='present', choices=['present', 'absent']), vserver=dict(required=True, type='str'), message=dict(default='', type='str'), show_cluster_motd=dict(default=True, type='bool') )) self.module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) self.na_helper = NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params) if HAS_XMLTODICT_LIB is False: self.module.fail_json(msg="the python xmltodict module is required") if HAS_NETAPP_LIB is False: self.module.fail_json(msg="the python NetApp-Lib module is required") self.server = netapp_utils.setup_na_ontap_zapi(module=self.module) def _create_call(self): api_call = netapp_utils.zapi.NaElement('vserver-motd-modify-iter') api_call.add_new_child('message', self.parameters['message']) api_call.add_new_child('is-cluster-message-enabled', 'true' if self.parameters['show_cluster_motd'] else 'false') query = netapp_utils.zapi.NaElement('query') motd_info = netapp_utils.zapi.NaElement('vserver-motd-info') motd_info.add_new_child('vserver', self.parameters['vserver']) query.add_child_elem(motd_info) api_call.add_child_elem(query) return api_call def commit_changes(self): results = netapp_utils.get_cserver(self.server) cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) netapp_utils.ems_log_event("na_ontap_motd", cserver) if self.parameters['state'] == 'absent': # Just make sure it is empty self.parameters['message'] = '' call = self._create_call() try: _call_result = self.server.invoke_successfully(call, enable_tunneling=False) except netapp_utils.zapi.NaApiError as err: self.module.fail_json(msg="Error calling API %s: %s" % ('vserver-motd-modify-iter', to_native(err)), exception=traceback.format_exc()) _dict_num_succeeded = xmltodict.parse( _call_result.get_child_by_name('num-succeeded').to_string(), xml_attribs=False) num_succeeded = int(_dict_num_succeeded['num-succeeded']) changed = bool(num_succeeded >= 1) result = {'state': self.parameters['state'], 'changed': changed} self.module.exit_json(**result) def main(): ansible_call = CDotMotd() ansible_call.commit_changes() if __name__ == '__main__': main()
gpl-3.0
fogbow/fogbow-dashboard
openstack_dashboard/test/api_tests/network_tests.py
2
24835
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import itertools import uuid from django import http from mox import IsA # noqa from novaclient.v1_1 import floating_ip_pools from openstack_dashboard import api from openstack_dashboard.test import helpers as test class NetworkClientTestCase(test.APITestCase): def test_networkclient_no_neutron(self): self.mox.StubOutWithMock(api.base, 'is_service_enabled') api.base.is_service_enabled(IsA(http.HttpRequest), 'network') \ .AndReturn(False) self.mox.ReplayAll() nc = api.network.NetworkClient(self.request) self.assertIsInstance(nc.floating_ips, api.nova.FloatingIpManager) self.assertIsInstance(nc.secgroups, api.nova.SecurityGroupManager) def test_networkclient_neutron(self): self.mox.StubOutWithMock(api.base, 'is_service_enabled') api.base.is_service_enabled(IsA(http.HttpRequest), 'network') \ .AndReturn(True) self.neutronclient = self.stub_neutronclient() self.neutronclient.list_extensions() \ .AndReturn({'extensions': self.api_extensions.list()}) self.mox.ReplayAll() nc = api.network.NetworkClient(self.request) self.assertIsInstance(nc.floating_ips, api.neutron.FloatingIpManager) self.assertIsInstance(nc.secgroups, api.neutron.SecurityGroupManager) def test_networkclient_neutron_with_nova_security_group(self): self.mox.StubOutWithMock(api.base, 'is_service_enabled') api.base.is_service_enabled(IsA(http.HttpRequest), 'network') \ .AndReturn(True) self.neutronclient = self.stub_neutronclient() self.neutronclient.list_extensions().AndReturn({'extensions': []}) self.mox.ReplayAll() nc = api.network.NetworkClient(self.request) self.assertIsInstance(nc.floating_ips, api.neutron.FloatingIpManager) self.assertIsInstance(nc.secgroups, api.nova.SecurityGroupManager) class NetworkApiNovaTestBase(test.APITestCase): def setUp(self): super(NetworkApiNovaTestBase, self).setUp() self.mox.StubOutWithMock(api.base, 'is_service_enabled') api.base.is_service_enabled(IsA(http.HttpRequest), 'network') \ .AndReturn(False) class NetworkApiNovaSecurityGroupTests(NetworkApiNovaTestBase): def test_server_update_security_groups(self): all_secgroups = self.security_groups.list() added_secgroup = all_secgroups[2] rm_secgroup = all_secgroups[0] cur_secgroups_raw = [{'id': sg.id, 'name': sg.name, 'rules': []} for sg in all_secgroups[0:2]] cur_secgroups_ret = {'security_groups': cur_secgroups_raw} new_sg_ids = [sg.id for sg in all_secgroups[1:3]] instance_id = self.servers.first().id novaclient = self.stub_novaclient() novaclient.security_groups = self.mox.CreateMockAnything() novaclient.servers = self.mox.CreateMockAnything() novaclient.client = self.mox.CreateMockAnything() novaclient.security_groups.list().AndReturn(all_secgroups) url = '/servers/%s/os-security-groups' % instance_id novaclient.client.get(url).AndReturn((200, cur_secgroups_ret)) novaclient.servers.add_security_group(instance_id, added_secgroup.name) novaclient.servers.remove_security_group(instance_id, rm_secgroup.name) self.mox.ReplayAll() api.network.server_update_security_groups( self.request, instance_id, new_sg_ids) class NetworkApiNovaFloatingIpTests(NetworkApiNovaTestBase): def test_floating_ip_pools_list(self): pool_names = ['pool1', 'pool2'] pools = [floating_ip_pools.FloatingIPPool( None, {'name': pool}) for pool in pool_names] novaclient = self.stub_novaclient() novaclient.floating_ip_pools = self.mox.CreateMockAnything() novaclient.floating_ip_pools.list().AndReturn(pools) self.mox.ReplayAll() ret = api.network.floating_ip_pools_list(self.request) self.assertEqual([p.name for p in ret], pool_names) def test_floating_ip_list(self): fips = self.api_floating_ips.list() novaclient = self.stub_novaclient() novaclient.floating_ips = self.mox.CreateMockAnything() novaclient.floating_ips.list().AndReturn(fips) self.mox.ReplayAll() ret = api.network.tenant_floating_ip_list(self.request) for r, e in zip(ret, fips): for attr in ['id', 'ip', 'pool', 'fixed_ip', 'instance_id']: self.assertEqual(r.__getattr__(attr), e.__getattr__(attr)) self.assertEqual(r.port_id, e.instance_id) def test_floating_ip_get(self): fip = self.api_floating_ips.first() novaclient = self.stub_novaclient() novaclient.floating_ips = self.mox.CreateMockAnything() novaclient.floating_ips.get(fip.id).AndReturn(fip) self.mox.ReplayAll() ret = api.network.tenant_floating_ip_get(self.request, fip.id) for attr in ['id', 'ip', 'pool', 'fixed_ip', 'instance_id']: self.assertEqual(ret.__getattr__(attr), fip.__getattr__(attr)) self.assertEqual(ret.port_id, fip.instance_id) def test_floating_ip_allocate(self): pool_name = 'fip_pool' fip = self.api_floating_ips.first() novaclient = self.stub_novaclient() novaclient.floating_ips = self.mox.CreateMockAnything() novaclient.floating_ips.create(pool=pool_name).AndReturn(fip) self.mox.ReplayAll() ret = api.network.tenant_floating_ip_allocate(self.request, pool_name) for attr in ['id', 'ip', 'pool', 'fixed_ip', 'instance_id']: self.assertEqual(ret.__getattr__(attr), fip.__getattr__(attr)) self.assertEqual(ret.port_id, fip.instance_id) def test_floating_ip_release(self): fip = self.api_floating_ips.first() novaclient = self.stub_novaclient() novaclient.floating_ips = self.mox.CreateMockAnything() novaclient.floating_ips.delete(fip.id) self.mox.ReplayAll() api.network.tenant_floating_ip_release(self.request, fip.id) def test_floating_ip_associate(self): server = api.nova.Server(self.servers.first(), self.request) floating_ip = self.floating_ips.first() novaclient = self.stub_novaclient() novaclient.floating_ips = self.mox.CreateMockAnything() novaclient.servers = self.mox.CreateMockAnything() novaclient.servers.get(server.id).AndReturn(server) novaclient.floating_ips.get(floating_ip.id).AndReturn(floating_ip) novaclient.servers.add_floating_ip(server.id, floating_ip.ip) \ .AndReturn(server) self.mox.ReplayAll() api.network.floating_ip_associate(self.request, floating_ip.id, server.id) def test_floating_ip_disassociate(self): server = api.nova.Server(self.servers.first(), self.request) floating_ip = self.api_floating_ips.first() novaclient = self.stub_novaclient() novaclient.servers = self.mox.CreateMockAnything() novaclient.floating_ips = self.mox.CreateMockAnything() novaclient.servers.get(server.id).AndReturn(server) novaclient.floating_ips.get(floating_ip.id).AndReturn(floating_ip) novaclient.servers.remove_floating_ip(server.id, floating_ip.ip) \ .AndReturn(server) self.mox.ReplayAll() api.network.floating_ip_disassociate(self.request, floating_ip.id, server.id) def test_floating_ip_target_list(self): servers = self.servers.list() novaclient = self.stub_novaclient() novaclient.servers = self.mox.CreateMockAnything() novaclient.servers.list().AndReturn(servers) self.mox.ReplayAll() targets = api.network.floating_ip_target_list(self.request) for target, server in zip(targets, servers): self.assertEqual(target.id, server.id) self.assertEqual(target.name, '%s (%s)' % (server.name, server.id)) def test_floating_ip_target_get_by_instance(self): self.mox.ReplayAll() instance_id = self.servers.first().id ret = api.network.floating_ip_target_get_by_instance(self.request, instance_id) self.assertEqual(instance_id, ret) class NetworkApiNeutronTestBase(test.APITestCase): def setUp(self): super(NetworkApiNeutronTestBase, self).setUp() self.mox.StubOutWithMock(api.base, 'is_service_enabled') api.base.is_service_enabled(IsA(http.HttpRequest), 'network') \ .AndReturn(True) self.qclient = self.stub_neutronclient() self.qclient.list_extensions() \ .AndReturn({'extensions': self.api_extensions.list()}) class NetworkApiNeutronSecurityGroupTests(NetworkApiNeutronTestBase): def setUp(self): super(NetworkApiNeutronSecurityGroupTests, self).setUp() self.sg_dict = dict([(sg['id'], sg['name']) for sg in self.api_q_secgroups.list()]) def _cmp_sg_rule(self, exprule, retrule): self.assertEqual(exprule['id'], retrule.id) self.assertEqual(exprule['security_group_id'], retrule.parent_group_id) self.assertEqual(exprule['direction'], retrule.direction) self.assertEqual(exprule['ethertype'], retrule.ethertype) self.assertEqual(exprule['port_range_min'], retrule.from_port) self.assertEqual(exprule['port_range_max'], retrule.to_port) if (exprule['remote_ip_prefix'] is None and exprule['remote_group_id'] is None): expcidr = ('::/0' if exprule['ethertype'] == 'IPv6' else '0.0.0.0/0') else: expcidr = exprule['remote_ip_prefix'] self.assertEqual(expcidr, retrule.ip_range.get('cidr')) self.assertEqual(self.sg_dict.get(exprule['remote_group_id']), retrule.group.get('name')) def _cmp_sg(self, exp_sg, ret_sg): self.assertEqual(exp_sg['id'], ret_sg.id) self.assertEqual(exp_sg['name'], ret_sg.name) exp_rules = exp_sg['security_group_rules'] self.assertEqual(len(exp_rules), len(ret_sg.rules)) for (exprule, retrule) in itertools.izip(exp_rules, ret_sg.rules): self._cmp_sg_rule(exprule, retrule) def test_security_group_list(self): sgs = self.api_q_secgroups.list() tenant_id = self.request.user.tenant_id # use deepcopy to ensure self.api_q_secgroups is not modified. self.qclient.list_security_groups(tenant_id=tenant_id) \ .AndReturn({'security_groups': copy.deepcopy(sgs)}) self.mox.ReplayAll() rets = api.network.security_group_list(self.request) self.assertEqual(len(sgs), len(rets)) for (exp, ret) in itertools.izip(sgs, rets): self._cmp_sg(exp, ret) def test_security_group_get(self): secgroup = self.api_q_secgroups.first() sg_ids = set([secgroup['id']] + [rule['remote_group_id'] for rule in secgroup['security_group_rules'] if rule['remote_group_id']]) related_sgs = [sg for sg in self.api_q_secgroups.list() if sg['id'] in sg_ids] # use deepcopy to ensure self.api_q_secgroups is not modified. self.qclient.show_security_group(secgroup['id']) \ .AndReturn({'security_group': copy.deepcopy(secgroup)}) self.qclient.list_security_groups(id=sg_ids, fields=['id', 'name']) \ .AndReturn({'security_groups': related_sgs}) self.mox.ReplayAll() ret = api.network.security_group_get(self.request, secgroup['id']) self._cmp_sg(secgroup, ret) def test_security_group_create(self): secgroup = self.api_q_secgroups.list()[1] body = {'security_group': {'name': secgroup['name'], 'description': secgroup['description']}} self.qclient.create_security_group(body) \ .AndReturn({'security_group': copy.deepcopy(secgroup)}) self.mox.ReplayAll() ret = api.network.security_group_create(self.request, secgroup['name'], secgroup['description']) self._cmp_sg(secgroup, ret) def test_security_group_update(self): secgroup = self.api_q_secgroups.list()[1] secgroup = copy.deepcopy(secgroup) secgroup['name'] = 'newname' secgroup['description'] = 'new description' body = {'security_group': {'name': secgroup['name'], 'description': secgroup['description']}} self.qclient.update_security_group(secgroup['id'], body) \ .AndReturn({'security_group': secgroup}) self.mox.ReplayAll() ret = api.network.security_group_update(self.request, secgroup['id'], secgroup['name'], secgroup['description']) self._cmp_sg(secgroup, ret) def test_security_group_delete(self): secgroup = self.api_q_secgroups.first() self.qclient.delete_security_group(secgroup['id']) self.mox.ReplayAll() api.network.security_group_delete(self.request, secgroup['id']) def test_security_group_rule_create(self): sg_rule = [r for r in self.api_q_secgroup_rules.list() if r['protocol'] == 'tcp' and r['remote_ip_prefix']][0] sg_id = sg_rule['security_group_id'] secgroup = [sg for sg in self.api_q_secgroups.list() if sg['id'] == sg_id][0] post_rule = copy.deepcopy(sg_rule) del post_rule['id'] del post_rule['tenant_id'] post_body = {'security_group_rule': post_rule} self.qclient.create_security_group_rule(post_body) \ .AndReturn({'security_group_rule': copy.deepcopy(sg_rule)}) self.qclient.list_security_groups(id=set([sg_id]), fields=['id', 'name']) \ .AndReturn({'security_groups': [copy.deepcopy(secgroup)]}) self.mox.ReplayAll() ret = api.network.security_group_rule_create( self.request, sg_rule['security_group_id'], sg_rule['direction'], sg_rule['ethertype'], sg_rule['protocol'], sg_rule['port_range_min'], sg_rule['port_range_max'], sg_rule['remote_ip_prefix'], sg_rule['remote_group_id']) self._cmp_sg_rule(sg_rule, ret) def test_security_group_rule_delete(self): sg_rule = self.api_q_secgroup_rules.first() self.qclient.delete_security_group_rule(sg_rule['id']) self.mox.ReplayAll() api.network.security_group_rule_delete(self.request, sg_rule['id']) def _get_instance(self, cur_sg_ids): instance_port = [p for p in self.api_ports.list() if p['device_owner'].startswith('compute:')][0] instance_id = instance_port['device_id'] # Emulate an intance with two ports instance_ports = [] for _i in range(2): p = copy.deepcopy(instance_port) p['id'] = str(uuid.uuid4()) p['security_groups'] = cur_sg_ids instance_ports.append(p) return (instance_id, instance_ports) def test_server_security_groups(self): cur_sg_ids = [sg['id'] for sg in self.api_q_secgroups.list()[:2]] instance_id, instance_ports = self._get_instance(cur_sg_ids) self.qclient.list_ports(device_id=instance_id) \ .AndReturn({'ports': instance_ports}) secgroups = copy.deepcopy(self.api_q_secgroups.list()) self.qclient.list_security_groups(id=set(cur_sg_ids)) \ .AndReturn({'security_groups': secgroups}) self.mox.ReplayAll() api.network.server_security_groups(self.request, instance_id) def test_server_update_security_groups(self): cur_sg_ids = [self.api_q_secgroups.first()['id']] new_sg_ids = [sg['id'] for sg in self.api_q_secgroups.list()[:2]] instance_id, instance_ports = self._get_instance(cur_sg_ids) self.qclient.list_ports(device_id=instance_id) \ .AndReturn({'ports': instance_ports}) for p in instance_ports: body = {'port': {'security_groups': new_sg_ids}} self.qclient.update_port(p['id'], body=body).AndReturn({'port': p}) self.mox.ReplayAll() api.network.server_update_security_groups( self.request, instance_id, new_sg_ids) def test_security_group_backend(self): self.mox.ReplayAll() self.assertEqual(api.network.security_group_backend(self.request), 'neutron') class NetworkApiNeutronFloatingIpTests(NetworkApiNeutronTestBase): def test_floating_ip_pools_list(self): search_opts = {'router:external': True} ext_nets = [n for n in self.api_networks.list() if n['router:external']] self.qclient.list_networks(**search_opts) \ .AndReturn({'networks': ext_nets}) self.mox.ReplayAll() rets = api.network.floating_ip_pools_list(self.request) for attr in ['id', 'name']: self.assertEqual([p.__getattr__(attr) for p in rets], [p[attr] for p in ext_nets]) def test_floating_ip_list(self): fips = self.api_q_floating_ips.list() filters = {'tenant_id': self.request.user.tenant_id} self.qclient.list_floatingips(**filters) \ .AndReturn({'floatingips': fips}) self.qclient.list_ports(**filters) \ .AndReturn({'ports': self.api_ports.list()}) self.mox.ReplayAll() rets = api.network.tenant_floating_ip_list(self.request) assoc_port = self.api_ports.list()[1] self.assertEqual(len(fips), len(rets)) for ret, exp in zip(rets, fips): for attr in ['id', 'ip', 'pool', 'fixed_ip', 'port_id']: self.assertEqual(ret.__getattr__(attr), exp[attr]) if exp['port_id']: dev_id = assoc_port['device_id'] if exp['port_id'] else None self.assertEqual(ret.instance_id, dev_id) def test_floating_ip_get_associated(self): fip = self.api_q_floating_ips.list()[1] assoc_port = self.api_ports.list()[1] self.qclient.show_floatingip(fip['id']).AndReturn({'floatingip': fip}) self.qclient.show_port(assoc_port['id']) \ .AndReturn({'port': assoc_port}) self.mox.ReplayAll() ret = api.network.tenant_floating_ip_get(self.request, fip['id']) for attr in ['id', 'ip', 'pool', 'fixed_ip', 'port_id']: self.assertEqual(ret.__getattr__(attr), fip[attr]) self.assertEqual(ret.instance_id, assoc_port['device_id']) def test_floating_ip_get_unassociated(self): fip = self.api_q_floating_ips.list()[0] self.qclient.show_floatingip(fip['id']).AndReturn({'floatingip': fip}) self.mox.ReplayAll() ret = api.network.tenant_floating_ip_get(self.request, fip['id']) for attr in ['id', 'ip', 'pool', 'fixed_ip', 'port_id']: self.assertEqual(ret.__getattr__(attr), fip[attr]) self.assertEqual(ret.instance_id, None) def test_floating_ip_allocate(self): ext_nets = [n for n in self.api_networks.list() if n['router:external']] ext_net = ext_nets[0] fip = self.api_q_floating_ips.first() self.qclient.create_floatingip( {'floatingip': {'floating_network_id': ext_net['id']}}) \ .AndReturn({'floatingip': fip}) self.mox.ReplayAll() ret = api.network.tenant_floating_ip_allocate(self.request, ext_net['id']) for attr in ['id', 'ip', 'pool', 'fixed_ip', 'port_id']: self.assertEqual(ret.__getattr__(attr), fip[attr]) self.assertEqual(ret.instance_id, None) def test_floating_ip_release(self): fip = self.api_q_floating_ips.first() self.qclient.delete_floatingip(fip['id']) self.mox.ReplayAll() api.network.tenant_floating_ip_release(self.request, fip['id']) def test_floating_ip_associate(self): fip = self.api_q_floating_ips.list()[1] assoc_port = self.api_ports.list()[1] ip_address = assoc_port['fixed_ips'][0]['ip_address'] target_id = '%s_%s' % (assoc_port['id'], ip_address) params = {'port_id': assoc_port['id'], 'fixed_ip_address': ip_address} self.qclient.update_floatingip(fip['id'], {'floatingip': params}) self.mox.ReplayAll() api.network.floating_ip_associate(self.request, fip['id'], target_id) def test_floating_ip_disassociate(self): fip = self.api_q_floating_ips.list()[1] assoc_port = self.api_ports.list()[1] ip_address = assoc_port['fixed_ips'][0]['ip_address'] target_id = '%s_%s' % (assoc_port['id'], ip_address) self.qclient.update_floatingip(fip['id'], {'floatingip': {'port_id': None}}) self.mox.ReplayAll() api.network.floating_ip_disassociate(self.request, fip['id'], target_id) def _get_target_id(self, port): param = {'id': port['id'], 'addr': port['fixed_ips'][0]['ip_address']} return '%(id)s_%(addr)s' % param def _get_target_name(self, port): param = {'svrid': port['device_id'], 'addr': port['fixed_ips'][0]['ip_address']} return 'server_%(svrid)s: %(addr)s' % param def test_floating_ip_target_list(self): ports = self.api_ports.list() target_ports = [(self._get_target_id(p), self._get_target_name(p)) for p in ports if not p['device_owner'].startswith('network:')] filters = {'tenant_id': self.request.user.tenant_id} self.qclient.list_ports(**filters).AndReturn({'ports': ports}) servers = self.servers.list() novaclient = self.stub_novaclient() novaclient.servers = self.mox.CreateMockAnything() search_opts = {'project_id': self.request.user.tenant_id} novaclient.servers.list(True, search_opts).AndReturn(servers) self.mox.ReplayAll() rets = api.network.floating_ip_target_list(self.request) self.assertEqual(len(rets), len(target_ports)) for ret, exp in zip(rets, target_ports): self.assertEqual(ret.id, exp[0]) self.assertEqual(ret.name, exp[1]) def test_floating_ip_target_get_by_instance(self): ports = self.api_ports.list() candidates = [p for p in ports if p['device_id'] == '1'] search_opts = {'device_id': '1'} self.qclient.list_ports(**search_opts).AndReturn({'ports': candidates}) self.mox.ReplayAll() ret = api.network.floating_ip_target_get_by_instance(self.request, '1') self.assertEqual(ret, self._get_target_id(candidates[0])) def test_target_floating_ip_port_by_instance(self): ports = self.api_ports.list() candidates = [p for p in ports if p['device_id'] == '1'] search_opts = {'device_id': '1'} self.qclient.list_ports(**search_opts).AndReturn({'ports': candidates}) self.mox.ReplayAll() ret = api.network.floating_ip_target_list_by_instance(self.request, '1') self.assertEqual(ret[0], self._get_target_id(candidates[0])) self.assertEqual(len(ret), len(candidates))
apache-2.0
0/SpanishAcquisition
spacq/devices/oxford/ips120_10.py
2
5674
import logging log = logging.getLogger(__name__) from collections import namedtuple from time import sleep from spacq.interface.resources import Resource from spacq.tool.box import Synchronized from ..abstract_device import AbstractDevice from ..tools import str_to_bool, quantity_wrapped, quantity_unwrapped """ Oxford Instruments IPS120-10 Superconducting Magnet Power Supply """ Status = namedtuple('Status', 'system_status, limits, activity, remote_status, heater, mode, mode_sweep') class IPS120_10(AbstractDevice): """ Interface for the Oxford Instruments IPS120-10. """ allowed_settings = ['default value', 'something else'] activities = ['hold', 'to_set', 'to_zero', 'clamped'] heater_delay = 10 # s def _setup(self): AbstractDevice._setup(self) self._perma_hot = True # Resources. read_write = ['perma_hot', 'sweep_rate', 'field'] for name in read_write: self.resources[name] = Resource(self, name, name) self.resources['perma_hot'].converter = str_to_bool self.resources['sweep_rate'].units = 'T.s-1' self.resources['field'].units = 'T' @Synchronized() def _connected(self): self.eos_char = '\r' AbstractDevice._connected(self) self.write('$Q4') # Extended resolution. self.write('$C3') # Remote & unlocked. self.write('$M9') # Display in Tesla. if self.device_status.activity == 4: self.write('$A0') # Unclamp. # Ensure some initial sanity. assert self.device_status.activity == 0, 'Not on hold.' def write(self, message): """ Append the "\r" that the device requires. """ AbstractDevice.write(self, message + '\r') @property def device_status(self): """ All the status information for the device. """ result = self.ask('X') system_status = int(result[1]) limits = int(result[2]) activity = int(result[4]) remote_status = int(result[6]) heater = int(result[8]) mode = int(result[10]) mode_sweep = int(result[11]) # The polarity status is deprecated. return Status(system_status, limits, activity, remote_status, heater, mode, mode_sweep) @property def activity(self): """ What the device is currently up to. """ return self.activities[self.device_status.activity] @activity.setter def activity(self, value): self.write('$A{0}'.format(self.activities.index(value))) @property def heater_on(self): """ Whether the heater is enabled. """ return bool(self.device_status.heater & 1) @heater_on.setter def heater_on(self, value): self.status.append('Turning heater o{0}'.format('n' if value else 'ff')) try: self.write('$H{0}'.format(int(value))) # Allow the heater to go to the correct setting. log.debug('Waiting for heater for {0} s.'.format(self.heater_delay)) sleep(self.heater_delay) finally: self.status.pop() @property def perma_hot(self): """ Whether the heater should always remain on. """ return self._perma_hot @perma_hot.setter def perma_hot(self, value): self._perma_hot = value @property # The value used on the device is in T/min. @quantity_wrapped('T.s-1', 1./60) def sweep_rate(self): """ The rate of the field sweep, as a quantity in T/s. """ return float(self.ask('R9')[1:]) @sweep_rate.setter @quantity_unwrapped('T.s-1', 60) def sweep_rate(self, value): if value <= 0: raise ValueError('Sweep rate must be positive, not {0}.'.format(value)) self.write('$T{0:f}'.format(value)) @property @quantity_wrapped('T') def persistent_field(self): """ The output field when the heater was last disabled, as a quantity in T. """ return float(self.ask('R18')[1:]) @property @quantity_wrapped('T') def output_field(self): """ The actual field due to the output current in T. """ return float(self.ask('R7')[1:]) @property @quantity_wrapped('T') def set_point(self): """ The set point, as a quantity in T. """ return float(self.ask('R8')[1:]) @set_point.setter @quantity_unwrapped('T') def set_point(self, value): self.write('$J{0}'.format(value)) @property def field(self): """ The magnetic field, as a quantity in T. """ return self.output_field def set_field(self, value): """ Go through all the steps for setting the output field. """ if self.output_field == value: return self.status.append('Setting field to {0}'.format(value)) try: set_delay = abs(value - self.output_field).value / self.sweep_rate.value # s self.set_point = value self.activity = 'to_set' # If the heater is on, the sweep rate is used, so wait. if self.heater_on: log.debug('Waiting for sweep for {0} s.'.format(set_delay)) sleep(set_delay) # Ensure that the sweep is actually over. while self.device_status.mode_sweep != 0: sleep(0.1) self.activity = 'hold' finally: self.status.pop() @field.setter @Synchronized() def field(self, value): status = self.device_status assert status.system_status == 0, 'System status: {0}'.format(status.system_status) assert status.limits == 0, 'Limits: {0}'.format(status.limits) assert status.mode_sweep == 0, 'Mode sweep: {0}'.format(status.mode_sweep) assert self.activity == 'hold', 'Activity: {0}'.format(self.activity) # Return to the last field. if not self.heater_on: self.set_field(self.persistent_field) self.heater_on = True # Change to the new field. self.set_field(value) if not self.perma_hot: self.heater_on = False @property def idn(self): """ *idn? substitute for this non-SCPI device. """ return self.ask('V') @property def opc(self): """ *opc? substitute for this non-SCPI device. """ return 1 name = 'IPS120-10' implementation = IPS120_10
bsd-2-clause
e-democracy/edemsignups
lib/gdata/docs/__init__.py
263
8993
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to Atom objects used with Google Documents.""" __author__ = ('api.jfisher (Jeff Fisher), ' 'api.eric@google.com (Eric Bidelman)') import atom import gdata DOCUMENTS_NAMESPACE = 'http://schemas.google.com/docs/2007' class Scope(atom.AtomBase): """The DocList ACL scope element""" _tag = 'scope' _namespace = gdata.GACL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' _attributes['type'] = 'type' def __init__(self, value=None, type=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.type = type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Role(atom.AtomBase): """The DocList ACL role element""" _tag = 'role' _namespace = gdata.GACL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class FeedLink(atom.AtomBase): """The DocList gd:feedLink element""" _tag = 'feedLink' _namespace = gdata.GDATA_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['href'] = 'href' def __init__(self, href=None, rel=None, text=None, extension_elements=None, extension_attributes=None): self.href = href self.rel = rel atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class ResourceId(atom.AtomBase): """The DocList gd:resourceId element""" _tag = 'resourceId' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class LastModifiedBy(atom.Person): """The DocList gd:lastModifiedBy element""" _tag = 'lastModifiedBy' _namespace = gdata.GDATA_NAMESPACE class LastViewed(atom.Person): """The DocList gd:lastViewed element""" _tag = 'lastViewed' _namespace = gdata.GDATA_NAMESPACE class WritersCanInvite(atom.AtomBase): """The DocList docs:writersCanInvite element""" _tag = 'writersCanInvite' _namespace = DOCUMENTS_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' class DocumentListEntry(gdata.GDataEntry): """The Google Documents version of an Atom Entry""" _tag = gdata.GDataEntry._tag _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feedLink', FeedLink) _children['{%s}resourceId' % gdata.GDATA_NAMESPACE] = ('resourceId', ResourceId) _children['{%s}lastModifiedBy' % gdata.GDATA_NAMESPACE] = ('lastModifiedBy', LastModifiedBy) _children['{%s}lastViewed' % gdata.GDATA_NAMESPACE] = ('lastViewed', LastViewed) _children['{%s}writersCanInvite' % DOCUMENTS_NAMESPACE] = ( 'writersCanInvite', WritersCanInvite) def __init__(self, resourceId=None, feedLink=None, lastViewed=None, lastModifiedBy=None, writersCanInvite=None, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, text=None, extension_elements=None, extension_attributes=None): self.feedLink = feedLink self.lastViewed = lastViewed self.lastModifiedBy = lastModifiedBy self.resourceId = resourceId self.writersCanInvite = writersCanInvite gdata.GDataEntry.__init__( self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def GetAclLink(self): """Extracts the DocListEntry's <gd:feedLink>. Returns: A FeedLink object. """ return self.feedLink def GetDocumentType(self): """Extracts the type of document from the DocListEntry. This method returns the type of document the DocListEntry represents. Possible values are document, presentation, spreadsheet, folder, or pdf. Returns: A string representing the type of document. """ if self.category: for category in self.category: if category.scheme == gdata.GDATA_NAMESPACE + '#kind': return category.label else: return None def DocumentListEntryFromString(xml_string): """Converts an XML string into a DocumentListEntry object. Args: xml_string: string The XML describing a Document List feed entry. Returns: A DocumentListEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListEntry, xml_string) class DocumentListAclEntry(gdata.GDataEntry): """A DocList ACL Entry flavor of an Atom Entry""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}scope' % gdata.GACL_NAMESPACE] = ('scope', Scope) _children['{%s}role' % gdata.GACL_NAMESPACE] = ('role', Role) def __init__(self, category=None, atom_id=None, link=None, title=None, updated=None, scope=None, role=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=None, category=category, content=None, atom_id=atom_id, link=link, published=None, title=title, updated=updated, text=None) self.scope = scope self.role = role def DocumentListAclEntryFromString(xml_string): """Converts an XML string into a DocumentListAclEntry object. Args: xml_string: string The XML describing a Document List ACL feed entry. Returns: A DocumentListAclEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListAclEntry, xml_string) class DocumentListFeed(gdata.GDataFeed): """A feed containing a list of Google Documents Items""" _tag = gdata.GDataFeed._tag _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [DocumentListEntry]) def DocumentListFeedFromString(xml_string): """Converts an XML string into a DocumentListFeed object. Args: xml_string: string The XML describing a DocumentList feed. Returns: A DocumentListFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListFeed, xml_string) class DocumentListAclFeed(gdata.GDataFeed): """A DocList ACL feed flavor of a Atom feed""" _tag = gdata.GDataFeed._tag _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [DocumentListAclEntry]) def DocumentListAclFeedFromString(xml_string): """Converts an XML string into a DocumentListAclFeed object. Args: xml_string: string The XML describing a DocumentList feed. Returns: A DocumentListFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListAclFeed, xml_string)
gpl-3.0
Alex-Diez/python-tdd-katas
old-katas/string-compress-kata/day-9.py
1
1370
# -*- codeing: utf-8 -*- class Compressor(object): def compress(self, toCompress): if toCompress is None: return "" else: result = [] index = 0 length = len (toCompress) while index < length: counter = 1 index += 1 while index < length and toCompress[index - 1] == toCompress[index]: counter += 1 index += 1 result.append(str(counter)) result.append(toCompress[index - 1]) return ''.join(result) import unittest class StringCompressorTest(unittest.TestCase): def setUp(self): self.compressor = Compressor() def test_none_compressed_to_an_empty_string(self): self.assertEqual("", self.compressor.compress(None)) def test_compresses_a_single_character_string(self): self.assertEqual("1a", self.compressor.compress("a")) def test_compresses_a_string_of_unique_characters(self): self.assertEqual("1a1b1c", self.compressor.compress("abc")) def test_compresses_a_string_of_doubled_characters(self): self.assertEqual("2a2b2c", self.compressor.compress("aabbcc")) def test_compresses_an_empty_string_to_another_empty_string(self): self.assertEqual("", self.compressor.compress(""))
mit
JelleZijlstra/cython
Cython/Compiler/Naming.py
12
5730
# # C naming conventions # # # Prefixes for generating C names. # Collected here to facilitate ensuring uniqueness. # pyrex_prefix = "__pyx_" codewriter_temp_prefix = pyrex_prefix + "t_" temp_prefix = u"__cyt_" builtin_prefix = pyrex_prefix + "builtin_" arg_prefix = pyrex_prefix + "arg_" funcdoc_prefix = pyrex_prefix + "doc_" enum_prefix = pyrex_prefix + "e_" func_prefix = pyrex_prefix + "f_" func_prefix_api = pyrex_prefix + "api_f_" pyfunc_prefix = pyrex_prefix + "pf_" pywrap_prefix = pyrex_prefix + "pw_" genbody_prefix = pyrex_prefix + "gb_" gstab_prefix = pyrex_prefix + "getsets_" prop_get_prefix = pyrex_prefix + "getprop_" const_prefix = pyrex_prefix + "k_" py_const_prefix = pyrex_prefix + "kp_" label_prefix = pyrex_prefix + "L" pymethdef_prefix = pyrex_prefix + "mdef_" methtab_prefix = pyrex_prefix + "methods_" memtab_prefix = pyrex_prefix + "members_" objstruct_prefix = pyrex_prefix + "obj_" typeptr_prefix = pyrex_prefix + "ptype_" prop_set_prefix = pyrex_prefix + "setprop_" type_prefix = pyrex_prefix + "t_" typeobj_prefix = pyrex_prefix + "type_" var_prefix = pyrex_prefix + "v_" varptr_prefix = pyrex_prefix + "vp_" varptr_prefix_api = pyrex_prefix + "api_vp_" wrapperbase_prefix= pyrex_prefix + "wrapperbase_" pybuffernd_prefix = pyrex_prefix + "pybuffernd_" pybufferstruct_prefix = pyrex_prefix + "pybuffer_" vtable_prefix = pyrex_prefix + "vtable_" vtabptr_prefix = pyrex_prefix + "vtabptr_" vtabstruct_prefix = pyrex_prefix + "vtabstruct_" opt_arg_prefix = pyrex_prefix + "opt_args_" convert_func_prefix = pyrex_prefix + "convert_" closure_scope_prefix = pyrex_prefix + "scope_" closure_class_prefix = pyrex_prefix + "scope_struct_" lambda_func_prefix = pyrex_prefix + "lambda_" module_is_main = pyrex_prefix + "module_is_main_" defaults_struct_prefix = pyrex_prefix + "defaults" dynamic_args_cname = pyrex_prefix + "dynamic_args" interned_prefixes = { 'str': pyrex_prefix + "n_", 'int': pyrex_prefix + "int_", 'float': pyrex_prefix + "float_", 'tuple': pyrex_prefix + "tuple_", 'codeobj': pyrex_prefix + "codeobj_", 'slice': pyrex_prefix + "slice_", 'ustring': pyrex_prefix + "ustring_", 'umethod': pyrex_prefix + "umethod_", } ctuple_type_prefix = pyrex_prefix + "ctuple_" args_cname = pyrex_prefix + "args" generator_cname = pyrex_prefix + "generator" sent_value_cname = pyrex_prefix + "sent_value" pykwdlist_cname = pyrex_prefix + "pyargnames" obj_base_cname = pyrex_prefix + "base" builtins_cname = pyrex_prefix + "b" preimport_cname = pyrex_prefix + "i" moddict_cname = pyrex_prefix + "d" dummy_cname = pyrex_prefix + "dummy" filename_cname = pyrex_prefix + "filename" modulename_cname = pyrex_prefix + "modulename" filetable_cname = pyrex_prefix + "f" intern_tab_cname = pyrex_prefix + "intern_tab" kwds_cname = pyrex_prefix + "kwds" lineno_cname = pyrex_prefix + "lineno" clineno_cname = pyrex_prefix + "clineno" cfilenm_cname = pyrex_prefix + "cfilenm" module_cname = pyrex_prefix + "m" moddoc_cname = pyrex_prefix + "mdoc" methtable_cname = pyrex_prefix + "methods" retval_cname = pyrex_prefix + "r" reqd_kwds_cname = pyrex_prefix + "reqd_kwds" self_cname = pyrex_prefix + "self" stringtab_cname = pyrex_prefix + "string_tab" vtabslot_cname = pyrex_prefix + "vtab" c_api_tab_cname = pyrex_prefix + "c_api_tab" gilstate_cname = pyrex_prefix + "state" skip_dispatch_cname = pyrex_prefix + "skip_dispatch" empty_tuple = pyrex_prefix + "empty_tuple" empty_bytes = pyrex_prefix + "empty_bytes" print_function = pyrex_prefix + "print" print_function_kwargs = pyrex_prefix + "print_kwargs" cleanup_cname = pyrex_prefix + "module_cleanup" pymoduledef_cname = pyrex_prefix + "moduledef" optional_args_cname = pyrex_prefix + "optional_args" import_star = pyrex_prefix + "import_star" import_star_set = pyrex_prefix + "import_star_set" outer_scope_cname= pyrex_prefix + "outer_scope" cur_scope_cname = pyrex_prefix + "cur_scope" enc_scope_cname = pyrex_prefix + "enc_scope" frame_cname = pyrex_prefix + "frame" frame_code_cname = pyrex_prefix + "frame_code" binding_cfunc = pyrex_prefix + "binding_PyCFunctionType" fused_func_prefix = pyrex_prefix + 'fuse_' quick_temp_cname = pyrex_prefix + "temp" # temp variable for quick'n'dirty temping global_code_object_cache_find = pyrex_prefix + 'find_code_object' global_code_object_cache_insert = pyrex_prefix + 'insert_code_object' genexpr_id_ref = 'genexpr' freelist_name = 'freelist' freecount_name = 'freecount' line_c_macro = "__LINE__" file_c_macro = "__FILE__" extern_c_macro = pyrex_prefix.upper() + "EXTERN_C" exc_type_name = pyrex_prefix + "exc_type" exc_value_name = pyrex_prefix + "exc_value" exc_tb_name = pyrex_prefix + "exc_tb" exc_lineno_name = pyrex_prefix + "exc_lineno" parallel_exc_type = pyrex_prefix + "parallel_exc_type" parallel_exc_value = pyrex_prefix + "parallel_exc_value" parallel_exc_tb = pyrex_prefix + "parallel_exc_tb" parallel_filename = pyrex_prefix + "parallel_filename" parallel_lineno = pyrex_prefix + "parallel_lineno" parallel_clineno = pyrex_prefix + "parallel_clineno" parallel_why = pyrex_prefix + "parallel_why" exc_vars = (exc_type_name, exc_value_name, exc_tb_name) api_name = pyrex_prefix + "capi__" h_guard_prefix = "__PYX_HAVE__" api_guard_prefix = "__PYX_HAVE_API__" api_func_guard = "__PYX_HAVE_API_FUNC_" PYX_NAN = "__PYX_NAN()" def py_version_hex(major, minor=0, micro=0, release_level=0, release_serial=0): return (major << 24) | (minor << 16) | (micro << 8) | (release_level << 4) | (release_serial)
apache-2.0
chadversary/deqp
modules/gles3/scripts/gen-invalid-texture-funcs.py
3
7163
# -*- coding: utf-8 -*- #------------------------------------------------------------------------- # drawElements Quality Program utilities # -------------------------------------- # # Copyright 2015 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #------------------------------------------------------------------------- import sys import string from genutil import * # Templates INVALID_TEXTURE_FUNC_TEMPLATE = """ case ${{NAME}} expect compile_fail values {} version 300 es both "" #version 300 es precision mediump float; ${DECLARATIONS} uniform mediump ${{SAMPLERTYPE}} s; void main() { ${SETUP} ${POSITION_FRAG_COLOR} = vec4(${{LOOKUP}}); ${OUTPUT} } "" end """[1:-1] # Classes def getValueExpr (argType): return "%s(0)" % argType class InvalidTexFuncCase(ShaderCase): def __init__(self, funcname, args): self.name = string.join([s.lower() for s in [funcname] + args], "_") self.funcname = funcname self.args = args def __str__(self): samplerType = self.args[0] lookup = self.funcname + "(s" for arg in self.args[1:]: lookup += ", %s" % getValueExpr(arg) lookup += ")" params = { "NAME": self.name, "SAMPLERTYPE": samplerType, "LOOKUP": lookup } return fillTemplate(INVALID_TEXTURE_FUNC_TEMPLATE, params) # Invalid lookup cases # \note Does not include cases that don't make sense INVALID_TEX_FUNC_CASES = [ # texture InvalidTexFuncCase("texture", ["sampler3DShadow", "vec4"]), InvalidTexFuncCase("texture", ["sampler2DArrayShadow", "vec4", "float"]), # textureProj InvalidTexFuncCase("textureProj", ["samplerCube", "vec4"]), InvalidTexFuncCase("textureProj", ["isamplerCube", "vec4"]), InvalidTexFuncCase("textureProj", ["usamplerCube", "vec4"]), InvalidTexFuncCase("textureProj", ["samplerCube", "vec4", "float"]), InvalidTexFuncCase("textureProj", ["isamplerCube", "vec4", "float"]), InvalidTexFuncCase("textureProj", ["usamplerCube", "vec4", "float"]), InvalidTexFuncCase("textureProj", ["sampler2DArrayShadow", "vec4"]), InvalidTexFuncCase("textureProj", ["sampler2DArrayShadow", "vec4", "float"]), # textureLod InvalidTexFuncCase("textureLod", ["samplerCubeShadow", "vec4", "float"]), InvalidTexFuncCase("textureLod", ["sampler2DArrayShadow", "vec4", "float"]), # textureOffset InvalidTexFuncCase("textureOffset", ["samplerCube", "vec3", "ivec2"]), InvalidTexFuncCase("textureOffset", ["isamplerCube", "vec3", "ivec2"]), InvalidTexFuncCase("textureOffset", ["usamplerCube", "vec3", "ivec2"]), InvalidTexFuncCase("textureOffset", ["samplerCube", "vec3", "ivec3"]), InvalidTexFuncCase("textureOffset", ["isamplerCube", "vec3", "ivec3"]), InvalidTexFuncCase("textureOffset", ["usamplerCube", "vec3", "ivec3"]), InvalidTexFuncCase("textureOffset", ["samplerCube", "vec3", "ivec2", "float"]), InvalidTexFuncCase("textureOffset", ["samplerCube", "vec3", "ivec3", "float"]), InvalidTexFuncCase("textureOffset", ["sampler2DArray", "vec3", "ivec3"]), InvalidTexFuncCase("textureOffset", ["sampler2DArray", "vec3", "ivec3", "float"]), InvalidTexFuncCase("textureOffset", ["samplerCubeShadow", "vec4", "ivec2"]), InvalidTexFuncCase("textureOffset", ["samplerCubeShadow", "vec4", "ivec3"]), InvalidTexFuncCase("textureOffset", ["sampler2DArrayShadow", "vec4", "ivec2"]), InvalidTexFuncCase("textureOffset", ["sampler2DArrayShadow", "vec4", "ivec2", "float"]), # texelFetch InvalidTexFuncCase("texelFetch", ["samplerCube", "ivec3", "int"]), InvalidTexFuncCase("texelFetch", ["isamplerCube", "ivec3", "int"]), InvalidTexFuncCase("texelFetch", ["usamplerCube", "ivec3", "int"]), InvalidTexFuncCase("texelFetch", ["sampler2DShadow", "ivec2", "int"]), InvalidTexFuncCase("texelFetch", ["samplerCubeShadow", "ivec3", "int"]), InvalidTexFuncCase("texelFetch", ["sampler2DArrayShadow", "ivec3", "int"]), # texelFetchOffset InvalidTexFuncCase("texelFetch", ["samplerCube", "ivec3", "int", "ivec3"]), InvalidTexFuncCase("texelFetch", ["sampler2DShadow", "ivec2", "int", "ivec2"]), InvalidTexFuncCase("texelFetch", ["samplerCubeShadow", "ivec3", "int", "ivec3"]), InvalidTexFuncCase("texelFetch", ["sampler2DArrayShadow", "ivec3", "int", "ivec3"]), # textureProjOffset InvalidTexFuncCase("textureProjOffset", ["samplerCube", "vec4", "ivec2"]), InvalidTexFuncCase("textureProjOffset", ["samplerCube", "vec4", "ivec3"]), InvalidTexFuncCase("textureProjOffset", ["samplerCubeShadow", "vec4", "ivec3"]), InvalidTexFuncCase("textureProjOffset", ["sampler2DArrayShadow", "vec4", "ivec2"]), InvalidTexFuncCase("textureProjOffset", ["sampler2DArrayShadow", "vec4", "ivec3"]), # textureLodOffset InvalidTexFuncCase("textureLodOffset", ["samplerCube", "vec3", "float", "ivec2"]), InvalidTexFuncCase("textureLodOffset", ["samplerCube", "vec3", "float", "ivec3"]), InvalidTexFuncCase("textureLodOffset", ["samplerCubeShadow", "vec3", "float", "ivec3"]), InvalidTexFuncCase("textureLodOffset", ["sampler2DArrayShadow", "vec3", "float", "ivec2"]), InvalidTexFuncCase("textureLodOffset", ["sampler2DArrayShadow", "vec3", "float", "ivec3"]), # textureProjLod InvalidTexFuncCase("textureProjLod", ["samplerCube", "vec4", "float"]), InvalidTexFuncCase("textureProjLod", ["sampler2DArray", "vec4", "float"]), InvalidTexFuncCase("textureProjLod", ["sampler2DArrayShadow", "vec4", "float"]), # textureGrad InvalidTexFuncCase("textureGrad", ["sampler2DArray", "vec3", "vec3", "vec3"]), # textureGradOffset InvalidTexFuncCase("textureGradOffset", ["samplerCube", "vec3", "vec3", "vec3", "ivec2"]), InvalidTexFuncCase("textureGradOffset", ["samplerCube", "vec3", "vec3", "vec3", "ivec3"]), InvalidTexFuncCase("textureGradOffset", ["samplerCubeShadow", "vec4", "vec3", "vec3", "ivec2"]), InvalidTexFuncCase("textureGradOffset", ["samplerCubeShadow", "vec4", "vec3", "vec3", "ivec3"]), # textureProjGrad InvalidTexFuncCase("textureProjGrad", ["samplerCube", "vec4", "vec3", "vec3"]), InvalidTexFuncCase("textureProjGrad", ["sampler2DArray", "vec4", "vec2", "vec2"]), # textureProjGradOffset InvalidTexFuncCase("textureProjGradOffset", ["samplerCube", "vec4", "vec3", "vec3", "ivec2"]), InvalidTexFuncCase("textureProjGradOffset", ["samplerCube", "vec4", "vec3", "vec3", "ivec3"]), InvalidTexFuncCase("textureProjGradOffset", ["sampler2DArray", "vec4", "vec2", "vec2", "ivec2"]), InvalidTexFuncCase("textureProjGradOffset", ["sampler2DArray", "vec4", "vec2", "vec2", "ivec3"]) ] if __name__ == "__main__": print "Generating shader case files." writeAllCases("invalid_texture_functions.test", INVALID_TEX_FUNC_CASES)
apache-2.0
wking/swc-amy
workshops/migrations/0040_add_country_to_online_events.py
3
1070
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def add_country_to_online_events(apps, schema_editor): """Add an 'Online' country to all events tagged with 'online' tag.""" Event = apps.get_model('workshops', 'Event') Tag = apps.get_model('workshops', 'Tag') online, _ = Tag.objects.get_or_create( name='online', defaults={'details': 'Events taking place entirely online'}, ) # Oceanic Pole of Inaccessibility coordinates: # https://en.wikipedia.org/wiki/Pole_of_inaccessibility#Oceanic_pole_of_inaccessibility latitude = -48.876667 longitude = -123.393333 Event.objects.filter(country__isnull=True, tags__in=[online]) \ .update(country='W3', latitude=latitude, longitude=longitude, venue='Internet') class Migration(migrations.Migration): dependencies = [ ('workshops', '0039_add_permission_groups'), ] operations = [ migrations.RunPython(add_country_to_online_events), ]
mit
stevenewey/django
django/contrib/admin/helpers.py
12
14304
from __future__ import unicode_literals import warnings from django import forms from django.conf import settings from django.contrib.admin.templatetags.admin_static import static from django.contrib.admin.utils import ( display_for_field, flatten_fieldsets, help_text_for_field, label_for_field, lookup_field, ) from django.core.exceptions import ObjectDoesNotExist from django.db.models.fields.related import ManyToManyRel from django.forms.utils import flatatt from django.template.defaultfilters import capfirst, linebreaksbr from django.utils import six from django.utils.deprecation import RemovedInDjango20Warning from django.utils.encoding import force_text, smart_text from django.utils.functional import cached_property from django.utils.html import conditional_escape, format_html from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ ACTION_CHECKBOX_NAME = '_selected_action' class ActionForm(forms.Form): action = forms.ChoiceField(label=_('Action:')) select_across = forms.BooleanField(label='', required=False, initial=0, widget=forms.HiddenInput({'class': 'select-across'})) checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False) class AdminForm(object): def __init__(self, form, fieldsets, prepopulated_fields, readonly_fields=None, model_admin=None): self.form, self.fieldsets = form, fieldsets self.prepopulated_fields = [{ 'field': form[field_name], 'dependencies': [form[f] for f in dependencies] } for field_name, dependencies in prepopulated_fields.items()] self.model_admin = model_admin if readonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields def __iter__(self): for name, options in self.fieldsets: yield Fieldset( self.form, name, readonly_fields=self.readonly_fields, model_admin=self.model_admin, **options ) def _media(self): media = self.form.media for fs in self: media = media + fs.media return media media = property(_media) class Fieldset(object): def __init__(self, form, name=None, readonly_fields=(), fields=(), classes=(), description=None, model_admin=None): self.form = form self.name, self.fields = name, fields self.classes = ' '.join(classes) self.description = description self.model_admin = model_admin self.readonly_fields = readonly_fields def _media(self): if 'collapse' in self.classes: extra = '' if settings.DEBUG else '.min' js = ['jquery%s.js' % extra, 'jquery.init.js', 'collapse%s.js' % extra] return forms.Media(js=[static('admin/js/%s' % url) for url in js]) return forms.Media() media = property(_media) def __iter__(self): for field in self.fields: yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin) class Fieldline(object): def __init__(self, form, field, readonly_fields=None, model_admin=None): self.form = form # A django.forms.Form instance if not hasattr(field, "__iter__") or isinstance(field, six.text_type): self.fields = [field] else: self.fields = field self.has_visible_field = not all(field in self.form.fields and self.form.fields[field].widget.is_hidden for field in self.fields) self.model_admin = model_admin if readonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields def __iter__(self): for i, field in enumerate(self.fields): if field in self.readonly_fields: yield AdminReadonlyField(self.form, field, is_first=(i == 0), model_admin=self.model_admin) else: yield AdminField(self.form, field, is_first=(i == 0)) def errors(self): return mark_safe( '\n'.join(self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields).strip('\n') ) class AdminField(object): def __init__(self, form, field, is_first): self.field = form[field] # A django.forms.BoundField instance self.is_first = is_first # Whether this field is first on the line self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput) self.is_readonly = False def label_tag(self): classes = [] contents = conditional_escape(force_text(self.field.label)) if self.is_checkbox: classes.append('vCheckboxLabel') if self.field.field.required: classes.append('required') if not self.is_first: classes.append('inline') attrs = {'class': ' '.join(classes)} if classes else {} # checkboxes should not have a label suffix as the checkbox appears # to the left of the label. return self.field.label_tag(contents=mark_safe(contents), attrs=attrs, label_suffix='' if self.is_checkbox else None) def errors(self): return mark_safe(self.field.errors.as_ul()) class AdminReadonlyField(object): def __init__(self, form, field, is_first, model_admin=None): # Make self.field look a little bit like a field. This means that # {{ field.name }} must be a useful class name to identify the field. # For convenience, store other field-related data here too. if callable(field): class_name = field.__name__ if field.__name__ != '<lambda>' else '' else: class_name = field if form._meta.labels and class_name in form._meta.labels: label = form._meta.labels[class_name] else: label = label_for_field(field, form._meta.model, model_admin) if form._meta.help_texts and class_name in form._meta.help_texts: help_text = form._meta.help_texts[class_name] else: help_text = help_text_for_field(class_name, form._meta.model) self.field = { 'name': class_name, 'label': label, 'help_text': help_text, 'field': field, } self.form = form self.model_admin = model_admin self.is_first = is_first self.is_checkbox = False self.is_readonly = True def label_tag(self): attrs = {} if not self.is_first: attrs["class"] = "inline" label = self.field['label'] return format_html('<label{}>{}:</label>', flatatt(attrs), capfirst(force_text(label))) def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f) return conditional_escape(result_repr) class InlineAdminFormSet(object): """ A wrapper around an inline formset for use in the admin system. """ def __init__(self, inline, formset, fieldsets, prepopulated_fields=None, readonly_fields=None, model_admin=None): self.opts = inline self.formset = formset self.fieldsets = fieldsets self.model_admin = model_admin if readonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields if prepopulated_fields is None: prepopulated_fields = {} self.prepopulated_fields = prepopulated_fields def __iter__(self): for form, original in zip(self.formset.initial_forms, self.formset.get_queryset()): view_on_site_url = self.opts.get_view_on_site_url(original) yield InlineAdminForm(self.formset, form, self.fieldsets, self.prepopulated_fields, original, self.readonly_fields, model_admin=self.opts, view_on_site_url=view_on_site_url) for form in self.formset.extra_forms: yield InlineAdminForm(self.formset, form, self.fieldsets, self.prepopulated_fields, None, self.readonly_fields, model_admin=self.opts) yield InlineAdminForm(self.formset, self.formset.empty_form, self.fieldsets, self.prepopulated_fields, None, self.readonly_fields, model_admin=self.opts) def fields(self): fk = getattr(self.formset, "fk", None) for i, field_name in enumerate(flatten_fieldsets(self.fieldsets)): if fk and fk.name == field_name: continue if field_name in self.readonly_fields: yield { 'label': label_for_field(field_name, self.opts.model, self.opts), 'widget': { 'is_hidden': False }, 'required': False, 'help_text': help_text_for_field(field_name, self.opts.model), } else: yield self.formset.form.base_fields[field_name] def _media(self): media = self.opts.media + self.formset.media for fs in self: media = media + fs.media return media media = property(_media) class InlineAdminForm(AdminForm): """ A wrapper around an inline form for use in the admin system. """ def __init__(self, formset, form, fieldsets, prepopulated_fields, original, readonly_fields=None, model_admin=None, view_on_site_url=None): self.formset = formset self.model_admin = model_admin self.original = original self.show_url = original and view_on_site_url is not None self.absolute_url = view_on_site_url super(InlineAdminForm, self).__init__(form, fieldsets, prepopulated_fields, readonly_fields, model_admin) @cached_property def original_content_type_id(self): warnings.warn( 'InlineAdminForm.original_content_type_id is deprecated and will be ' 'removed in Django 2.0. If you were using this attribute to construct ' 'the "view on site" URL, use the `absolute_url` attribute instead.', RemovedInDjango20Warning, stacklevel=2 ) if self.original is not None: # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level. from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(self.original).pk raise AttributeError def __iter__(self): for name, options in self.fieldsets: yield InlineFieldset(self.formset, self.form, name, self.readonly_fields, model_admin=self.model_admin, **options) def needs_explicit_pk_field(self): # Auto fields are editable (oddly), so need to check for auto or non-editable pk if self.form._meta.model._meta.has_auto_field or not self.form._meta.model._meta.pk.editable: return True # Also search any parents for an auto field. (The pk info is propagated to child # models so that does not need to be checked in parents.) for parent in self.form._meta.model._meta.get_parent_list(): if parent._meta.has_auto_field: return True return False def pk_field(self): return AdminField(self.form, self.formset._pk_field.name, False) def fk_field(self): fk = getattr(self.formset, "fk", None) if fk: return AdminField(self.form, fk.name, False) else: return "" def deletion_field(self): from django.forms.formsets import DELETION_FIELD_NAME return AdminField(self.form, DELETION_FIELD_NAME, False) def ordering_field(self): from django.forms.formsets import ORDERING_FIELD_NAME return AdminField(self.form, ORDERING_FIELD_NAME, False) class InlineFieldset(Fieldset): def __init__(self, formset, *args, **kwargs): self.formset = formset super(InlineFieldset, self).__init__(*args, **kwargs) def __iter__(self): fk = getattr(self.formset, "fk", None) for field in self.fields: if fk and fk.name == field: continue yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin) class AdminErrorList(forms.utils.ErrorList): """ Stores all errors for the form/formsets in an add/change stage view. """ def __init__(self, form, inline_formsets): super(AdminErrorList, self).__init__() if form.is_bound: self.extend(form.errors.values()) for inline_formset in inline_formsets: self.extend(inline_formset.non_form_errors()) for errors_in_inline_form in inline_formset.errors: self.extend(errors_in_inline_form.values())
bsd-3-clause
NSLS-II/channelarchiver
tests/test_archiver.py
1
11262
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from channelarchiver import Archiver, codes, utils, exceptions from channelarchiver.models import ChannelData, ArchiveProperties from tests.mock_archiver import MockArchiver import datetime import pytest utc = utils.UTC() local_tz = utils.local_tz class TestArchiver(unittest.TestCase): def setUp(self): self.archiver = Archiver('http://fake') self.archiver.archiver = MockArchiver() def test_scan_archives_all(self): self.archiver.scan_archives() archives_for_channel = self.archiver.archives_for_channel try: data = self.archiver.get('XF:23IDA-VA:0{DP:1-IP:1}P-I', '2013-08-11', '2013-08-12') print(data) except exceptions.ChannelNotFound: pytest.skip('Cannot test channel archiver at NSLS2. You are likely' ' not testing from inside the nsls2 firewall') self.assertTrue('EXAMPLE:DOUBLE_SCALAR{TD:1}' in archives_for_channel) self.assertTrue('EXAMPLE:INT_WAVEFORM' in archives_for_channel) self.assertTrue('EXAMPLE:ENUM_SCALAR' in archives_for_channel) self.assertEqual( archives_for_channel, { 'EXAMPLE:DOUBLE_SCALAR{TD:1}': [ ArchiveProperties( key=1001, start_time=datetime.datetime(2012, 7, 12, 21, 47, 23, 664000, tzinfo=utc), end_time=datetime.datetime(2012, 7, 13, 11, 18, 55, 671259, tzinfo=utc) ) ], 'EXAMPLE:INT_WAVEFORM': [ ArchiveProperties( key=1001, start_time=datetime.datetime(2012, 7, 12, 23, 14, 19, 129600, tzinfo=utc), end_time=datetime.datetime(2012, 7, 13, 8, 26, 18, 558211, tzinfo=utc) ) ], 'EXAMPLE:ENUM_SCALAR': [ ArchiveProperties( key=1008, start_time=datetime.datetime(2012, 7, 12, 22, 41, 10, 765676, tzinfo=utc), end_time=datetime.datetime(2012, 7, 13, 9, 20, 23, 623789, tzinfo=utc) ) ] } ) def test_scan_archives_one(self): self.archiver.scan_archives('EXAMPLE:DOUBLE_SCALAR{TD:1}') archives_for_channel = self.archiver.archives_for_channel.keys() self.assertTrue('EXAMPLE:DOUBLE_SCALAR{TD:1}' in archives_for_channel) self.assertFalse('EXAMPLE:INT_WAVEFORM' in archives_for_channel) self.assertFalse('EXAMPLE:ENUM_SCALAR' in archives_for_channel) def test_scan_archives_list(self): self.archiver.scan_archives(['EXAMPLE:DOUBLE_SCALAR{TD:1}', 'EXAMPLE:ENUM_SCALAR']) archives_for_channel = self.archiver.archives_for_channel.keys() self.assertTrue('EXAMPLE:DOUBLE_SCALAR{TD:1}' in archives_for_channel) self.assertFalse('EXAMPLE:INT_WAVEFORM' in archives_for_channel) self.assertTrue('EXAMPLE:ENUM_SCALAR' in archives_for_channel) def test_get_scalar(self): start = datetime.datetime(2012, 1, 1, tzinfo=utc) end = datetime.datetime(2013, 1, 1, tzinfo=utc) data = self.archiver.get(['EXAMPLE:DOUBLE_SCALAR{TD:1}'], start, end, interpolation=codes.interpolation.RAW) self.assertTrue(isinstance(data, list)) channel_data = data[0] self.assertEqual(channel_data.channel, 'EXAMPLE:DOUBLE_SCALAR{TD:1}') self.assertEqual(channel_data.data_type, codes.data_type.DOUBLE) self.assertEqual(channel_data.elements, 1) self.assertEqual(channel_data.values, [ 200.5, 199.9, 198.7, 196.1 ]) self.assertEqual(channel_data.times, [ datetime.datetime(2012, 7, 12, 21, 47, 23, 664000, utc), datetime.datetime(2012, 7, 13, 2, 5, 1, 443589, utc), datetime.datetime(2012, 7, 13, 7, 19, 31, 806097, utc), datetime.datetime(2012, 7, 13, 11, 18, 55, 671259, utc) ]) self.assertEqual(channel_data.statuses, [0, 6, 6, 5]) self.assertEqual(channel_data.severities, [0, 1, 1, 2]) self.assertEqual(repr(channel_data.times[0].tzinfo), 'UTC()') def test_get_interpolation_string(self): start = datetime.datetime(2012, 1, 1, tzinfo=utc) end = datetime.datetime(2013, 1, 1, tzinfo=utc) channel_data = self.archiver.get('EXAMPLE:DOUBLE_SCALAR{TD:1}', start, end, interpolation='raw') self.assertEqual(channel_data.channel, 'EXAMPLE:DOUBLE_SCALAR{TD:1}') self.assertEqual(channel_data.values, [ 200.5, 199.9, 198.7, 196.1 ]) def test_get_scalar_str(self): start = datetime.datetime(2012, 1, 1, tzinfo=utc) end = datetime.datetime(2013, 1, 1, tzinfo=utc) channel_data = self.archiver.get('EXAMPLE:DOUBLE_SCALAR{TD:1}', start, end, interpolation=codes.interpolation.RAW) self.assertTrue(isinstance(channel_data, ChannelData)) self.assertEqual(channel_data.channel, 'EXAMPLE:DOUBLE_SCALAR{TD:1}') self.assertEqual(channel_data.data_type, codes.data_type.DOUBLE) def test_get_scalar_in_tz(self): start = datetime.datetime(2012, 1, 1, tzinfo=utc) end = datetime.datetime(2013, 1, 1, tzinfo=utc) data = self.archiver.get('EXAMPLE:DOUBLE_SCALAR{TD:1}', start, end, interpolation=codes.interpolation.RAW, tz=utils.UTC(11.5)) self.assertEqual(str(data.times[0].tzinfo), 'UTC+11:30') self.assertEqual(repr(data.times[0].tzinfo), 'UTC(+11.5)') def test_get_without_scan(self): start = datetime.datetime(2012, 1, 1, tzinfo=utc) end = datetime.datetime(2013, 1, 1, tzinfo=utc) self.assertRaises(exceptions.ChannelNotFound, self.archiver.get, ['EXAMPLE:DOUBLE_SCALAR{TD:1}'], start, end, interpolation=codes.interpolation.RAW, scan_archives=False) def test_get_with_restrictive_interval(self): start = datetime.datetime(2012, 7, 13, tzinfo=utc) end = datetime.datetime(2012, 7, 13, 10, tzinfo=utc) channel_data = self.archiver.get('EXAMPLE:DOUBLE_SCALAR{TD:1}', start, end, interpolation=codes.interpolation.RAW) self.assertEqual(channel_data.values, [ 199.9, 198.7 ]) self.assertEqual(channel_data.times, [ datetime.datetime(2012, 7, 13, 2, 5, 1, 443589, utc), datetime.datetime(2012, 7, 13, 7, 19, 31, 806097, utc) ]) def test_get_with_restrictive_interval_with_tzs(self): start = datetime.datetime(2012, 7, 13, 10, tzinfo=utils.UTC(10)) end = datetime.datetime(2012, 7, 13, 20, tzinfo=utils.UTC(10)) channel_data = self.archiver.get('EXAMPLE:DOUBLE_SCALAR{TD:1}', start, end, interpolation=codes.interpolation.RAW) self.assertEqual(channel_data.values, [ 199.9, 198.7 ]) self.assertEqual(channel_data.times, [ datetime.datetime(2012, 7, 13, 2, 5, 1, 443589, utc), datetime.datetime(2012, 7, 13, 7, 19, 31, 806097, utc) ]) self.assertEqual(repr(channel_data.times[0].tzinfo), 'UTC(+10)') def test_get_with_str_times(self): start = '2012-07-13 00:00:00Z' end = '2012-07-13 10:00:00Z' channel_data = self.archiver.get('EXAMPLE:DOUBLE_SCALAR{TD:1}', start, end, interpolation=codes.interpolation.RAW) self.assertEqual(channel_data.values, [ 199.9, 198.7 ]) self.assertEqual(channel_data.times, [ datetime.datetime(2012, 7, 13, 2, 5, 1, 443589, utc), datetime.datetime(2012, 7, 13, 7, 19, 31, 806097, utc) ]) def test_get_with_str_times_incl_tz(self): start = '2012-07-13 10:00:00+10:00' end = '2012-07-13 20:00:00+10:00' channel_data = self.archiver.get('EXAMPLE:DOUBLE_SCALAR{TD:1}', start, end, interpolation=codes.interpolation.RAW) self.assertEqual(channel_data.values, [ 199.9, 198.7 ]) self.assertEqual(channel_data.times, [ datetime.datetime(2012, 7, 13, 2, 5, 1, 443589, utc), datetime.datetime(2012, 7, 13, 7, 19, 31, 806097, utc) ]) self.assertEqual(repr(channel_data.times[0].tzinfo), 'UTC(+10)') def test_get_waveform(self): start = datetime.datetime(2012, 1, 1) end = datetime.datetime(2013, 1, 1) channel_data = self.archiver.get( 'EXAMPLE:INT_WAVEFORM', start, end, interpolation=codes.interpolation.RAW) self.assertEqual(channel_data.channel, 'EXAMPLE:INT_WAVEFORM') self.assertEqual(channel_data.data_type, codes.data_type.INT) self.assertEqual(channel_data.elements, 3) self.assertEqual(channel_data.values, [ [3, 5, 13], [2, 4, 11], [0, 7, 1] ]) def test_get_enum(self): start = datetime.datetime(2012, 1, 1) end = datetime.datetime(2013, 1, 1) channel_data = self.archiver.get( 'EXAMPLE:ENUM_SCALAR', start, end, interpolation=codes.interpolation.RAW) self.assertEqual(channel_data.channel, 'EXAMPLE:ENUM_SCALAR') self.assertEqual(channel_data.data_type, codes.data_type.ENUM) self.assertEqual(channel_data.values, [7, 1, 8]) def test_get_multiple(self): start = datetime.datetime(2012, 1, 1) end = datetime.datetime(2013, 1, 1) data = self.archiver.get( ['EXAMPLE:DOUBLE_SCALAR{TD:1}', 'EXAMPLE:INT_WAVEFORM', 'EXAMPLE:ENUM_SCALAR'], start, end, interpolation=codes.interpolation.RAW) self.assertTrue(isinstance(data, list)) self.assertEqual(data[0].channel, 'EXAMPLE:DOUBLE_SCALAR{TD:1}') self.assertEqual(data[1].channel, 'EXAMPLE:INT_WAVEFORM') self.assertEqual(data[2].channel, 'EXAMPLE:ENUM_SCALAR') self.assertEqual(data[0].values, [ 200.5, 199.9, 198.7, 196.1 ]) self.assertEqual(data[1].values, [[3, 5, 13], [2, 4, 11], [0, 7, 1]]) self.assertEqual(data[2].values, [7, 1, 8]) def test_get_with_wrong_number_of_keys(self): start = datetime.datetime(2012, 1, 1) end = datetime.datetime(2013, 1, 1) self.assertRaises(exceptions.ChannelKeyMismatch, self.archiver.get, [ 'EXAMPLE:DOUBLE_SCALAR{TD:1}' ], start, end, archive_keys=[1001, 1008], interpolation=codes.interpolation.RAW) if __name__ == '__main__': unittest.main()
mit
maxpumperla/elephas
tests/utils/test_model_utils.py
1
1051
import pytest from elephas.utils.model_utils import ModelType, LossModelTypeMapper @pytest.mark.parametrize('loss, model_type', [('binary_crossentropy', ModelType.CLASSIFICATION), ('mean_squared_error', ModelType.REGRESSION), ('categorical_crossentropy', ModelType.CLASSIFICATION), ('mean_absolute_error', ModelType.REGRESSION)]) def test_model_type_mapper(loss, model_type): assert LossModelTypeMapper().get_model_type(loss) == model_type def test_model_type_mapper_custom(): LossModelTypeMapper().register_loss('test', ModelType.REGRESSION) assert LossModelTypeMapper().get_model_type('test') == ModelType.REGRESSION def test_model_type_mapper_custom_callable(): def custom_loss(y_true, y_pred): return y_true - y_pred LossModelTypeMapper().register_loss(custom_loss, ModelType.REGRESSION) assert LossModelTypeMapper().get_model_type('custom_loss') == ModelType.REGRESSION
mit
pythonchelle/opencomparison
apps/package/templatetags/package_tags.py
3
2014
from datetime import datetime, timedelta from django import template from package.models import Commit from package.context_processors import used_packages_list register = template.Library() from django.core.cache import cache class ParticipantURLNode(template.Node): def __init__(self, repo, participant): self.repo = template.Variable(repo) self.participant = template.Variable(participant) def render(self, context): repo = self.repo.resolve(context) participant = self.participant.resolve(context) if repo.user_url: user_url = repo.user_url % participant else: user_url = '%s/%s' % (repo.url, participant) return user_url @register.tag def participant_url(parser, token): try: tag_name, repo, participant = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0] return ParticipantURLNode(repo, participant) @register.filter def commits_over_52(package): now = datetime.now() commits = Commit.objects.filter( package=package, commit_date__gt=now - timedelta(weeks=52), ).values_list('commit_date', flat=True) weeks = [0] * 52 for cdate in commits: age_weeks = (now - cdate).days // 7 if age_weeks < 52: weeks[age_weeks] += 1 return ','.join(map(str,reversed(weeks))) @register.inclusion_tag('package/templatetags/_usage_button.html', takes_context=True) def usage_button(context): response = used_packages_list(context['request']) response['STATIC_URL'] = context['STATIC_URL'] response['package'] = context['package'] if context['package'].pk in response['used_packages_list']: response['usage_action'] = "remove" response['image'] = "usage_triangle_filled" else: response['usage_action'] = "add" response['image'] = "usage_triangle_hollow" return response
mit
SunguckLee/MariaDB
storage/tokudb/mysql-test/tokudb/t/change_column_int_key.py
56
1671
#!/usr/bin/env python import sys def gen_test(types): for a in range(len(types)): for b in range(len(types)): if a < b: print print "CREATE TABLE t (a %s, PRIMARY KEY(a));" % (types[a]) print "--replace_regex /MariaDB/XYZ/ /MySQL/XYZ/" print "--error ER_UNSUPPORTED_EXTENSION" print "ALTER TABLE t CHANGE COLUMN a a %s;" % (types[b]) print "DROP TABLE t;" print "CREATE TABLE t (a %s, KEY(a));" % (types[a]) print "--replace_regex /MariaDB/XYZ/ /MySQL/XYZ/" print "--error ER_UNSUPPORTED_EXTENSION" print "ALTER TABLE t CHANGE COLUMN a a %s;" % (types[b]) print "DROP TABLE t;" print "CREATE TABLE t (a %s, CLUSTERING KEY(a));" % (types[a]) print "--replace_regex /MariaDB/XYZ/ /MySQL/XYZ/" print "--error ER_UNSUPPORTED_EXTENSION" print "ALTER TABLE t CHANGE COLUMN a a %s;" % (types[b]) print "DROP TABLE t;" def main(): print "# this test is generated by change_int_key.py" print "# ensure that changing an int column that is part of a key is not hot" print "--disable_warnings" print "DROP TABLE IF EXISTS t;" print "--enable_warnings" print "SET SESSION DEFAULT_STORAGE_ENGINE=\"TokuDB\";" print "SET SESSION TOKUDB_DISABLE_SLOW_ALTER=1;" gen_test([ "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT" ]) gen_test([ "TINYINT UNSIGNED", "SMALLINT UNSIGNED", "MEDIUMINT UNSIGNED", "INT UNSIGNED", "BIGINT UNSIGNED" ]) return 0 sys.exit(main())
gpl-2.0
windyuuy/opera
chromium/src/chrome/common/extensions/docs/server2/persistent_object_store_test.py
117
1737
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from persistent_object_store import PersistentObjectStore import unittest class PersistentObjectStoreTest(unittest.TestCase): '''Tests for PersistentObjectStore. These are all a bit contrived because ultimately it comes down to our use of the appengine datastore API, and we mock it out for tests anyway. Who knows whether it's correct. ''' def testPersistence(self): # First object store. object_store = PersistentObjectStore('test') object_store.Set('key', 'value') self.assertEqual('value', object_store.Get('key').Get()) # Other object store should have it too. another_object_store = PersistentObjectStore('test') self.assertEqual('value', another_object_store.Get('key').Get()) # Setting in the other store should set in both. mapping = {'key2': 'value2', 'key3': 'value3'} another_object_store.SetMulti(mapping) self.assertEqual(mapping, object_store.GetMulti(mapping.keys()).Get()) self.assertEqual(mapping, another_object_store.GetMulti(mapping.keys()).Get()) # And delete. object_store.DelMulti(mapping.keys()) self.assertEqual({}, object_store.GetMulti(mapping.keys()).Get()) self.assertEqual({}, another_object_store.GetMulti(mapping.keys()).Get()) def testNamespaceIsolation(self): object_store = PersistentObjectStore('test') another_object_store = PersistentObjectStore('another') object_store.Set('key', 'value') self.assertEqual(None, another_object_store.Get('key').Get()) if __name__ == '__main__': unittest.main()
bsd-3-clause
quasipedia/swaggery
swaggery/checker.py
1
9830
#! /usr/bin/env python3 '''A code linter/checker for user-defined APIs. This module will try to detect common errors that might be done while coding an API, such as forgetting to define a path, or defining optional path parameters, or... Usage: checker.py <API-DIRECTORY> ... It is possible to perform the checks on multiple directories at once. ''' import os import re import sys import pkgutil import inspect from importlib import import_module from docopt import docopt from . import utils from .logger import log from .keywords import * # A regex that can extract HTTP status codes from source code of a method. HTTP_STATUSES_REGEX = re.compile(r'Respond\( *(\d\d\d)') class Checker(object): '''An abstract class that allow for defining checks as methods. Each check should have the same signature, so that `check_all` can iterate over them. Checks follow an unix-like convention of returning a value that evaluate to False if the for no error conditions, and a value evaluating to True (namely a list of error messages) if such conditions arise. ''' @property def checks(self): '''Return the list of all check methods.''' condition = lambda a: a.startswith('check_') return (getattr(self, a) for a in dir(self) if condition(a)) def __call__(self, *args, **kwargs): '''Perform all checks in the Checker class.''' err_messages = [] for ch in self.checks: msgs = ch(*args, **kwargs) if msgs: err_messages.extend(msgs) for em in err_messages: log.critical(em) return err_messages class ApiChecker(Checker): '''A checker for the Api class.''' def check_has_docstring(self, api): '''An API class must have a docstring.''' if not api.__doc__: msg = 'The Api class "{}" lacks a docstring.' return [msg.format(api.__name__)] def check_has_version(self, api): '''An API class must have a `version` attribute.''' if not hasattr(api, 'version'): msg = 'The Api class "{}" lacks a `version` attribute.' return [msg.format(api.__name__)] def check_has_path(self, api): '''An API class must have a `path` attribute.''' if not hasattr(api, 'path'): msg = 'The Api class "{}" lacks a `path` attribute.' return [msg.format(api.__name__)] class ResourceMethodChecker(Checker): '''A checker for individual methods in the Resource class.''' def check_docstring(self, method): '''All methods should have a docstring.''' mn = method.__name__ if method.__doc__ is None: return ['Missing docstring for method "{}"'.format(mn)] def check_return_types(self, method): '''Return types must be correct, their codes must match actual use.''' mn = method.__name__ retanno = method.__annotations__.get('return', None) # Take a look at the syntax if not retanno: return ['Missing return types for method "{}"'.format(mn)] if not isinstance(retanno, (list, tuple)): msg = 'Return annotation for method "{}" not tuple nor list' return [msg.format(mn)] if (any(map(lambda t: not isinstance(t, (list, tuple)), retanno)) or any(map(lambda t: not (2 <= len(t) <= 3), retanno))): msg = ('Return values series for "{}" should be composed of ' '2 or 3-items tuples (code, msg, type).') return [msg.format(mn)] errors = [] # Take a look at the codes declared = set([t[0] for t in retanno]) actual = set(int(s) for s in HTTP_STATUSES_REGEX.findall(method.source)) if declared != actual: if declared.issubset(actual): msg = 'Method {} returns undeclared codes: {}.' errors.append(msg.format(mn, actual - declared)) elif actual.issubset(declared): msg = 'Method {} declares codes {} that are never used.' errors.append(msg.format(mn, declared - actual)) else: msg = 'Declared {} and Used {} codes mismatch.' errors.append(msg.format(declared, actual)) # Take a look at the types ret_with_types = filter(lambda t: len(t) == 3, retanno) msg = 'Method {} return type for code {} must be class (not instance).' msg_mod = 'Method {} return type for code {} must subclass from Model.' for code, _, type_ in ret_with_types: try: if Model not in type_.__bases__: errors.append(msg_mod.format(mn, code)) except AttributeError: errors.append(msg.format(mn, code)) return errors def check_params_types(self, method): '''Types in argument annotations must be instances, not classes.''' mn = method.__name__ annos = dict(method.__annotations__) errors = [] # Take a look at the syntax msg_tuple = 'Parameter {} in method {} is not annotated with a tuple.' msg_ptype = 'Parameter {} in method {} is not a valid Ptype.' msg_mod = 'Type for param {} in method {} must descend from Model.' msg_cls = 'Type for param {} in method {} must be instance (not class)' bodies = [] for pname, anno in annos.items(): if pname == 'return': continue elif len(anno) != 2: errors.append(msg_tuple.format(pname, mn)) else: param_type, value_type = anno if param_type not in Ptypes: errors.append(msg_ptype.format(pname, mn)) elif param_type == 'body': bodies.append(pname) elif param_type == 'path': default = method.signature.parameters[pname].default if default is not inspect._empty: msg = ('Path prameter {} in method {} has a default ' 'value ({}) that would make it optional (which ' 'is wrong!)') errors.append(msg.format(pname, mn, default)) if hasattr(value_type, '__bases__'): errors.append(msg_cls.format(pname, mn)) elif Model not in value_type.__class__.__bases__: errors.append(msg_mod.format(pname, mn)) # Only one body parameter! if len(bodies) > 1: msg = 'Too many "Ptypes.body" params {} for method {} (max=1).' errors.append(msg.format(bodies, mn)) return errors class ResourceChecker(Checker): '''A checker for the Resource class.''' path_params_regex = re.compile(r'<(.*?)>') def check_path_consistency(self, resource): '''Path arguments must be consistent for all methods.''' msg = ('Method "{}" path variables {}) do not conform with the ' 'resource subpath declaration ({}).') errors = [] # If subpath is not set, it will be detected by another checker if resource.subpath is None: return errors declared = sorted(self.path_params_regex.findall(resource.subpath)) for callback in resource.callbacks: actual = sorted(utils.filter_annotations_by_ptype( callback, Ptypes.path)) if declared == actual: continue errors.append(msg.format( '{}.{}'.format(resource.__name__, callback.__name__), actual, resource.subpath)) return errors def check_no_multiple_handlers(self, resource): '''The same verb cannot be repeated on several endpoints.''' seen = [] errors = [] msg = 'HTTP verb "{}" associated to more than one endpoint in "{}".' for method in resource.callbacks: for op in getattr(method, 'swagger_ops'): if op in seen: errors.append(msg.format(op, resource.__name__)) else: seen.append(op) return errors def check_methods(self, resource): '''Iteratively check all methods (endpoints) in the Resource.''' checker = ResourceMethodChecker() errors = [] for callback in resource.callbacks: new_errors = checker(callback) if new_errors: errors.extend(new_errors) return errors def main(directories): '''Perform all checks on the API's contained in `directory`.''' msg = 'Checking module "{}" from directory "{}" for coding errors.' api_checker = ApiChecker() resource_checker = ResourceChecker() errors = [] modules = [] for loader, mname, _ in pkgutil.walk_packages(directories): sys.path.append(os.path.abspath(loader.path)) log.info(msg.format(mname, loader.path)) modules.append(mname) import_module(mname) for api in Api: if api.__module__.split('.')[-1] not in modules: continue log.debug('Anlysing Api class: {}'.format(api.__name__)) errors.extend(api_checker(api)) for res in Resource: if res.__module__.split('.')[-1] not in modules: continue log.debug('Anlysing Resource class: {}'.format(res.__name__)) errors.extend(resource_checker(res)) else: log.info('All modules tested, no problem detected.') return errors # TODO: Add a checker class for Models. if __name__ == '__main__': from logging import INFO arguments = docopt(__doc__) log.setLevel(INFO) errors = main(arguments['<API-DIRECTORY>'])
agpl-3.0
Kazade/NeHe-Website
google_appengine/lib/django-1.2/tests/regressiontests/forms/localflavor/cl.py
86
2290
from django.contrib.localflavor.cl.forms import CLRutField, CLRegionSelect from django.core.exceptions import ValidationError from utils import LocalFlavorTestCase class CLLocalFlavorTests(LocalFlavorTestCase): def test_CLRegionSelect(self): f = CLRegionSelect() out = u'''<select name="foo"> <option value="RM">Regi\xf3n Metropolitana de Santiago</option> <option value="I">Regi\xf3n de Tarapac\xe1</option> <option value="II">Regi\xf3n de Antofagasta</option> <option value="III">Regi\xf3n de Atacama</option> <option value="IV">Regi\xf3n de Coquimbo</option> <option value="V">Regi\xf3n de Valpara\xedso</option> <option value="VI">Regi\xf3n del Libertador Bernardo O&#39;Higgins</option> <option value="VII">Regi\xf3n del Maule</option> <option value="VIII">Regi\xf3n del B\xedo B\xedo</option> <option value="IX">Regi\xf3n de la Araucan\xeda</option> <option value="X">Regi\xf3n de los Lagos</option> <option value="XI">Regi\xf3n de Ays\xe9n del General Carlos Ib\xe1\xf1ez del Campo</option> <option value="XII">Regi\xf3n de Magallanes y la Ant\xe1rtica Chilena</option> <option value="XIV">Regi\xf3n de Los R\xedos</option> <option value="XV">Regi\xf3n de Arica-Parinacota</option> </select>''' self.assertEqual(f.render('foo', 'bar'), out) def test_CLRutField(self): error_invalid = [u'The Chilean RUT is not valid.'] error_format = [u'Enter a valid Chilean RUT. The format is XX.XXX.XXX-X.'] valid = { '11-6': '11-6', '116': '11-6', '767484100': '76.748.410-0', '78.412.790-7': '78.412.790-7', '8.334.6043': '8.334.604-3', '76793310-K': '76.793.310-K', '76793310-k': '76.793.310-K', } invalid = { '11.111.111-0': error_invalid, '111': error_invalid, } self.assertFieldOutput(CLRutField, valid, invalid) # deal with special "Strict Mode". invalid = { '11-6': error_format, '767484100': error_format, '8.334.6043': error_format, '76793310-K': error_format, '11.111.111-0': error_invalid } self.assertFieldOutput(CLRutField, {}, invalid, field_kwargs={"strict": True} )
bsd-3-clause
isidorn/test2
test/old_regression/issue_197.py
6
1562
#!/usr/bin/python # Copyright 2010-2012 RethinkDB, all rights reserved. import os, sys, time sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common'))) from test_common import * sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'bench', 'stress-client'))) try: import stress except: print "This test needs the Python interface to the stress client." raise def test_function(opts, port, test_dir): model = stress.FuzzyModel(1) # Every single operation will hit the same key key_generator = stress.SeedKeyGenerator() print "Setting up connections..." read_client = stress.Client() read_connection = stress.Connection("localhost:%d" % port) read_op = stress.ReadOp(key_generator, model.random_chooser(), read_connection, batch_factor=1) read_client.add_op(1, read_op) write_client = stress.Client() write_connection = stress.Connection("localhost:%d" % port) write_op = stress.UpdateOp(key_generator, model.random_chooser(), None, write_connection, size=1000) write_client.add_op(1, write_op) duration = 10 print "Running for %d seconds..." % duration read_client.start() write_client.start() time.sleep(duration) read_client.stop() write_client.stop() print "Did %d inserts and %d reads." % (write_op.poll()["queries"], read_op.poll()["queries"]) if __name__ == "__main__": op = make_option_parser() auto_server_test_main(test_function, op.parse(sys.argv))
agpl-3.0
AnotherIvan/calibre
src/calibre/utils/pyconsole/__init__.py
14
1290
#!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import sys, os from calibre import prints as prints_, preferred_encoding, isbytestring from calibre.utils.config import Config, ConfigProxy, JSONConfig from calibre.utils.ipc.launch import Worker from calibre.constants import __appname__, __version__, iswindows from calibre.gui2 import error_dialog # Time to wait for communication to/from the interpreter process POLL_TIMEOUT = 0.01 # seconds preferred_encoding, isbytestring, __appname__, __version__, error_dialog, \ iswindows def console_config(): desc='Settings to control the calibre console' c = Config('console', desc) c.add_opt('theme', default='native', help='The color theme') c.add_opt('scrollback', default=10000, help='Max number of lines to keep in the scrollback buffer') return c prefs = ConfigProxy(console_config()) dynamic = JSONConfig('console') def prints(*args, **kwargs): kwargs['file'] = sys.__stdout__ prints_(*args, **kwargs) class Process(Worker): @property def env(self): env = dict(os.environ) env.update(self._env) return env
gpl-3.0
thomascarterx/kosmosfs
scripts.solaris/metalogprune.py
11
2353
#!/usr/bin/env python # # $Id$ # # Copyright 2008 Quantcast Corp. # # This file is part of Kosmos File System (KFS). # # Licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. See the License for the specific language governing # permissions and limitations under the License. # # \file metalogprune.py # \brief KFS log and checkpoint housekeeping # # We gzip and keep all the old log files around. This is a bit of an # overkill---we can prune away files that are no longer referenced by # any checkpoint. We find the oldest checkpoint file and find that # the log it references; files older than that log file are deleted. # import os import sys import glob import stat import time import getopt import gzip def age(file): """return age of file (last mtime) in seconds""" now = time.time() return now - os.stat(file)[stat.ST_MTIME] def orderByAge(this, that): if age(this) > age(that): return this return that def olderThanLog(logfile, lognum): """Return True if logfile which is of the form log.# has a sequence number less than lognum""" (base, extn) = os.path.splitext(logfile) extn = extn[1:] if extn == 'gz': val = int(os.path.splitext(base)[1][1:]) else: val = int(extn) return val < lognum def prunefiles(cpdir, logdir): """Find the log file that is referenced by the oldest CP file. Log files that are older than that one can be deleted.""" oldest = reduce(orderByAge, glob.glob(cpdir + '/chkpt.*')) if oldest is None: return print "Oldest cp: %s" % oldest # get the log file for l in open(oldest).xreadlines(): if l.startswith('log/'): lognum = int(os.path.splitext(l[4:])[1][1:]) print lognum alllogfiles = glob.glob(logdir + '/log.*') oldones = [f for f in alllogfiles if olderThanLog(f, lognum)] for f in oldones: os.remove(f) break if (__name__ == "__main__"): if len(sys.argv) != 3: raise getopt.GetoptError, "missing arguments" # kfscpdir, kfslogdir prunefiles(sys.argv[1], sys.argv[2])
apache-2.0
cgmckeever/contests
2012-mebipenny/finals/bj/territory.py
7
9538
from __future__ import division from httplib import * import sys import argparse import json import os import time import collections import itertools class GameServer: def __init__(self, host, port): self.conn = HTTPConnection(host, port) self.path = '' def create_game(self, rows, cols, seats=2, delay=None, coverage=None): body = {'rows':rows,'cols':cols, 'seats':seats} if delay: body['delay_time'] = delay if coverage: body['seed_coverage'] = coverage self.conn.request('POST', '/', json.dumps(body)) resp = self.conn.getresponse() if resp.status != 201: body = resp.read() raise RuntimeError("Tried to create a game, got response {}, {}".format(resp.status, body)) loc = resp.getheader('Location') print "Created game at {}, copied to clipboard", loc out = os.popen('/usr/bin/pbcopy', 'w') out.write(loc[1:]) out.close() return loc def join_game(self, path, name): if path.startswith('/') == False: path = '/' + path self.path = path player_info = {'name':name} resp = self.post('/players', json.dumps(player_info)) if resp.status == 410: print "Game full or gone" return None elif resp.status == 200: game_body = json.loads(resp.read()) game = Game(game_body) game.token = resp.getheader("X-Turn-Token") print "Joined game" else: body = resp.read() raise RuntimeError("Unexpected response {}, {}".format(resp.status, body)) return game def request_match(self): resp = self.get('/match') if resp.status != 201: body = resp.read() raise RuntimeError("Problem requesting match: {}, {}".format(resp.status, body)) else: loc = resp.getheader("Location") print "Requested match, got", loc return loc def post(self, rel_path, body, token=None): headers = {} if token: headers = {'X-Turn-Token': token} self.conn.request('POST', self.path + rel_path, body, headers) return self.conn.getresponse() def get(self, rel_path): self.conn.request('GET', self.path + rel_path) return self.conn.getresponse() class Tile: def __init__(self, row, col): self.row = row self.col = col @classmethod def from_json(cls, data): row = data['row'] col = data['col'] return cls(row, col) def to_json(self): data = {'row' : self.row, 'col' : self.col } return data def is_adjacent(self, other): if abs(self.row - other.row) == 1 and self.col == other.col: return True if abs(self.col - other.col) == 1 and self.row == other.row: return True return False def __eq__(self, other): return (self.row, self.col) == (other.row, other.col) def __cmp__(self, other): return cmp((self.row, self.col), (other.row, other.col)) def __hash__(self): return hash((self.row, self.col)) def __unicode__(self): return unicode((self.row, self.col)) def __repr__(self): return "Tile(%s, %s)" % (self.row, self.col) class Claim: def __init__(self, tile, owner): self.tile = tile self.owner = owner @classmethod def from_json(cls, data): tile = Tile.from_json(data['tile']) return cls(tile, data['owner']) def __repr__(self): return repr(self.tile) + ' -> ' + self.owner class Player: """ {id: <string>, name: <string>, score: <integer> or 'disqualified', hand: [<Tile>*] or <integer>} """ def __init__(self, ID, name, score, hand): self.id = ID self.name = name self.score = score self.hand = hand @classmethod def from_json(cls, data): player_id = data['id'] name = data['name'] score = data['score'] if score == 'disqualified': score = None try: hand = [Tile.from_json(x) for x in data['hand']] except: hand = [None for i in range(data['hand'])] return cls(player_id, name, score, hand) class Game: def __init__(self, json_body): """ {rows: <integer>, cols: <integer>, draw_size: <integer>, claims: [<Claim>*], players: [<Player>*], state: <Game State>} """ self.rows = json_body['rows'] self.cols = json_body['cols'] self.draw_size = json_body['draw_size'] claims = [Claim.from_json(x) for x in json_body['claims']] self.claims_map = {claim.tile : claim.owner for claim in claims} players = [Player.from_json(x) for x in json_body['players']] self.players = {player.id : player for player in players} self.state = json_body['state'] self.player_id = json_body['player_id'] def is_completed(self): return self.state == 'completed' def update(self, delta): self.draw_size = delta.draw_size claims_to_update = {claim.tile : claim.owner for claim in delta.claims} for tile, owner in claims_to_update.items(): if owner == None: print "Updating a claim to 'none'?" self.claims_map.update(claims_to_update) players_to_update = {player.id : player for player in delta.players} self.players.update(players_to_update) self.state = delta.state def printBoard(self): board = [['-' for x in range(self.cols)] for y in range(self.rows)] for tile, owner in self.claims_map.items(): if owner is None: s = '#' else: s = owner[:1] board[tile.row][tile.col] = s print '' for row in board: print ' ' + ''.join(row) print '' def armiesAdjacentToTile(self, tile): up = Tile(tile.row-1, tile.col) down = Tile(tile.row+1, tile.col) left = Tile(tile.row, tile.col-1) right = Tile(tile.row, tile.col+1) tiles = [up, down, left, right] armies = [] for tile in tiles: already_used = False for army in armies: if tile in army.claims: # Already in a found army, skip it already_used = True if already_used: continue army = self.armyAtTile(tile) if army: armies.append(army) return armies def armyAtTile(self, tile, found=None): if found is None: found = set() if tile in found: return Army(found) if tile not in self.claims_map or self.claims_map[tile] is None: return None found.add(tile) owner = self.claims_map[tile] up = Tile(tile.row-1, tile.col) down = Tile(tile.row+1, tile.col) left = Tile(tile.row, tile.col-1) right = Tile(tile.row, tile.col+1) if self.claims_map.get(up) == owner: found.update(self.armyAtTile(up, found).claims) if self.claims_map.get(down) == owner: found.update(self.armyAtTile(down, found).claims) if self.claims_map.get(right) == owner: found.update(self.armyAtTile(right, found).claims) if self.claims_map.get(left) == owner: found.update(self.armyAtTile(left, found).claims) return Army(found, owner) class Army: def __init__(self, claims, owner=None): self.claims = claims self.owner = owner class GameDelta: @classmethod def from_json(cls, json_body): """ {draw_size: <integer>, claims: [<Claim>*], players: [<Player>*], state: <Game State>}""" draw_size = json_body['draw_size'] claims = [Claim.from_json(x) for x in json_body['claims']] players = [Player.from_json(x) for x in json_body['players']] state = json_body['state'] self = cls(draw_size, claims, players, state) return self def __init__(self, draw_size, claims, players, state): self.draw_size = draw_size self.claims = claims self.players = players self.state = state class Move: def __init__(self, tile, score, favor, note=None): self.tile = tile self.score = score self.note = note self.favor = favor def __repr__(self): s = "{} -> {}".format(self.tile, self.score) if self.note: s += ' ({})'.format(self.note) return s def runWithBot(botClass): parser = argparse.ArgumentParser(description="Bot for 2012 Mebipenny final problem") parser.add_argument('host') parser.add_argument('port', type=int) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-n', '--new', nargs=2, metavar=('ROWS', 'COLS'), type=int, help="Rows and columns for a new game") group.add_argument('-j', '--join', metavar="GAME_PATH", help="Path to the game on the server", dest='path') group.add_argument('-m', '--match', action='store_true', help="Request the next available game from the server") newgame_group = parser.add_argument_group("New game options", "These options only apply to manually created new games") newgame_group.add_argument('-d', '--delay', type=float, metavar='N', help="Adds a delay of N seconds after every turn") newgame_group.add_argument('-s', '--seats', type=int, default=2, help="Number of seats in the game") newgame_group.add_argument('-c', '--coverage', type=float, help="Percent of board to seed with walls") parser.add_argument('player_name') args = parser.parse_args() server = GameServer(args.host, args.port) if args.new: rows, cols = args.new path = server.create_game(rows, cols, args.seats, args.delay, args.coverage) elif args.path: path = args.path else: path = server.request_match() name = args.player_name + '_' + botClass.name game = server.join_game(path, name) game_player = game.players[game.player_id] bot = botClass(server, game, game_player.id) while not game.is_completed(): game.printBoard() bot.take_turn() players = game.players.values() player_scores = collections.Counter(game.claims_map.values()) for player in players: score = player_scores[player.id] marker = '' if player.id == game_player.id: marker = ' *' print "{}{} -> {}".format(player.name, marker, score) if __name__ == "__main__": print "This file should not be run directly. Import it into other files." #winner = sorted(players, key=lambda p: p.score, reverse=True)[0] #if winner.id == player.id: # print "WINNER"
mit
100star/h2o
py/testdir_single_jvm/test_GLM2_poisson_rand2.py
9
2123
import unittest, random, sys, time sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_glm, h2o_import as h2i def define_params(): paramDict = { 'standardize': [None, 0, 1], 'beta_epsilon': [None, 0.0001], 'family': ['poisson'], 'n_folds': [2, 3, 4], 'lambda': [1e-8, 1e-4], 'alpha': [0, 0.5], 'max_iter': [5, 10, 19], # only log and identify are legal # 'link': ["identify", "logit", "log", "inverse", "tweedie"] 'link': ["identity", "log"] } return paramDict class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): global SEED SEED = h2o.setup_random_seed() h2o.init() @classmethod def tearDownClass(cls): h2o.tear_down_cloud() def test_GLM2_poisson_rand2(self): csvPathname = 'standard/covtype.data' parseResult = h2i.import_parse(bucket='home-0xdiag-datasets', path=csvPathname, schema='put') paramDict = define_params() for trial in range(20): params = { 'response': 54, 'n_folds': 3, 'family': "poisson", 'alpha': 0.5, 'lambda': 1e-4, 'beta_epsilon': 0.001, 'max_iter': 15, } colX = h2o_glm.pickRandGlmParams(paramDict, params) kwargs = params.copy() # make timeout bigger with xvals timeoutSecs = 60 + (kwargs['n_folds']*40) # or double the 4 seconds per iteration (max_iter+1 worst case?) timeoutSecs = max(timeoutSecs, (8 * (kwargs['max_iter']+1))) start = time.time() glm = h2o_cmd.runGLM(timeoutSecs=timeoutSecs, parseResult=parseResult, **kwargs) print "glm end on ", csvPathname, 'took', time.time() - start, 'seconds' h2o_glm.simpleCheckGLM(self, glm, None, **kwargs) print "Trial #", trial, "completed\n" if __name__ == '__main__': h2o.unit_main()
apache-2.0
joopert/home-assistant
homeassistant/components/xiaomi_aqara/binary_sensor.py
7
17805
"""Support for Xiaomi aqara binary sensors.""" import logging from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.core import callback from homeassistant.helpers.event import async_call_later from . import PY_XIAOMI_GATEWAY, XiaomiDevice _LOGGER = logging.getLogger(__name__) NO_CLOSE = "no_close" ATTR_OPEN_SINCE = "Open since" MOTION = "motion" NO_MOTION = "no_motion" ATTR_LAST_ACTION = "last_action" ATTR_NO_MOTION_SINCE = "No motion since" DENSITY = "density" ATTR_DENSITY = "Density" def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Xiaomi devices.""" devices = [] for (_, gateway) in hass.data[PY_XIAOMI_GATEWAY].gateways.items(): for device in gateway.devices["binary_sensor"]: model = device["model"] if model in ["motion", "sensor_motion", "sensor_motion.aq2"]: devices.append(XiaomiMotionSensor(device, hass, gateway)) elif model in ["magnet", "sensor_magnet", "sensor_magnet.aq2"]: devices.append(XiaomiDoorSensor(device, gateway)) elif model == "sensor_wleak.aq1": devices.append(XiaomiWaterLeakSensor(device, gateway)) elif model in ["smoke", "sensor_smoke"]: devices.append(XiaomiSmokeSensor(device, gateway)) elif model in ["natgas", "sensor_natgas"]: devices.append(XiaomiNatgasSensor(device, gateway)) elif model in [ "switch", "sensor_switch", "sensor_switch.aq2", "sensor_switch.aq3", "remote.b1acn01", ]: if "proto" not in device or int(device["proto"][0:1]) == 1: data_key = "status" else: data_key = "button_0" devices.append(XiaomiButton(device, "Switch", data_key, hass, gateway)) elif model in [ "86sw1", "sensor_86sw1", "sensor_86sw1.aq1", "remote.b186acn01", ]: if "proto" not in device or int(device["proto"][0:1]) == 1: data_key = "channel_0" else: data_key = "button_0" devices.append( XiaomiButton(device, "Wall Switch", data_key, hass, gateway) ) elif model in [ "86sw2", "sensor_86sw2", "sensor_86sw2.aq1", "remote.b286acn01", ]: if "proto" not in device or int(device["proto"][0:1]) == 1: data_key_left = "channel_0" data_key_right = "channel_1" else: data_key_left = "button_0" data_key_right = "button_1" devices.append( XiaomiButton( device, "Wall Switch (Left)", data_key_left, hass, gateway ) ) devices.append( XiaomiButton( device, "Wall Switch (Right)", data_key_right, hass, gateway ) ) devices.append( XiaomiButton( device, "Wall Switch (Both)", "dual_channel", hass, gateway ) ) elif model in ["cube", "sensor_cube", "sensor_cube.aqgl01"]: devices.append(XiaomiCube(device, hass, gateway)) elif model in ["vibration", "vibration.aq1"]: devices.append(XiaomiVibration(device, "Vibration", "status", gateway)) else: _LOGGER.warning("Unmapped Device Model %s", model) add_entities(devices) class XiaomiBinarySensor(XiaomiDevice, BinarySensorDevice): """Representation of a base XiaomiBinarySensor.""" def __init__(self, device, name, xiaomi_hub, data_key, device_class): """Initialize the XiaomiSmokeSensor.""" self._data_key = data_key self._device_class = device_class self._should_poll = False self._density = 0 XiaomiDevice.__init__(self, device, name, xiaomi_hub) @property def should_poll(self): """Return True if entity has to be polled for state.""" return self._should_poll @property def is_on(self): """Return true if sensor is on.""" return self._state @property def device_class(self): """Return the class of binary sensor.""" return self._device_class def update(self): """Update the sensor state.""" _LOGGER.debug("Updating xiaomi sensor (%s) by polling", self._sid) self._get_from_hub(self._sid) class XiaomiNatgasSensor(XiaomiBinarySensor): """Representation of a XiaomiNatgasSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiSmokeSensor.""" self._density = None XiaomiBinarySensor.__init__( self, device, "Natgas Sensor", xiaomi_hub, "alarm", "gas" ) @property def device_state_attributes(self): """Return the state attributes.""" attrs = {ATTR_DENSITY: self._density} attrs.update(super().device_state_attributes) return attrs def parse_data(self, data, raw_data): """Parse data sent by gateway.""" if DENSITY in data: self._density = int(data.get(DENSITY)) value = data.get(self._data_key) if value is None: return False if value in ("1", "2"): if self._state: return False self._state = True return True if value == "0": if self._state: self._state = False return True return False class XiaomiMotionSensor(XiaomiBinarySensor): """Representation of a XiaomiMotionSensor.""" def __init__(self, device, hass, xiaomi_hub): """Initialize the XiaomiMotionSensor.""" self._hass = hass self._no_motion_since = 0 self._unsub_set_no_motion = None if "proto" not in device or int(device["proto"][0:1]) == 1: data_key = "status" else: data_key = "motion_status" XiaomiBinarySensor.__init__( self, device, "Motion Sensor", xiaomi_hub, data_key, "motion" ) @property def device_state_attributes(self): """Return the state attributes.""" attrs = {ATTR_NO_MOTION_SINCE: self._no_motion_since} attrs.update(super().device_state_attributes) return attrs @callback def _async_set_no_motion(self, now): """Set state to False.""" self._unsub_set_no_motion = None self._state = False self.async_schedule_update_ha_state() def parse_data(self, data, raw_data): """Parse data sent by gateway. Polling (proto v1, firmware version 1.4.1_159.0143) >> { "cmd":"read","sid":"158..."} << {'model': 'motion', 'sid': '158...', 'short_id': 26331, 'cmd': 'read_ack', 'data': '{"voltage":3005}'} Multicast messages (proto v1, firmware version 1.4.1_159.0143) << {'model': 'motion', 'sid': '158...', 'short_id': 26331, 'cmd': 'report', 'data': '{"status":"motion"}'} << {'model': 'motion', 'sid': '158...', 'short_id': 26331, 'cmd': 'report', 'data': '{"no_motion":"120"}'} << {'model': 'motion', 'sid': '158...', 'short_id': 26331, 'cmd': 'report', 'data': '{"no_motion":"180"}'} << {'model': 'motion', 'sid': '158...', 'short_id': 26331, 'cmd': 'report', 'data': '{"no_motion":"300"}'} << {'model': 'motion', 'sid': '158...', 'short_id': 26331, 'cmd': 'heartbeat', 'data': '{"voltage":3005}'} """ if raw_data["cmd"] == "heartbeat": _LOGGER.debug( "Skipping heartbeat of the motion sensor. " "It can introduce an incorrect state because of a firmware " "bug (https://github.com/home-assistant/home-assistant/pull/" "11631#issuecomment-357507744)." ) return if NO_MOTION in data: self._no_motion_since = data[NO_MOTION] self._state = False return True value = data.get(self._data_key) if value is None: return False if value == MOTION: if self._data_key == "motion_status": if self._unsub_set_no_motion: self._unsub_set_no_motion() self._unsub_set_no_motion = async_call_later( self._hass, 120, self._async_set_no_motion ) if self.entity_id is not None: self._hass.bus.fire( "xiaomi_aqara.motion", {"entity_id": self.entity_id} ) self._no_motion_since = 0 if self._state: return False self._state = True return True class XiaomiDoorSensor(XiaomiBinarySensor): """Representation of a XiaomiDoorSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiDoorSensor.""" self._open_since = 0 if "proto" not in device or int(device["proto"][0:1]) == 1: data_key = "status" else: data_key = "window_status" XiaomiBinarySensor.__init__( self, device, "Door Window Sensor", xiaomi_hub, data_key, "opening" ) @property def device_state_attributes(self): """Return the state attributes.""" attrs = {ATTR_OPEN_SINCE: self._open_since} attrs.update(super().device_state_attributes) return attrs def parse_data(self, data, raw_data): """Parse data sent by gateway.""" self._should_poll = False if NO_CLOSE in data: # handle push from the hub self._open_since = data[NO_CLOSE] return True value = data.get(self._data_key) if value is None: return False if value == "open": self._should_poll = True if self._state: return False self._state = True return True if value == "close": self._open_since = 0 if self._state: self._state = False return True return False class XiaomiWaterLeakSensor(XiaomiBinarySensor): """Representation of a XiaomiWaterLeakSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiWaterLeakSensor.""" if "proto" not in device or int(device["proto"][0:1]) == 1: data_key = "status" else: data_key = "wleak_status" XiaomiBinarySensor.__init__( self, device, "Water Leak Sensor", xiaomi_hub, data_key, "moisture" ) def parse_data(self, data, raw_data): """Parse data sent by gateway.""" self._should_poll = False value = data.get(self._data_key) if value is None: return False if value == "leak": self._should_poll = True if self._state: return False self._state = True return True if value == "no_leak": if self._state: self._state = False return True return False class XiaomiSmokeSensor(XiaomiBinarySensor): """Representation of a XiaomiSmokeSensor.""" def __init__(self, device, xiaomi_hub): """Initialize the XiaomiSmokeSensor.""" self._density = 0 XiaomiBinarySensor.__init__( self, device, "Smoke Sensor", xiaomi_hub, "alarm", "smoke" ) @property def device_state_attributes(self): """Return the state attributes.""" attrs = {ATTR_DENSITY: self._density} attrs.update(super().device_state_attributes) return attrs def parse_data(self, data, raw_data): """Parse data sent by gateway.""" if DENSITY in data: self._density = int(data.get(DENSITY)) value = data.get(self._data_key) if value is None: return False if value in ("1", "2"): if self._state: return False self._state = True return True if value == "0": if self._state: self._state = False return True return False class XiaomiVibration(XiaomiBinarySensor): """Representation of a Xiaomi Vibration Sensor.""" def __init__(self, device, name, data_key, xiaomi_hub): """Initialize the XiaomiVibration.""" self._last_action = None super().__init__(device, name, xiaomi_hub, data_key, None) @property def device_state_attributes(self): """Return the state attributes.""" attrs = {ATTR_LAST_ACTION: self._last_action} attrs.update(super().device_state_attributes) return attrs def parse_data(self, data, raw_data): """Parse data sent by gateway.""" value = data.get(self._data_key) if value is None: return False if value not in ("vibrate", "tilt", "free_fall", "actively"): _LOGGER.warning("Unsupported movement_type detected: %s", value) return False self.hass.bus.fire( "xiaomi_aqara.movement", {"entity_id": self.entity_id, "movement_type": value}, ) self._last_action = value return True class XiaomiButton(XiaomiBinarySensor): """Representation of a Xiaomi Button.""" def __init__(self, device, name, data_key, hass, xiaomi_hub): """Initialize the XiaomiButton.""" self._hass = hass self._last_action = None XiaomiBinarySensor.__init__(self, device, name, xiaomi_hub, data_key, None) @property def device_state_attributes(self): """Return the state attributes.""" attrs = {ATTR_LAST_ACTION: self._last_action} attrs.update(super().device_state_attributes) return attrs def parse_data(self, data, raw_data): """Parse data sent by gateway.""" value = data.get(self._data_key) if value is None: return False if value == "long_click_press": self._state = True click_type = "long_click_press" elif value == "long_click_release": self._state = False click_type = "hold" elif value == "click": click_type = "single" elif value == "double_click": click_type = "double" elif value == "both_click": click_type = "both" elif value == "double_both_click": click_type = "double_both" elif value == "shake": click_type = "shake" elif value == "long_click": click_type = "long" elif value == "long_both_click": click_type = "long_both" else: _LOGGER.warning("Unsupported click_type detected: %s", value) return False self._hass.bus.fire( "xiaomi_aqara.click", {"entity_id": self.entity_id, "click_type": click_type}, ) self._last_action = click_type return True class XiaomiCube(XiaomiBinarySensor): """Representation of a Xiaomi Cube.""" def __init__(self, device, hass, xiaomi_hub): """Initialize the Xiaomi Cube.""" self._hass = hass self._last_action = None self._state = False if "proto" not in device or int(device["proto"][0:1]) == 1: data_key = "status" else: data_key = "cube_status" XiaomiBinarySensor.__init__(self, device, "Cube", xiaomi_hub, data_key, None) @property def device_state_attributes(self): """Return the state attributes.""" attrs = {ATTR_LAST_ACTION: self._last_action} attrs.update(super().device_state_attributes) return attrs def parse_data(self, data, raw_data): """Parse data sent by gateway.""" if self._data_key in data: self._hass.bus.fire( "xiaomi_aqara.cube_action", {"entity_id": self.entity_id, "action_type": data[self._data_key]}, ) self._last_action = data[self._data_key] if "rotate" in data: action_value = float( data["rotate"] if isinstance(data["rotate"], int) else data["rotate"].replace(",", ".") ) self._hass.bus.fire( "xiaomi_aqara.cube_action", { "entity_id": self.entity_id, "action_type": "rotate", "action_value": action_value, }, ) self._last_action = "rotate" if "rotate_degree" in data: action_value = float( data["rotate_degree"] if isinstance(data["rotate_degree"], int) else data["rotate_degree"].replace(",", ".") ) self._hass.bus.fire( "xiaomi_aqara.cube_action", { "entity_id": self.entity_id, "action_type": "rotate", "action_value": action_value, }, ) self._last_action = "rotate" return True
apache-2.0
ammarkhann/FinalSeniorCode
lib/python2.7/site-packages/google/protobuf/internal/well_known_types.py
52
26624
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Contains well known classes. This files defines well known classes which need extra maintenance including: - Any - Duration - FieldMask - Struct - Timestamp """ __author__ = 'jieluo@google.com (Jie Luo)' from datetime import datetime from datetime import timedelta import six from google.protobuf.descriptor import FieldDescriptor _TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S' _NANOS_PER_SECOND = 1000000000 _NANOS_PER_MILLISECOND = 1000000 _NANOS_PER_MICROSECOND = 1000 _MILLIS_PER_SECOND = 1000 _MICROS_PER_SECOND = 1000000 _SECONDS_PER_DAY = 24 * 3600 _DURATION_SECONDS_MAX = 315576000000 class Error(Exception): """Top-level module error.""" class ParseError(Error): """Thrown in case of parsing error.""" class Any(object): """Class for Any Message type.""" def Pack(self, msg, type_url_prefix='type.googleapis.com/'): """Packs the specified message into current Any message.""" if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/': self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) else: self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) self.value = msg.SerializeToString() def Unpack(self, msg): """Unpacks the current Any message into specified message.""" descriptor = msg.DESCRIPTOR if not self.Is(descriptor): return False msg.ParseFromString(self.value) return True def TypeName(self): """Returns the protobuf type name of the inner message.""" # Only last part is to be used: b/25630112 return self.type_url.split('/')[-1] def Is(self, descriptor): """Checks if this Any represents the given protobuf type.""" return self.TypeName() == descriptor.full_name class Timestamp(object): """Class for Timestamp message type.""" def ToJsonString(self): """Converts Timestamp to RFC 3339 date string format. Returns: A string converted from timestamp. The string is always Z-normalized and uses 3, 6 or 9 fractional digits as required to represent the exact time. Example of the return format: '1972-01-01T10:00:20.021Z' """ nanos = self.nanos % _NANOS_PER_SECOND total_sec = self.seconds + (self.nanos - nanos) // _NANOS_PER_SECOND seconds = total_sec % _SECONDS_PER_DAY days = (total_sec - seconds) // _SECONDS_PER_DAY dt = datetime(1970, 1, 1) + timedelta(days, seconds) result = dt.isoformat() if (nanos % 1e9) == 0: # If there are 0 fractional digits, the fractional # point '.' should be omitted when serializing. return result + 'Z' if (nanos % 1e6) == 0: # Serialize 3 fractional digits. return result + '.%03dZ' % (nanos / 1e6) if (nanos % 1e3) == 0: # Serialize 6 fractional digits. return result + '.%06dZ' % (nanos / 1e3) # Serialize 9 fractional digits. return result + '.%09dZ' % nanos def FromJsonString(self, value): """Parse a RFC 3339 date string format to Timestamp. Args: value: A date string. Any fractional digits (or none) and any offset are accepted as long as they fit into nano-seconds precision. Example of accepted format: '1972-01-01T10:00:20.021-05:00' Raises: ParseError: On parsing problems. """ timezone_offset = value.find('Z') if timezone_offset == -1: timezone_offset = value.find('+') if timezone_offset == -1: timezone_offset = value.rfind('-') if timezone_offset == -1: raise ParseError( 'Failed to parse timestamp: missing valid timezone offset.') time_value = value[0:timezone_offset] # Parse datetime and nanos. point_position = time_value.find('.') if point_position == -1: second_value = time_value nano_value = '' else: second_value = time_value[:point_position] nano_value = time_value[point_position + 1:] date_object = datetime.strptime(second_value, _TIMESTAMPFOMAT) td = date_object - datetime(1970, 1, 1) seconds = td.seconds + td.days * _SECONDS_PER_DAY if len(nano_value) > 9: raise ParseError( 'Failed to parse Timestamp: nanos {0} more than ' '9 fractional digits.'.format(nano_value)) if nano_value: nanos = round(float('0.' + nano_value) * 1e9) else: nanos = 0 # Parse timezone offsets. if value[timezone_offset] == 'Z': if len(value) != timezone_offset + 1: raise ParseError('Failed to parse timestamp: invalid trailing' ' data {0}.'.format(value)) else: timezone = value[timezone_offset:] pos = timezone.find(':') if pos == -1: raise ParseError( 'Invalid timezone offset value: {0}.'.format(timezone)) if timezone[0] == '+': seconds -= (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60 else: seconds += (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60 # Set seconds and nanos self.seconds = int(seconds) self.nanos = int(nanos) def GetCurrentTime(self): """Get the current UTC into Timestamp.""" self.FromDatetime(datetime.utcnow()) def ToNanoseconds(self): """Converts Timestamp to nanoseconds since epoch.""" return self.seconds * _NANOS_PER_SECOND + self.nanos def ToMicroseconds(self): """Converts Timestamp to microseconds since epoch.""" return (self.seconds * _MICROS_PER_SECOND + self.nanos // _NANOS_PER_MICROSECOND) def ToMilliseconds(self): """Converts Timestamp to milliseconds since epoch.""" return (self.seconds * _MILLIS_PER_SECOND + self.nanos // _NANOS_PER_MILLISECOND) def ToSeconds(self): """Converts Timestamp to seconds since epoch.""" return self.seconds def FromNanoseconds(self, nanos): """Converts nanoseconds since epoch to Timestamp.""" self.seconds = nanos // _NANOS_PER_SECOND self.nanos = nanos % _NANOS_PER_SECOND def FromMicroseconds(self, micros): """Converts microseconds since epoch to Timestamp.""" self.seconds = micros // _MICROS_PER_SECOND self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND def FromMilliseconds(self, millis): """Converts milliseconds since epoch to Timestamp.""" self.seconds = millis // _MILLIS_PER_SECOND self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND def FromSeconds(self, seconds): """Converts seconds since epoch to Timestamp.""" self.seconds = seconds self.nanos = 0 def ToDatetime(self): """Converts Timestamp to datetime.""" return datetime.utcfromtimestamp( self.seconds + self.nanos / float(_NANOS_PER_SECOND)) def FromDatetime(self, dt): """Converts datetime to Timestamp.""" td = dt - datetime(1970, 1, 1) self.seconds = td.seconds + td.days * _SECONDS_PER_DAY self.nanos = td.microseconds * _NANOS_PER_MICROSECOND class Duration(object): """Class for Duration message type.""" def ToJsonString(self): """Converts Duration to string format. Returns: A string converted from self. The string format will contains 3, 6, or 9 fractional digits depending on the precision required to represent the exact Duration value. For example: "1s", "1.010s", "1.000000100s", "-3.100s" """ _CheckDurationValid(self.seconds, self.nanos) if self.seconds < 0 or self.nanos < 0: result = '-' seconds = - self.seconds + int((0 - self.nanos) // 1e9) nanos = (0 - self.nanos) % 1e9 else: result = '' seconds = self.seconds + int(self.nanos // 1e9) nanos = self.nanos % 1e9 result += '%d' % seconds if (nanos % 1e9) == 0: # If there are 0 fractional digits, the fractional # point '.' should be omitted when serializing. return result + 's' if (nanos % 1e6) == 0: # Serialize 3 fractional digits. return result + '.%03ds' % (nanos / 1e6) if (nanos % 1e3) == 0: # Serialize 6 fractional digits. return result + '.%06ds' % (nanos / 1e3) # Serialize 9 fractional digits. return result + '.%09ds' % nanos def FromJsonString(self, value): """Converts a string to Duration. Args: value: A string to be converted. The string must end with 's'. Any fractional digits (or none) are accepted as long as they fit into precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s Raises: ParseError: On parsing problems. """ if len(value) < 1 or value[-1] != 's': raise ParseError( 'Duration must end with letter "s": {0}.'.format(value)) try: pos = value.find('.') if pos == -1: seconds = int(value[:-1]) nanos = 0 else: seconds = int(value[:pos]) if value[0] == '-': nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9)) else: nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9)) _CheckDurationValid(seconds, nanos) self.seconds = seconds self.nanos = nanos except ValueError: raise ParseError( 'Couldn\'t parse duration: {0}.'.format(value)) def ToNanoseconds(self): """Converts a Duration to nanoseconds.""" return self.seconds * _NANOS_PER_SECOND + self.nanos def ToMicroseconds(self): """Converts a Duration to microseconds.""" micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) return self.seconds * _MICROS_PER_SECOND + micros def ToMilliseconds(self): """Converts a Duration to milliseconds.""" millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND) return self.seconds * _MILLIS_PER_SECOND + millis def ToSeconds(self): """Converts a Duration to seconds.""" return self.seconds def FromNanoseconds(self, nanos): """Converts nanoseconds to Duration.""" self._NormalizeDuration(nanos // _NANOS_PER_SECOND, nanos % _NANOS_PER_SECOND) def FromMicroseconds(self, micros): """Converts microseconds to Duration.""" self._NormalizeDuration( micros // _MICROS_PER_SECOND, (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND) def FromMilliseconds(self, millis): """Converts milliseconds to Duration.""" self._NormalizeDuration( millis // _MILLIS_PER_SECOND, (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND) def FromSeconds(self, seconds): """Converts seconds to Duration.""" self.seconds = seconds self.nanos = 0 def ToTimedelta(self): """Converts Duration to timedelta.""" return timedelta( seconds=self.seconds, microseconds=_RoundTowardZero( self.nanos, _NANOS_PER_MICROSECOND)) def FromTimedelta(self, td): """Convertd timedelta to Duration.""" self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY, td.microseconds * _NANOS_PER_MICROSECOND) def _NormalizeDuration(self, seconds, nanos): """Set Duration by seconds and nonas.""" # Force nanos to be negative if the duration is negative. if seconds < 0 and nanos > 0: seconds += 1 nanos -= _NANOS_PER_SECOND self.seconds = seconds self.nanos = nanos def _CheckDurationValid(seconds, nanos): if seconds < -_DURATION_SECONDS_MAX or seconds > _DURATION_SECONDS_MAX: raise Error( 'Duration is not valid: Seconds {0} must be in range ' '[-315576000000, 315576000000].'.format(seconds)) if nanos <= -_NANOS_PER_SECOND or nanos >= _NANOS_PER_SECOND: raise Error( 'Duration is not valid: Nanos {0} must be in range ' '[-999999999, 999999999].'.format(nanos)) def _RoundTowardZero(value, divider): """Truncates the remainder part after division.""" # For some languanges, the sign of the remainder is implementation # dependent if any of the operands is negative. Here we enforce # "rounded toward zero" semantics. For example, for (-5) / 2 an # implementation may give -3 as the result with the remainder being # 1. This function ensures we always return -2 (closer to zero). result = value // divider remainder = value % divider if result < 0 and remainder > 0: return result + 1 else: return result class FieldMask(object): """Class for FieldMask message type.""" def ToJsonString(self): """Converts FieldMask to string according to proto3 JSON spec.""" camelcase_paths = [] for path in self.paths: camelcase_paths.append(_SnakeCaseToCamelCase(path)) return ','.join(camelcase_paths) def FromJsonString(self, value): """Converts string to FieldMask according to proto3 JSON spec.""" self.Clear() for path in value.split(','): self.paths.append(_CamelCaseToSnakeCase(path)) def IsValidForDescriptor(self, message_descriptor): """Checks whether the FieldMask is valid for Message Descriptor.""" for path in self.paths: if not _IsValidPath(message_descriptor, path): return False return True def AllFieldsFromDescriptor(self, message_descriptor): """Gets all direct fields of Message Descriptor to FieldMask.""" self.Clear() for field in message_descriptor.fields: self.paths.append(field.name) def CanonicalFormFromMask(self, mask): """Converts a FieldMask to the canonical form. Removes paths that are covered by another path. For example, "foo.bar" is covered by "foo" and will be removed if "foo" is also in the FieldMask. Then sorts all paths in alphabetical order. Args: mask: The original FieldMask to be converted. """ tree = _FieldMaskTree(mask) tree.ToFieldMask(self) def Union(self, mask1, mask2): """Merges mask1 and mask2 into this FieldMask.""" _CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) tree.MergeFromFieldMask(mask2) tree.ToFieldMask(self) def Intersect(self, mask1, mask2): """Intersects mask1 and mask2 into this FieldMask.""" _CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) intersection = _FieldMaskTree() for path in mask2.paths: tree.IntersectPath(path, intersection) intersection.ToFieldMask(self) def MergeMessage( self, source, destination, replace_message_field=False, replace_repeated_field=False): """Merges fields specified in FieldMask from source to destination. Args: source: Source message. destination: The destination message to be merged into. replace_message_field: Replace message field if True. Merge message field if False. replace_repeated_field: Replace repeated field if True. Append elements of repeated field if False. """ tree = _FieldMaskTree(self) tree.MergeMessage( source, destination, replace_message_field, replace_repeated_field) def _IsValidPath(message_descriptor, path): """Checks whether the path is valid for Message Descriptor.""" parts = path.split('.') last = parts.pop() for name in parts: field = message_descriptor.fields_by_name[name] if (field is None or field.label == FieldDescriptor.LABEL_REPEATED or field.type != FieldDescriptor.TYPE_MESSAGE): return False message_descriptor = field.message_type return last in message_descriptor.fields_by_name def _CheckFieldMaskMessage(message): """Raises ValueError if message is not a FieldMask.""" message_descriptor = message.DESCRIPTOR if (message_descriptor.name != 'FieldMask' or message_descriptor.file.name != 'google/protobuf/field_mask.proto'): raise ValueError('Message {0} is not a FieldMask.'.format( message_descriptor.full_name)) def _SnakeCaseToCamelCase(path_name): """Converts a path name from snake_case to camelCase.""" result = [] after_underscore = False for c in path_name: if c.isupper(): raise Error('Fail to print FieldMask to Json string: Path name ' '{0} must not contain uppercase letters.'.format(path_name)) if after_underscore: if c.islower(): result.append(c.upper()) after_underscore = False else: raise Error('Fail to print FieldMask to Json string: The ' 'character after a "_" must be a lowercase letter ' 'in path name {0}.'.format(path_name)) elif c == '_': after_underscore = True else: result += c if after_underscore: raise Error('Fail to print FieldMask to Json string: Trailing "_" ' 'in path name {0}.'.format(path_name)) return ''.join(result) def _CamelCaseToSnakeCase(path_name): """Converts a field name from camelCase to snake_case.""" result = [] for c in path_name: if c == '_': raise ParseError('Fail to parse FieldMask: Path name ' '{0} must not contain "_"s.'.format(path_name)) if c.isupper(): result += '_' result += c.lower() else: result += c return ''.join(result) class _FieldMaskTree(object): """Represents a FieldMask in a tree structure. For example, given a FieldMask "foo.bar,foo.baz,bar.baz", the FieldMaskTree will be: [_root] -+- foo -+- bar | | | +- baz | +- bar --- baz In the tree, each leaf node represents a field path. """ def __init__(self, field_mask=None): """Initializes the tree by FieldMask.""" self._root = {} if field_mask: self.MergeFromFieldMask(field_mask) def MergeFromFieldMask(self, field_mask): """Merges a FieldMask to the tree.""" for path in field_mask.paths: self.AddPath(path) def AddPath(self, path): """Adds a field path into the tree. If the field path to add is a sub-path of an existing field path in the tree (i.e., a leaf node), it means the tree already matches the given path so nothing will be added to the tree. If the path matches an existing non-leaf node in the tree, that non-leaf node will be turned into a leaf node with all its children removed because the path matches all the node's children. Otherwise, a new path will be added. Args: path: The field path to add. """ node = self._root for name in path.split('.'): if name not in node: node[name] = {} elif not node[name]: # Pre-existing empty node implies we already have this entire tree. return node = node[name] # Remove any sub-trees we might have had. node.clear() def ToFieldMask(self, field_mask): """Converts the tree to a FieldMask.""" field_mask.Clear() _AddFieldPaths(self._root, '', field_mask) def IntersectPath(self, path, intersection): """Calculates the intersection part of a field path with this tree. Args: path: The field path to calculates. intersection: The out tree to record the intersection part. """ node = self._root for name in path.split('.'): if name not in node: return elif not node[name]: intersection.AddPath(path) return node = node[name] intersection.AddLeafNodes(path, node) def AddLeafNodes(self, prefix, node): """Adds leaf nodes begin with prefix to this tree.""" if not node: self.AddPath(prefix) for name in node: child_path = prefix + '.' + name self.AddLeafNodes(child_path, node[name]) def MergeMessage( self, source, destination, replace_message, replace_repeated): """Merge all fields specified by this tree from source to destination.""" _MergeMessage( self._root, source, destination, replace_message, replace_repeated) def _StrConvert(value): """Converts value to str if it is not.""" # This file is imported by c extension and some methods like ClearField # requires string for the field name. py2/py3 has different text # type and may use unicode. if not isinstance(value, str): return value.encode('utf-8') return value def _MergeMessage( node, source, destination, replace_message, replace_repeated): """Merge all fields specified by a sub-tree from source to destination.""" source_descriptor = source.DESCRIPTOR for name in node: child = node[name] field = source_descriptor.fields_by_name[name] if field is None: raise ValueError('Error: Can\'t find field {0} in message {1}.'.format( name, source_descriptor.full_name)) if child: # Sub-paths are only allowed for singular message fields. if (field.label == FieldDescriptor.LABEL_REPEATED or field.cpp_type != FieldDescriptor.CPPTYPE_MESSAGE): raise ValueError('Error: Field {0} in message {1} is not a singular ' 'message field and cannot have sub-fields.'.format( name, source_descriptor.full_name)) _MergeMessage( child, getattr(source, name), getattr(destination, name), replace_message, replace_repeated) continue if field.label == FieldDescriptor.LABEL_REPEATED: if replace_repeated: destination.ClearField(_StrConvert(name)) repeated_source = getattr(source, name) repeated_destination = getattr(destination, name) if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: for item in repeated_source: repeated_destination.add().MergeFrom(item) else: repeated_destination.extend(repeated_source) else: if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: if replace_message: destination.ClearField(_StrConvert(name)) if source.HasField(name): getattr(destination, name).MergeFrom(getattr(source, name)) else: setattr(destination, name, getattr(source, name)) def _AddFieldPaths(node, prefix, field_mask): """Adds the field paths descended from node to field_mask.""" if not node: field_mask.paths.append(prefix) return for name in sorted(node): if prefix: child_path = prefix + '.' + name else: child_path = name _AddFieldPaths(node[name], child_path, field_mask) _INT_OR_FLOAT = six.integer_types + (float,) def _SetStructValue(struct_value, value): if value is None: struct_value.null_value = 0 elif isinstance(value, bool): # Note: this check must come before the number check because in Python # True and False are also considered numbers. struct_value.bool_value = value elif isinstance(value, six.string_types): struct_value.string_value = value elif isinstance(value, _INT_OR_FLOAT): struct_value.number_value = value else: raise ValueError('Unexpected type') def _GetStructValue(struct_value): which = struct_value.WhichOneof('kind') if which == 'struct_value': return struct_value.struct_value elif which == 'null_value': return None elif which == 'number_value': return struct_value.number_value elif which == 'string_value': return struct_value.string_value elif which == 'bool_value': return struct_value.bool_value elif which == 'list_value': return struct_value.list_value elif which is None: raise ValueError('Value not set') class Struct(object): """Class for Struct message type.""" __slots__ = [] def __getitem__(self, key): return _GetStructValue(self.fields[key]) def __setitem__(self, key, value): _SetStructValue(self.fields[key], value) def get_or_create_list(self, key): """Returns a list for this key, creating if it didn't exist already.""" return self.fields[key].list_value def get_or_create_struct(self, key): """Returns a struct for this key, creating if it didn't exist already.""" return self.fields[key].struct_value # TODO(haberman): allow constructing/merging from dict. class ListValue(object): """Class for ListValue message type.""" def __len__(self): return len(self.values) def append(self, value): _SetStructValue(self.values.add(), value) def extend(self, elem_seq): for value in elem_seq: self.append(value) def __getitem__(self, index): """Retrieves item by the specified index.""" return _GetStructValue(self.values.__getitem__(index)) def __setitem__(self, index, value): _SetStructValue(self.values.__getitem__(index), value) def items(self): for i in range(len(self)): yield self[i] def add_struct(self): """Appends and returns a struct value as the next value in the list.""" return self.values.add().struct_value def add_list(self): """Appends and returns a list value as the next value in the list.""" return self.values.add().list_value WKTBASES = { 'google.protobuf.Any': Any, 'google.protobuf.Duration': Duration, 'google.protobuf.FieldMask': FieldMask, 'google.protobuf.ListValue': ListValue, 'google.protobuf.Struct': Struct, 'google.protobuf.Timestamp': Timestamp, }
mit
adlius/osf.io
api_tests/wb/views/test_wb_hooks.py
1
39325
from __future__ import unicode_literals import pytest from addons.osfstorage.models import OsfStorageFolder from framework.auth import signing from api.caching.tasks import update_storage_usage_cache from osf_tests.factories import ( AuthUserFactory, ProjectFactory, PreprintFactory ) from api_tests.utils import create_test_file, create_test_preprint_file from osf.models import QuickFilesNode @pytest.fixture() def user(): return AuthUserFactory() @pytest.fixture() def quickfiles_node(user): return QuickFilesNode.objects.get_for_user(user) @pytest.fixture() def quickfiles_file(user, quickfiles_node): file = create_test_file(quickfiles_node, user, filename='road_dogg.mp3') return file @pytest.fixture() def quickfiles_folder(quickfiles_node): return OsfStorageFolder.objects.get_root(target=quickfiles_node) @pytest.fixture() def node(user): return ProjectFactory(creator=user) @pytest.fixture() def node_two(user): return ProjectFactory(creator=user) @pytest.fixture() def osfstorage(node): return node.get_addon('osfstorage') @pytest.fixture() def root_node(osfstorage): return osfstorage.get_root() @pytest.fixture() def node_two_root_node(node_two): node_two_settings = node_two.get_addon('osfstorage') return node_two_settings.get_root() @pytest.fixture() def file(node, user): return create_test_file(node, user, 'test_file') @pytest.fixture() def folder(root_node, user): return root_node.append_folder('Nina Simone') @pytest.fixture() def folder_two(root_node, user): return root_node.append_folder('Second Folder') def sign_payload(payload): return signing.sign_data(signing.default_signer, payload) @pytest.mark.django_db @pytest.mark.enable_quickfiles_creation @pytest.mark.enable_implicit_clean class TestMove(): @pytest.fixture() def move_url(self, node): return '/_/wb/hooks/{}/move/'.format(node._id) @pytest.fixture() def quickfiles_move_url(self, quickfiles_node): return '/_/wb/hooks/{}/move/'.format(quickfiles_node._id) @pytest.fixture() def payload(self, file, folder, root_node, user): return { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': folder.name, } } @pytest.fixture() def signed_payload(self, payload): return sign_payload(payload) def test_move_hook(self, app, move_url, signed_payload, folder, file): res = app.post_json(move_url, signed_payload, expect_errors=False) assert res.status_code == 200 def test_move_checkedout_file(self, app, file, user, move_url, signed_payload): file.checkout = user file.save() res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert b'Cannot move file as it is checked out.' in res._app_iter[0] def test_move_checked_out_file_in_folder(self, app, root_node, user, folder, folder_two, move_url): file = folder.append_file('No I don\'t wanna go') file.checkout = user file.save() signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert 'Cannot move file as it is checked out.' in res.json['errors'][0]['detail'] def test_move_checkedout_file_two_deep_in_folder(self, app, root_node, user, folder, folder_two, move_url): folder_nested = folder.append_folder('Nested') file = folder_nested.append_file('No I don\'t wanna go') file.checkout = user file.save() signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert 'Cannot move file as it is checked out.' in res.json['errors'][0]['detail'] def test_move_file_out_of_node(self, app, user, move_url, root_node, node, node_two, node_two_root_node, folder): # project having a preprint should not block other moves node.preprint_file = root_node.append_file('far') node.save() folder_two = node_two_root_node.append_folder('To There') signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(move_url, signed_payload, expect_errors=False) assert res.status_code == 200 def test_can_move_file_out_of_quickfiles_node(self, app, quickfiles_move_url, quickfiles_file, quickfiles_node, quickfiles_folder, node, user): dest_folder = OsfStorageFolder.objects.get_root(target=node) signed_payload = sign_payload({ 'source': quickfiles_folder._id, 'target': quickfiles_node._id, 'user': user._id, 'destination': { 'parent': dest_folder._id, 'target': node._id, 'name': quickfiles_file.name, } }) res = app.post_json(quickfiles_move_url, signed_payload, expect_errors=False) assert res.status_code == 200 def test_can_rename_file_in_quickfiles_node(self, app, node, user, quickfiles_move_url, quickfiles_node, quickfiles_file, quickfiles_folder): new_name = 'new_file_name.txt' signed_payload = sign_payload({ 'source': quickfiles_file._id, 'target': quickfiles_node._id, 'user': user._id, 'name': quickfiles_file.name, 'destination': { 'parent': quickfiles_folder._id, 'target': quickfiles_node._id, 'name': new_name, } }) res = app.post_json(quickfiles_move_url, signed_payload, expect_errors=False) assert res.status_code == 200 quickfiles_file.reload() assert quickfiles_file.name == new_name assert res.json['name'] == new_name def test_blank_destination_file_name(self, app, move_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': '', } } ) res = app.post_json(move_url, signed_payload, expect_errors=False) assert res.status_code == 200 file.reload() assert file.name == 'test_file' def test_blank_source(self, app, move_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': '', 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'hello.txt', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['source'][0] == 'This field may not be blank.' def test_no_parent(self, app, move_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'target': folder.target._id, 'name': 'hello.txt', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['destination']['parent'][0] == 'This field is required.' def test_rename_file(self, app, move_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'new_file_name', } } ) res = app.post_json(move_url, signed_payload, expect_errors=False) assert res.status_code == 200 file.reload() assert file.name == 'new_file_name' def test_invalid_payload(self, app, move_url): signed_payload = { 'key': 'incorrectly_formed_payload' } res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'Invalid Payload' def test_source_does_not_exist(self, app, move_url, root_node, user, folder): signed_payload = sign_payload( { 'source': '12345', 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'test_file', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 404 def test_parent_does_not_exist(self, app, file, move_url, root_node, user, folder): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': '12345', 'target': folder.target._id, 'name': 'test_file', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 404 def test_node_in_params_does_not_exist(self, app, file, root_node, user, folder): move_url = '/_/wb/hooks/{}/move/'.format('12345') signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'test_file', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 404 def test_storage_usage_move_within_node(self, app, node, signed_payload, move_url): """ Checking moves within a node, since the net value hasn't changed the cache will remain expired at None. """ assert node.storage_usage is None res = app.post_json(move_url, signed_payload) assert res.status_code == 200 assert node.storage_usage is None # this is intentional, the cache shouldn't be touched def test_storage_usage_move_between_nodes(self, app, node, node_two, file, root_node, user, node_two_root_node, move_url): """ Checking storage usage when moving files outside a node mean both need to be recalculated, as both values have changed. """ assert node.storage_usage is None # the cache starts expired, but there is 1337 bytes in there assert node_two.storage_usage is None # zero bytes here signed_payload = sign_payload( { 'source': file._id, 'target': node._id, 'user': user._id, 'destination': { 'parent': node_two_root_node._id, 'target': node_two._id, 'name': 'test_file', } } ) res = app.post_json(move_url, signed_payload) assert res.status_code == 200 assert node.storage_usage is None assert node_two.storage_usage == 1337 @pytest.mark.django_db class TestMovePreprint(): @pytest.fixture() def preprint(self, user): return PreprintFactory(creator=user) @pytest.fixture() def root_node(self, preprint): return preprint.root_folder @pytest.fixture() def file(self, preprint, user): return create_test_preprint_file(preprint, user, 'test_file') @pytest.fixture() def folder(self, root_node, user): return root_node.append_folder('Nina Simone') @pytest.fixture() def move_url(self, preprint): return '/_/wb/hooks/{}/move/'.format(preprint._id) @pytest.fixture() def payload(self, file, folder, root_node, user): return { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': folder.name, } } @pytest.fixture() def signed_payload(self, payload): return sign_payload(payload) def test_move_hook(self, app, move_url, signed_payload, folder, file): res = app.post_json(move_url, signed_payload, expect_errors=False) assert res.status_code == 200 def test_move_checkedout_file(self, app, file, user, move_url, signed_payload): file.checkout = user file.save() res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert b'Cannot move file as it is checked out.' in res._app_iter[0] def test_move_checked_out_file_in_folder(self, app, root_node, user, folder, folder_two, move_url): file = folder.append_file('No I don\'t wanna go') file.checkout = user file.save() signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert 'Cannot move file as it is checked out.' in res.json['errors'][0]['detail'] def test_move_checkedout_file_two_deep_in_folder(self, app, root_node, user, folder, folder_two, move_url): folder_nested = folder.append_folder('Nested') file = folder_nested.append_file('No I don\'t wanna go') file.checkout = user file.save() signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert 'Cannot move file as it is checked out.' in res.json['errors'][0]['detail'] def test_move_primary_file_out_of_node(self, app, user, move_url, root_node, preprint, node_two, node_two_root_node, folder): file = folder.append_file('No I don\'t wanna go') preprint.primary_file = file preprint.save() folder_two = node_two_root_node.append_folder('To There') signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'Cannot move file as it is the primary file of preprint.' # def test_move_file_out_of_node(self, app, user, move_url, root_node, node, node_two, node_two_root_node, folder): # project having a preprint should not block other moves node.preprint_file = root_node.append_file('far') node.save() folder_two = node_two_root_node.append_folder('To There') signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(move_url, signed_payload, expect_errors=False) assert res.status_code == 200 def test_within_preprint_move(self, app, user, move_url, file, preprint, folder, root_node): preprint.primary_file = file preprint.save() signed_payload = sign_payload({ 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': folder.name, } }) res = app.post_json(move_url, signed_payload, expect_errors=False) assert res.status_code == 200 def test_blank_destination_file_name(self, app, move_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': '', } } ) res = app.post_json(move_url, signed_payload, expect_errors=False) assert res.status_code == 200 file.reload() assert file.name == 'test_file' def test_blank_source(self, app, move_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': '', 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'hello.txt', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['source'][0] == 'This field may not be blank.' def test_no_parent(self, app, move_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'target': folder.target._id, 'name': 'hello.txt', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['destination']['parent'][0] == 'This field is required.' def test_rename_file(self, app, move_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'new_file_name', } } ) res = app.post_json(move_url, signed_payload, expect_errors=False) assert res.status_code == 200 file.reload() assert file.name == 'new_file_name' def test_invalid_payload(self, app, move_url): signed_payload = { 'key': 'incorrectly_formed_payload' } res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'Invalid Payload' def test_source_does_not_exist(self, app, move_url, root_node, user, folder): signed_payload = sign_payload( { 'source': '12345', 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'test_file', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 404 def test_parent_does_not_exist(self, app, file, move_url, root_node, user, folder): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': '12345', 'target': folder.target._id, 'name': 'test_file', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 404 def test_preprint_in_params_does_not_exist(self, app, file, root_node, user, folder): move_url = '/_/wb/hooks/{}/move/'.format('12345') signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'test_file', } } ) res = app.post_json(move_url, signed_payload, expect_errors=True) assert res.status_code == 404 @pytest.mark.django_db @pytest.mark.enable_quickfiles_creation @pytest.mark.enable_implicit_clean class TestCopy(): @pytest.fixture() def copy_url(self, node): return '/_/wb/hooks/{}/copy/'.format(node._id) @pytest.fixture() def quickfiles_copy_url(self, quickfiles_node): return '/_/wb/hooks/{}/copy/'.format(quickfiles_node._id) @pytest.fixture() def payload(self, file, folder, root_node, user): return { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': folder.name, } } @pytest.fixture() def signed_payload(self, payload): return sign_payload(payload) def test_copy_hook(self, app, copy_url, signed_payload, folder, file): res = app.post_json(copy_url, signed_payload, expect_errors=False) assert res.status_code == 201 def test_copy_checkedout_file(self, app, file, user, copy_url, signed_payload): file.checkout = user file.save() res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 201 def test_copy_checked_out_file_in_folder(self, app, root_node, user, folder, folder_two, copy_url): file = folder.append_file('No I don\'t wanna go') file.checkout = user file.save() signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 201 def test_copy_checkedout_file_two_deep_in_folder(self, app, root_node, user, folder, folder_two, copy_url): folder_nested = folder.append_folder('Nested') file = folder_nested.append_file('No I don\'t wanna go') file.checkout = user file.save() signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 201 def test_copy_preprint_file_out_of_node(self, app, user, copy_url, root_node, node, node_two, node_two_root_node, folder): file = folder.append_file('No I don\'t wanna go') node.preprint_file = file node.save() folder_two = node_two_root_node.append_folder('To There') signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 201 def test_copy_file_out_of_node(self, app, user, copy_url, root_node, node, node_two, node_two_root_node, folder): node.preprint_file = root_node.append_file('far') node.save() folder_two = node_two_root_node.append_folder('To There') signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=False) assert res.status_code == 201 def test_within_node_copy_while_preprint(self, app, user, copy_url, file, node, folder, root_node): node.preprint_file = file node.save() signed_payload = sign_payload({ 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': folder.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=False) assert res.status_code == 201 def test_can_copy_file_out_of_quickfiles_node(self, app, quickfiles_copy_url, quickfiles_file, quickfiles_node, quickfiles_folder, node, user): dest_folder = OsfStorageFolder.objects.get_root(target=node) signed_payload = sign_payload({ 'source': quickfiles_folder._id, 'target': quickfiles_node._id, 'user': user._id, 'destination': { 'parent': dest_folder._id, 'target': node._id, 'name': quickfiles_file.name, } }) res = app.post_json(quickfiles_copy_url, signed_payload, expect_errors=False) assert res.status_code == 201 def test_blank_destination_file_name(self, app, copy_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': '', } } ) res = app.post_json(copy_url, signed_payload, expect_errors=False) assert res.status_code == 201 file.reload() assert file.name == 'test_file' def test_blank_source(self, app, copy_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': '', 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'hello.txt', } } ) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['source'][0] == 'This field may not be blank.' def test_no_parent(self, app, copy_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'target': folder.target._id, 'name': 'hello.txt', } } ) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['destination']['parent'][0] == 'This field is required.' def test_invalid_payload(self, app, copy_url): signed_payload = { 'key': 'incorrectly_formed_payload' } res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'Invalid Payload' def test_storage_usage_copy_within_node(self, app, node, file, signed_payload, copy_url): """ Checking copys within a node, since the net size will double the storage usage should be the file size * 2 """ assert node.storage_usage is None res = app.post_json(copy_url, signed_payload) assert res.status_code == 201 assert node.storage_usage == file.versions.last().metadata['size'] * 2 def test_storage_usage_copy_between_nodes(self, app, node, node_two, file, user, node_two_root_node, copy_url): """ Checking storage usage when copying files to outside a node means only the destination should be recalculated. """ assert node.storage_usage is None # The node cache starts expired, but there is 1337 bytes in there assert node_two.storage_usage is None # There are zero bytes in node_two signed_payload = sign_payload( { 'source': file._id, 'target': node._id, 'user': user._id, 'destination': { 'parent': node_two_root_node._id, 'target': node_two._id, 'name': 'test_file', } } ) res = app.post_json(copy_url, signed_payload) assert res.status_code == 201 # The node cache is None because it's value should be unchanged -- assert node.storage_usage is None # But there's really 1337 bytes in the node update_storage_usage_cache(node.id, node._id) assert node.storage_usage == 1337 # And we have exactly 1337 bytes copied in node_two assert node_two.storage_usage == 1337 @pytest.mark.django_db @pytest.mark.enable_quickfiles_creation @pytest.mark.enable_implicit_clean class TestCopyPreprint(): @pytest.fixture() def preprint(self, user): return PreprintFactory(creator=user) @pytest.fixture() def root_node(self, preprint): return preprint.root_folder @pytest.fixture() def file(self, preprint, user): return create_test_preprint_file(preprint, user, 'test_file') @pytest.fixture() def folder(self, root_node, user): return root_node.append_folder('Nina Simone') @pytest.fixture() def copy_url(self, preprint): return '/_/wb/hooks/{}/copy/'.format(preprint._id) @pytest.fixture() def payload(self, file, folder, root_node, user): return { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': folder.name, } } @pytest.fixture() def signed_payload(self, payload): return sign_payload(payload) def test_copy_hook(self, app, copy_url, signed_payload, folder, file): res = app.post_json(copy_url, signed_payload, expect_errors=False) assert res.status_code == 201 def test_copy_checkedout_file(self, app, file, user, copy_url, signed_payload): file.checkout = user file.save() res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 201 def test_copy_checked_out_file_in_folder(self, app, root_node, user, folder, folder_two, copy_url): file = folder.append_file('No I don\'t wanna go') file.checkout = user file.save() signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 201 def test_copy_checkedout_file_two_deep_in_folder(self, app, root_node, user, folder, folder_two, copy_url): folder_nested = folder.append_folder('Nested') file = folder_nested.append_file('No I don\'t wanna go') file.checkout = user file.save() signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 201 def test_copy_preprint_file_out_of_preprint(self, app, user, copy_url, root_node, preprint, node_two, node_two_root_node, folder): file = folder.append_file('No I don\'t wanna go') preprint.primary_file = file preprint.save() folder_two = node_two_root_node.append_folder('To There') signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 201 def test_copy_file_out_of_preprint(self, app, user, copy_url, root_node, preprint, node_two, node_two_root_node, folder): preprint.primary_file = root_node.append_file('far') preprint.save() folder_two = node_two_root_node.append_folder('To There') signed_payload = sign_payload({ 'source': folder._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder_two._id, 'target': folder_two.target._id, 'name': folder_two.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=False) assert res.status_code == 201 def test_within_preprint_copy_while_preprint(self, app, user, copy_url, file, preprint, folder, root_node): preprint.primary_file = file preprint.save() signed_payload = sign_payload({ 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': folder.name, } }) res = app.post_json(copy_url, signed_payload, expect_errors=False) assert res.status_code == 201 def test_blank_destination_file_name(self, app, copy_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': '', } } ) res = app.post_json(copy_url, signed_payload, expect_errors=False) assert res.status_code == 201 file.reload() assert file.name == 'test_file' def test_blank_source(self, app, copy_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': '', 'target': root_node._id, 'user': user._id, 'destination': { 'parent': folder._id, 'target': folder.target._id, 'name': 'hello.txt', } } ) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['source'][0] == 'This field may not be blank.' def test_no_parent(self, app, copy_url, user, root_node, folder, file): signed_payload = sign_payload( { 'source': file._id, 'target': root_node._id, 'user': user._id, 'destination': { 'target': folder.target._id, 'name': 'hello.txt', } } ) res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['destination']['parent'][0] == 'This field is required.' def test_invalid_payload(self, app, copy_url): signed_payload = { 'key': 'incorrectly_formed_payload' } res = app.post_json(copy_url, signed_payload, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'Invalid Payload'
apache-2.0
iamroot12a/kernel
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/EventClass.py
4653
3596
# EventClass.py # # This is a library defining some events types classes, which could # be used by other scripts to analyzing the perf samples. # # Currently there are just a few classes defined for examples, # PerfEvent is the base class for all perf event sample, PebsEvent # is a HW base Intel x86 PEBS event, and user could add more SW/HW # event classes based on requirements. import struct # Event types, user could add more here EVTYPE_GENERIC = 0 EVTYPE_PEBS = 1 # Basic PEBS event EVTYPE_PEBS_LL = 2 # PEBS event with load latency info EVTYPE_IBS = 3 # # Currently we don't have good way to tell the event type, but by # the size of raw buffer, raw PEBS event with load latency data's # size is 176 bytes, while the pure PEBS event's size is 144 bytes. # def create_event(name, comm, dso, symbol, raw_buf): if (len(raw_buf) == 144): event = PebsEvent(name, comm, dso, symbol, raw_buf) elif (len(raw_buf) == 176): event = PebsNHM(name, comm, dso, symbol, raw_buf) else: event = PerfEvent(name, comm, dso, symbol, raw_buf) return event class PerfEvent(object): event_num = 0 def __init__(self, name, comm, dso, symbol, raw_buf, ev_type=EVTYPE_GENERIC): self.name = name self.comm = comm self.dso = dso self.symbol = symbol self.raw_buf = raw_buf self.ev_type = ev_type PerfEvent.event_num += 1 def show(self): print "PMU event: name=%12s, symbol=%24s, comm=%8s, dso=%12s" % (self.name, self.symbol, self.comm, self.dso) # # Basic Intel PEBS (Precise Event-based Sampling) event, whose raw buffer # contains the context info when that event happened: the EFLAGS and # linear IP info, as well as all the registers. # class PebsEvent(PerfEvent): pebs_num = 0 def __init__(self, name, comm, dso, symbol, raw_buf, ev_type=EVTYPE_PEBS): tmp_buf=raw_buf[0:80] flags, ip, ax, bx, cx, dx, si, di, bp, sp = struct.unpack('QQQQQQQQQQ', tmp_buf) self.flags = flags self.ip = ip self.ax = ax self.bx = bx self.cx = cx self.dx = dx self.si = si self.di = di self.bp = bp self.sp = sp PerfEvent.__init__(self, name, comm, dso, symbol, raw_buf, ev_type) PebsEvent.pebs_num += 1 del tmp_buf # # Intel Nehalem and Westmere support PEBS plus Load Latency info which lie # in the four 64 bit words write after the PEBS data: # Status: records the IA32_PERF_GLOBAL_STATUS register value # DLA: Data Linear Address (EIP) # DSE: Data Source Encoding, where the latency happens, hit or miss # in L1/L2/L3 or IO operations # LAT: the actual latency in cycles # class PebsNHM(PebsEvent): pebs_nhm_num = 0 def __init__(self, name, comm, dso, symbol, raw_buf, ev_type=EVTYPE_PEBS_LL): tmp_buf=raw_buf[144:176] status, dla, dse, lat = struct.unpack('QQQQ', tmp_buf) self.status = status self.dla = dla self.dse = dse self.lat = lat PebsEvent.__init__(self, name, comm, dso, symbol, raw_buf, ev_type) PebsNHM.pebs_nhm_num += 1 del tmp_buf
gpl-2.0
DREAM-ODA-OS/tools
imgproc/clip_to_mask.py
1
4966
#!/usr/bin/env python #------------------------------------------------------------------------------ # # This tool clips data to mask. Based on the mask value, the code # performs following pixel operations: # mask no-data value (0x00) -> sets pixel to a given no-data value # mask data value (0xFF) -> copies pixel from the original image # # This tool extracts subset of the image specified by the row/column # offset of the upper-left corner and row/column size of extracted # block. The tool takes care of preserving the geo-metadata. # # Author: Martin Paces <martin.paces@eox.at> # #------------------------------------------------------------------------------- # Copyright (C) 2013 EOX IT Services GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies of this Software or works derived from this Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #------------------------------------------------------------------------------- import sys from os.path import basename from numpy import dtype from img import ( FormatOptions, ImageFileReader, create_geotiff, DEF_GEOTIFF_FOPT, Progress, Block, execute, Point2, ) from img.algs import clip_to_mask from img.cli import error def usage(): """Print a short command usage help.""" exe = basename(sys.argv[0]) out = sys.stderr print >>out, ( "USAGE: %s <input image> <mask> <output TIF> <no data value or list>" % exe ) print >>out, "EXAMPLE: %s input.tif mask.tif output.tif 255,255,255" % exe print >>out, "EXAMPLE: %s input.tif mask.tif output.tif 0" % exe def process(tile, img_in, img_mask, img_out, nodata, clipped_mask_value=0): """ Process one tile. """ # pylint: disable=too-many-arguments tile = tile & img_out # clip tile to the image extent b_in = img_in.read(Block(img_in.dtype, tile)) b_mask = img_mask.read(Block(img_mask.dtype, tile)) b_out = clip_to_mask(b_in, b_mask, nodata, clipped_mask_value) img_out.write(b_out) if __name__ == "__main__": FOPTS = FormatOptions(DEF_GEOTIFF_FOPT) # default format options MASKBG = 0x00 MASKFG = 0xFF try: INPUT = sys.argv[1] MASK = sys.argv[2] OUTPUT = sys.argv[3] NODATA = sys.argv[4].split(",") #anything else treated as a format option FOPTS.set_options(sys.argv[5:]) except IndexError: error("Not enough input arguments!") usage() sys.exit(1) # open input image IMG_IN = ImageFileReader(INPUT) # convert no-data values to the image's data type if len(NODATA) == 1 and len(IMG_IN) > 1: NODATA = NODATA * len(IMG_IN) NODATA = [dtype(dt).type(nd) for dt, nd in zip(IMG_IN.dtypes, NODATA)] # open the mask image IMG_MASK = ImageFileReader(MASK) # check mask properties if IMG_MASK.size.z > 1: error("Multi-band masks are not supported!") sys.exit(1) if IMG_MASK.dtype != 'uint8': error("Unsupported mask data type '%s'!" % IMG_MASK.dtype) sys.exit(1) if Point2(IMG_IN.size) != Point2(IMG_MASK.size): error( "Input mask and image must have the same pixel" " size! image: %dx%d mask: %dx%d" % (IMG_IN.size.y, IMG_IN.size.x, IMG_MASK.size.y, IMG_MASK.size.x) ) sys.exit(1) # creation parameters PARAM = { 'path': OUTPUT, 'nrow': IMG_IN.size.y, 'ncol': IMG_IN.size.x, 'nband': IMG_IN.size.z, 'dtype': IMG_IN.dtype, 'options' : FOPTS.options, 'nodata': NODATA, } PARAM.update(IMG_IN.geocoding) # add geo-coding # open output image IMG_OUT = create_geotiff(**PARAM) # block size TILE_SIZE = (int(FOPTS["BLOCKXSIZE"]), int(FOPTS["BLOCKYSIZE"])) print "Clipping image by a mask ..." execute( IMG_OUT.tiles(TILE_SIZE), process, ( IMG_IN, IMG_MASK, IMG_OUT, NODATA, MASKBG, ), progress=Progress(sys.stdout, IMG_OUT.tile_count(TILE_SIZE)), )
mit
RaoUmer/django
tests/regressiontests/forms/tests/util.py
111
3318
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.forms.util import flatatt, ErrorDict, ErrorList from django.test import TestCase from django.utils.safestring import mark_safe from django.utils import six from django.utils.translation import ugettext_lazy from django.utils.encoding import python_2_unicode_compatible class FormsUtilTestCase(TestCase): # Tests for forms/util.py module. def test_flatatt(self): ########### # flatatt # ########### self.assertEqual(flatatt({'id': "header"}), ' id="header"') self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"') self.assertEqual(flatatt({}), '') def test_validation_error(self): ################### # ValidationError # ################### # Can take a string. self.assertHTMLEqual(str(ErrorList(ValidationError("There was an error.").messages)), '<ul class="errorlist"><li>There was an error.</li></ul>') # Can take a unicode string. self.assertHTMLEqual(six.text_type(ErrorList(ValidationError("Not \u03C0.").messages)), '<ul class="errorlist"><li>Not π.</li></ul>') # Can take a lazy string. self.assertHTMLEqual(str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)), '<ul class="errorlist"><li>Error.</li></ul>') # Can take a list. self.assertHTMLEqual(str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), '<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>') # Can take a mixture in a list. self.assertHTMLEqual(str(ErrorList(ValidationError(["First error.", "Not \u03C0.", ugettext_lazy("Error.")]).messages)), '<ul class="errorlist"><li>First error.</li><li>Not π.</li><li>Error.</li></ul>') @python_2_unicode_compatible class VeryBadError: def __str__(self): return "A very bad error." # Can take a non-string. self.assertHTMLEqual(str(ErrorList(ValidationError(VeryBadError()).messages)), '<ul class="errorlist"><li>A very bad error.</li></ul>') # Escapes non-safe input but not input marked safe. example = 'Example of link: <a href="http://www.example.com/">example</a>' self.assertHTMLEqual(str(ErrorList([example])), '<ul class="errorlist"><li>Example of link: &lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>') self.assertHTMLEqual(str(ErrorList([mark_safe(example)])), '<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul>') self.assertHTMLEqual(str(ErrorDict({'name': example})), '<ul class="errorlist"><li>nameExample of link: &lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>') self.assertHTMLEqual(str(ErrorDict({'name': mark_safe(example)})), '<ul class="errorlist"><li>nameExample of link: <a href="http://www.example.com/">example</a></li></ul>')
bsd-3-clause
gregsaun/neversleepeyes
doc/python-gphoto2/examples/set-capture-target.py
1
2316
#!/usr/bin/env python # python-gphoto2 - Python interface to libgphoto2 # http://github.com/jim-easterbrook/python-gphoto2 # Copyright (C) 2015 Jim Easterbrook jim@jim-easterbrook.me.uk # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function import logging import sys import gphoto2 as gp def main(): # use Python logging logging.basicConfig( format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) # get user value if len(sys.argv) != 2: print('One command line parameter required') return 1 try: value = int(sys.argv[1]) except: print('Integer parameter required') return 1 # open camera connection camera = gp.check_result(gp.gp_camera_new()) context = gp.gp_context_new() gp.check_result(gp.gp_camera_init(camera, context)) # get configuration tree config = gp.check_result(gp.gp_camera_get_config(camera, context)) # find the capture target config item capture_target = gp.check_result( gp.gp_widget_get_child_by_name(config, 'capturetarget')) # check value in range count = gp.check_result(gp.gp_widget_count_choices(capture_target)) if value < 0 or value >= count: print('Parameter out of range') return 1 # set value value = gp.check_result(gp.gp_widget_get_choice(capture_target, value)) gp.check_result(gp.gp_widget_set_value(capture_target, value)) # set config gp.check_result(gp.gp_camera_set_config(camera, config, context)) # clean up gp.check_result(gp.gp_camera_exit(camera, context)) return 0 if __name__ == "__main__": sys.exit(main())
gpl-3.0
hwstar/chargectrlr-python-buspirate
chargerctrl/LoadEnableDialog.py
1
2349
__author__ = 'srodgers' from .Dialog import * """ This file is part of chargectrl-python-buspirate. chargectrl-python-buspirate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. chargectrl-python-buspirate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with chargectrl-python-buspirate. If not, see <http://www.gnu.org/licenses/>. """ class LoadEnableDialog(Dialog): def __init__(self, parent, cc, title = None, xoffset=50, yoffset=50): self.cc = cc self.state = "NO" Dialog.__init__(self, parent=parent, title=title, xoffset=xoffset, yoffset=yoffset) # # Dialog body def body(self, master): self.legend = Label(master, text="Load Enabled", width=20) if self.cc.get_load_enable_state(): self.state = 'YES' else: self.state = 'NO' self.field = Label(master, text = self.state, relief=SUNKEN, width=3, background= 'white', foreground='black') self.legend.grid(row=0, column=0, sticky=W) self.field.grid(row=0, column=1, sticky=W) # # Buttons def buttonbox(self): box = Frame(self) self.enabutton = Button(box, text="ENABLE", width=10, command=self.enable) self.enabutton.pack(side=LEFT) self.disabutton = Button(box, text="DISABLE", width=10, command=self.disable, default=ACTIVE) self.disabutton.pack(side=LEFT) self.disabutton = Button(box, text="CLOSE", width=10, command=self.cancel) self.disabutton.pack(side=LEFT) self.bind("<Escape>", self.cancel) box.pack() # # Enable load def enable(self): self.cc.enable_load() self.state = 'YES' self.field.configure(text=self.state) # # Disable load def disable(self): self.cc.disable_load() self.state = 'NO' self.field.configure(text=self.state)
gpl-3.0
HybridF5/nova
nova/scheduler/weights/affinity.py
10
3243
# Copyright (c) 2015 Ericsson AB # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Affinity Weighers. Weigh hosts by the number of instances from a given host. AffinityWeigher implements the soft-affinity policy for server groups by preferring the hosts that has more instances from the given group. AntiAffinityWeigher implements the soft-anti-affinity policy for server groups by preferring the hosts that has less instances from the given group. """ from oslo_config import cfg from oslo_log import log as logging from nova.i18n import _LW from nova.scheduler import weights CONF = cfg.CONF LOG = logging.getLogger(__name__) class _SoftAffinityWeigherBase(weights.BaseHostWeigher): policy_name = None def _weigh_object(self, host_state, request_spec): """Higher weights win.""" if not request_spec.instance_group: return 0 policies = request_spec.instance_group.policies if self.policy_name not in policies: return 0 instances = set(host_state.instances.keys()) members = set(request_spec.instance_group.members) member_on_host = instances.intersection(members) return len(member_on_host) class ServerGroupSoftAffinityWeigher(_SoftAffinityWeigherBase): policy_name = 'soft-affinity' warning_sent = False def weight_multiplier(self): if (CONF.soft_affinity_weight_multiplier < 0 and not self.warning_sent): LOG.warn(_LW('For the soft_affinity_weight_multiplier only a ' 'positive value is meaningful as a negative value ' 'would mean that the affinity weigher would ' 'prefer non-collocating placement.')) self.warning_sent = True return CONF.soft_affinity_weight_multiplier class ServerGroupSoftAntiAffinityWeigher(_SoftAffinityWeigherBase): policy_name = 'soft-anti-affinity' warning_sent = False def weight_multiplier(self): if (CONF.soft_anti_affinity_weight_multiplier < 0 and not self.warning_sent): LOG.warn(_LW('For the soft_anti_affinity_weight_multiplier only a ' 'positive value is meaningful as a negative value ' 'would mean that the anti-affinity weigher would ' 'prefer collocating placement.')) self.warning_sent = True return CONF.soft_anti_affinity_weight_multiplier def _weigh_object(self, host_state, request_spec): weight = super(ServerGroupSoftAntiAffinityWeigher, self)._weigh_object( host_state, request_spec) return -1 * weight
apache-2.0
Shaswat27/sympy
examples/intermediate/partial_differential_eqs.py
115
1985
#!/usr/bin/env python """Partial Differential Equations example Demonstrates various ways to solve partial differential equations """ from sympy import symbols, Eq, Function, pde_separate, pprint, sin, cos, latex from sympy import Derivative as D def main(): r, phi, theta = symbols("r,phi,theta") Xi = Function('Xi') R, Phi, Theta, u = map(Function, ['R', 'Phi', 'Theta', 'u']) C1, C2 = symbols('C1,C2') pprint("Separation of variables in Laplace equation in spherical coordinates") pprint("Laplace equation in spherical coordinates:") eq = Eq(D(Xi(r, phi, theta), r, 2) + 2/r * D(Xi(r, phi, theta), r) + 1/(r**2 * sin(phi)**2) * D(Xi(r, phi, theta), theta, 2) + cos(phi)/(r**2 * sin(phi)) * D(Xi(r, phi, theta), phi) + 1/r**2 * D(Xi(r, phi, theta), phi, 2)) pprint(eq) pprint("We can either separate this equation in regards with variable r:") res_r = pde_separate(eq, Xi(r, phi, theta), [R(r), u(phi, theta)]) pprint(res_r) pprint("Or separate it in regards of theta:") res_theta = pde_separate(eq, Xi(r, phi, theta), [Theta(theta), u(r, phi)]) pprint(res_theta) res_phi = pde_separate(eq, Xi(r, phi, theta), [Phi(phi), u(r, theta)]) pprint("But we cannot separate it in regards of variable phi: ") pprint("Result: %s" % res_phi) pprint("\n\nSo let's make theta dependent part equal with -C1:") eq_theta = Eq(res_theta[0], -C1) pprint(eq_theta) pprint("\nThis also means that second part is also equal to -C1:") eq_left = Eq(res_theta[1], -C1) pprint(eq_left) pprint("\nLets try to separate phi again :)") res_theta = pde_separate(eq_left, u(r, phi), [Phi(phi), R(r)]) pprint("\nThis time it is successful:") pprint(res_theta) pprint("\n\nSo our final equations with separated variables are:") pprint(eq_theta) pprint(Eq(res_theta[0], C2)) pprint(Eq(res_theta[1], C2)) if __name__ == "__main__": main()
bsd-3-clause
chromium2014/src
remoting/tools/build/remoting_copy_locales.py
142
5150
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Helper script to repack paks for a list of locales. Gyp doesn't have any built-in looping capability, so this just provides a way to loop over a list of locales when repacking pak files, thus avoiding a proliferation of mostly duplicate, cut-n-paste gyp actions. """ import optparse import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..', 'tools', 'grit')) from grit.format import data_pack # Some build paths defined by gyp. GRIT_DIR = None INT_DIR = None # The target platform. If it is not defined, sys.platform will be used. OS = None # Extra input files. EXTRA_INPUT_FILES = [] class Usage(Exception): def __init__(self, msg): self.msg = msg def calc_output(locale): """Determine the file that will be generated for the given locale.""" #e.g. '<(INTERMEDIATE_DIR)/remoting_locales/da.pak', if OS == 'mac' or OS == 'ios': # For Cocoa to find the locale at runtime, it needs to use '_' instead # of '-' (http://crbug.com/20441). return os.path.join(INT_DIR, 'remoting', 'resources', '%s.lproj' % locale.replace('-', '_'), 'locale.pak') else: return os.path.join(INT_DIR, 'remoting_locales', locale + '.pak') def calc_inputs(locale): """Determine the files that need processing for the given locale.""" inputs = [] #e.g. '<(grit_out_dir)/remoting/resources/da.pak' inputs.append(os.path.join(GRIT_DIR, 'remoting/resources/%s.pak' % locale)) # Add any extra input files. for extra_file in EXTRA_INPUT_FILES: inputs.append('%s_%s.pak' % (extra_file, locale)) return inputs def list_outputs(locales): """Returns the names of files that will be generated for the given locales. This is to provide gyp the list of output files, so build targets can properly track what needs to be built. """ outputs = [] for locale in locales: outputs.append(calc_output(locale)) # Quote each element so filename spaces don't mess up gyp's attempt to parse # it into a list. return " ".join(['"%s"' % x for x in outputs]) def list_inputs(locales): """Returns the names of files that will be processed for the given locales. This is to provide gyp the list of input files, so build targets can properly track their prerequisites. """ inputs = [] for locale in locales: inputs += calc_inputs(locale) # Quote each element so filename spaces don't mess up gyp's attempt to parse # it into a list. return " ".join(['"%s"' % x for x in inputs]) def repack_locales(locales): """ Loop over and repack the given locales.""" for locale in locales: inputs = calc_inputs(locale) output = calc_output(locale) data_pack.DataPack.RePack(output, inputs) def DoMain(argv): global GRIT_DIR global INT_DIR global OS global EXTRA_INPUT_FILES parser = optparse.OptionParser("usage: %prog [options] locales") parser.add_option("-i", action="store_true", dest="inputs", default=False, help="Print the expected input file list, then exit.") parser.add_option("-o", action="store_true", dest="outputs", default=False, help="Print the expected output file list, then exit.") parser.add_option("-g", action="store", dest="grit_dir", help="GRIT build files output directory.") parser.add_option("-x", action="store", dest="int_dir", help="Intermediate build files output directory.") parser.add_option("-e", action="append", dest="extra_input", default=[], help="Full path to an extra input pak file without the\ locale suffix and \".pak\" extension.") parser.add_option("-p", action="store", dest="os", help="The target OS. (e.g. mac, linux, win, etc.)") options, locales = parser.parse_args(argv) if not locales: parser.error('Please specificy at least one locale to process.\n') print_inputs = options.inputs print_outputs = options.outputs GRIT_DIR = options.grit_dir INT_DIR = options.int_dir EXTRA_INPUT_FILES = options.extra_input OS = options.os if not OS: if sys.platform == 'darwin': OS = 'mac' elif sys.platform.startswith('linux'): OS = 'linux' elif sys.platform in ('cygwin', 'win32'): OS = 'win' else: OS = sys.platform if print_inputs and print_outputs: parser.error('Please specify only one of "-i" or "-o".\n') if print_inputs and not GRIT_DIR: parser.error('Please specify "-g".\n') if print_outputs and not INT_DIR: parser.error('Please specify "-x".\n') if not (print_inputs or print_outputs or (GRIT_DIR and INT_DIR)): parser.error('Please specify both "-g" and "-x".\n') if print_inputs: return list_inputs(locales) if print_outputs: return list_outputs(locales) return repack_locales(locales) if __name__ == '__main__': results = DoMain(sys.argv[1:]) if results: print results
bsd-3-clause
Tehsmash/nova
nova/objects/pci_device.py
16
8982
# Copyright 2013 Intel Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_log import log as logging from oslo_serialization import jsonutils from nova import db from nova import objects from nova.objects import base from nova.objects import fields from nova import utils LOG = logging.getLogger(__name__) def compare_pci_device_attributes(obj_a, obj_b): pci_ignore_fields = base.NovaPersistentObject.fields.keys() for name in obj_a.obj_fields: if name in pci_ignore_fields: continue is_set_a = obj_a.obj_attr_is_set(name) is_set_b = obj_b.obj_attr_is_set(name) if is_set_a != is_set_b: return False if is_set_a: if getattr(obj_a, name) != getattr(obj_b, name): return False return True # TODO(berrange): Remove NovaObjectDictCompat @base.NovaObjectRegistry.register class PciDevice(base.NovaPersistentObject, base.NovaObject, base.NovaObjectDictCompat): """Object to represent a PCI device on a compute node. PCI devices are managed by the compute resource tracker, which discovers the devices from the hardware platform, claims, allocates and frees devices for instances. The PCI device information is permanently maintained in a database. This makes it convenient to get PCI device information, like physical function for a VF device, adjacent switch IP address for a NIC, hypervisor identification for a PCI device, etc. It also provides a convenient way to check device allocation information for administrator purposes. A device can be in available/claimed/allocated/deleted/removed state. A device is available when it is discovered.. A device is claimed prior to being allocated to an instance. Normally the transition from claimed to allocated is quick. However, during a resize operation the transition can take longer, because devices are claimed in prep_resize and allocated in finish_resize. A device becomes removed when hot removed from a node (i.e. not found in the next auto-discover) but not yet synced with the DB. A removed device should not be allocated to any instance, and once deleted from the DB, the device object is changed to deleted state and no longer synced with the DB. Filed notes:: | 'dev_id': | Hypervisor's identification for the device, the string format | is hypervisor specific | 'extra_info': | Device-specific properties like PF address, switch ip address etc. """ # Version 1.0: Initial version # Version 1.1: String attributes updated to support unicode # Version 1.2: added request_id field # Version 1.3: Added field to represent PCI device NUMA node VERSION = '1.3' fields = { 'id': fields.IntegerField(), # Note(yjiang5): the compute_node_id may be None because the pci # device objects are created before the compute node is created in DB 'compute_node_id': fields.IntegerField(nullable=True), 'address': fields.StringField(), 'vendor_id': fields.StringField(), 'product_id': fields.StringField(), 'dev_type': fields.StringField(), 'status': fields.StringField(), 'dev_id': fields.StringField(nullable=True), 'label': fields.StringField(nullable=True), 'instance_uuid': fields.StringField(nullable=True), 'request_id': fields.StringField(nullable=True), 'extra_info': fields.DictOfStringsField(), 'numa_node': fields.IntegerField(nullable=True), } def obj_make_compatible(self, primitive, target_version): target_version = utils.convert_version_to_tuple(target_version) if target_version < (1, 2) and 'request_id' in primitive: del primitive['request_id'] def update_device(self, dev_dict): """Sync the content from device dictionary to device object. The resource tracker updates the available devices periodically. To avoid meaningless syncs with the database, we update the device object only if a value changed. """ # Note(yjiang5): status/instance_uuid should only be updated by # functions like claim/allocate etc. The id is allocated by # database. The extra_info is created by the object. no_changes = ('status', 'instance_uuid', 'id', 'extra_info') map(lambda x: dev_dict.pop(x, None), [key for key in no_changes]) for k, v in dev_dict.items(): if k in self.fields.keys(): self[k] = v else: # Note (yjiang5) extra_info.update does not update # obj_what_changed, set it explicitely extra_info = self.extra_info extra_info.update({k: v}) self.extra_info = extra_info def __init__(self, *args, **kwargs): super(PciDevice, self).__init__(*args, **kwargs) self.obj_reset_changes() self.extra_info = {} def __eq__(self, other): return compare_pci_device_attributes(self, other) def __ne__(self, other): return not (self == other) @staticmethod def _from_db_object(context, pci_device, db_dev): for key in pci_device.fields: if key != 'extra_info': pci_device[key] = db_dev[key] else: extra_info = db_dev.get("extra_info") pci_device.extra_info = jsonutils.loads(extra_info) pci_device._context = context pci_device.obj_reset_changes() return pci_device @base.remotable_classmethod def get_by_dev_addr(cls, context, compute_node_id, dev_addr): db_dev = db.pci_device_get_by_addr( context, compute_node_id, dev_addr) return cls._from_db_object(context, cls(), db_dev) @base.remotable_classmethod def get_by_dev_id(cls, context, id): db_dev = db.pci_device_get_by_id(context, id) return cls._from_db_object(context, cls(), db_dev) @classmethod def create(cls, dev_dict): """Create a PCI device based on hypervisor information. As the device object is just created and is not synced with db yet thus we should not reset changes here for fields from dict. """ pci_device = cls() pci_device.update_device(dev_dict) pci_device.status = 'available' return pci_device @base.remotable def save(self): if self.status == 'removed': self.status = 'deleted' db.pci_device_destroy(self._context, self.compute_node_id, self.address) elif self.status != 'deleted': updates = self.obj_get_changes() if 'extra_info' in updates: updates['extra_info'] = jsonutils.dumps(updates['extra_info']) if updates: db_pci = db.pci_device_update(self._context, self.compute_node_id, self.address, updates) self._from_db_object(self._context, self, db_pci) @base.NovaObjectRegistry.register class PciDeviceList(base.ObjectListBase, base.NovaObject): # Version 1.0: Initial version # PciDevice <= 1.1 # Version 1.1: PciDevice 1.2 VERSION = '1.1' fields = { 'objects': fields.ListOfObjectsField('PciDevice'), } child_versions = { '1.0': '1.1', # NOTE(danms): PciDevice was at 1.1 before we added this '1.1': '1.2', '1.2': '1.3', } def __init__(self, *args, **kwargs): super(PciDeviceList, self).__init__(*args, **kwargs) self.objects = [] self.obj_reset_changes() @base.remotable_classmethod def get_by_compute_node(cls, context, node_id): db_dev_list = db.pci_device_get_all_by_node(context, node_id) return base.obj_make_list(context, cls(context), objects.PciDevice, db_dev_list) @base.remotable_classmethod def get_by_instance_uuid(cls, context, uuid): db_dev_list = db.pci_device_get_all_by_instance_uuid(context, uuid) return base.obj_make_list(context, cls(context), objects.PciDevice, db_dev_list)
apache-2.0
p0cisk/Quantum-GIS
python/plugins/processing/tests/Grass7AlgorithmsRasterTest.py
7
1779
# -*- coding: utf-8 -*- """ *************************************************************************** Grass7AlgorithmsRasterTest.py ----------------------------- Date : May 2016 Copyright : (C) 2016 by Médéric Ribreux Email : mederic dot ribreux at medspx dot fr *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Médéric Ribreux' __date__ = 'May 2016' __copyright__ = '(C) 2016, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = ':%H$' import AlgorithmsTestBase import nose2 import shutil from qgis.testing import ( start_app, unittest ) class TestGrass7AlgorithmsRasterTest(unittest.TestCase, AlgorithmsTestBase.AlgorithmsTest): @classmethod def setUpClass(cls): start_app() from processing.core.Processing import Processing Processing.initialize() cls.cleanup_paths = [] @classmethod def tearDownClass(cls): for path in cls.cleanup_paths: shutil.rmtree(path) def test_definition_file(self): return 'grass7_algorithms_raster_tests.yaml' if __name__ == '__main__': nose2.main()
gpl-2.0
llooker/python_sdk
lookerapi/models/integration.py
1
16072
# coding: utf-8 """ Looker API 3.0 Reference ### Authorization The Looker API uses Looker **API3** credentials for authorization and access control. Looker admins can create API3 credentials on Looker's **Admin/Users** page. Pass API3 credentials to the **/login** endpoint to obtain a temporary access_token. Include that access_token in the Authorization header of Looker API requests. For details, see [Looker API Authorization](https://looker.com/docs/r/api/authorization) ### Client SDKs The Looker API is a RESTful system that should be usable by any programming language capable of making HTTPS requests. Client SDKs for a variety of programming languages can be generated from the Looker API's Swagger JSON metadata to streamline use of the Looker API in your applications. A client SDK for Ruby is available as an example. For more information, see [Looker API Client SDKs](https://looker.com/docs/r/api/client_sdks) ### Try It Out! The 'api-docs' page served by the Looker instance includes 'Try It Out!' buttons for each API method. After logging in with API3 credentials, you can use the \"Try It Out!\" buttons to call the API directly from the documentation page to interactively explore API features and responses. ### Versioning Future releases of Looker will expand this API release-by-release to securely expose more and more of the core power of Looker to API client applications. API endpoints marked as \"beta\" may receive breaking changes without warning. Stable (non-beta) API endpoints should not receive breaking changes in future releases. For more information, see [Looker API Versioning](https://looker.com/docs/r/api/versioning) OpenAPI spec version: 3.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class Integration(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id=None, integration_hub_id=None, label=None, description=None, enabled=None, params=None, supported_formats=None, supported_action_types=None, supported_formattings=None, supported_visualization_formattings=None, supported_download_settings=None, icon_url=None, required_fields=None, can=None): """ Integration - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'id': 'str', 'integration_hub_id': 'int', 'label': 'str', 'description': 'str', 'enabled': 'bool', 'params': 'list[IntegrationParam]', 'supported_formats': 'list[str]', 'supported_action_types': 'list[str]', 'supported_formattings': 'list[str]', 'supported_visualization_formattings': 'list[str]', 'supported_download_settings': 'list[str]', 'icon_url': 'str', 'required_fields': 'list[IntegrationRequiredField]', 'can': 'dict(str, bool)' } self.attribute_map = { 'id': 'id', 'integration_hub_id': 'integration_hub_id', 'label': 'label', 'description': 'description', 'enabled': 'enabled', 'params': 'params', 'supported_formats': 'supported_formats', 'supported_action_types': 'supported_action_types', 'supported_formattings': 'supported_formattings', 'supported_visualization_formattings': 'supported_visualization_formattings', 'supported_download_settings': 'supported_download_settings', 'icon_url': 'icon_url', 'required_fields': 'required_fields', 'can': 'can' } self._id = id self._integration_hub_id = integration_hub_id self._label = label self._description = description self._enabled = enabled self._params = params self._supported_formats = supported_formats self._supported_action_types = supported_action_types self._supported_formattings = supported_formattings self._supported_visualization_formattings = supported_visualization_formattings self._supported_download_settings = supported_download_settings self._icon_url = icon_url self._required_fields = required_fields self._can = can @property def id(self): """ Gets the id of this Integration. ID of the integration. :return: The id of this Integration. :rtype: str """ return self._id @id.setter def id(self, id): """ Sets the id of this Integration. ID of the integration. :param id: The id of this Integration. :type: str """ self._id = id @property def integration_hub_id(self): """ Gets the integration_hub_id of this Integration. ID of the integration hub. :return: The integration_hub_id of this Integration. :rtype: int """ return self._integration_hub_id @integration_hub_id.setter def integration_hub_id(self, integration_hub_id): """ Sets the integration_hub_id of this Integration. ID of the integration hub. :param integration_hub_id: The integration_hub_id of this Integration. :type: int """ self._integration_hub_id = integration_hub_id @property def label(self): """ Gets the label of this Integration. Label for the integration. :return: The label of this Integration. :rtype: str """ return self._label @label.setter def label(self, label): """ Sets the label of this Integration. Label for the integration. :param label: The label of this Integration. :type: str """ self._label = label @property def description(self): """ Gets the description of this Integration. Description of the integration. :return: The description of this Integration. :rtype: str """ return self._description @description.setter def description(self, description): """ Sets the description of this Integration. Description of the integration. :param description: The description of this Integration. :type: str """ self._description = description @property def enabled(self): """ Gets the enabled of this Integration. Whether the integration is available to users. :return: The enabled of this Integration. :rtype: bool """ return self._enabled @enabled.setter def enabled(self, enabled): """ Sets the enabled of this Integration. Whether the integration is available to users. :param enabled: The enabled of this Integration. :type: bool """ self._enabled = enabled @property def params(self): """ Gets the params of this Integration. Array of params for the integration. :return: The params of this Integration. :rtype: list[IntegrationParam] """ return self._params @params.setter def params(self, params): """ Sets the params of this Integration. Array of params for the integration. :param params: The params of this Integration. :type: list[IntegrationParam] """ self._params = params @property def supported_formats(self): """ Gets the supported_formats of this Integration. A list of data formats the integration supports. Valid values are: \"txt\", \"csv\", \"inline_json\", \"json\", \"json_detail\", \"xlsx\", \"html\", \"wysiwyg_pdf\", \"assembled_pdf\", \"wysiwyg_png\", \"csv_zip\". :return: The supported_formats of this Integration. :rtype: list[str] """ return self._supported_formats @supported_formats.setter def supported_formats(self, supported_formats): """ Sets the supported_formats of this Integration. A list of data formats the integration supports. Valid values are: \"txt\", \"csv\", \"inline_json\", \"json\", \"json_detail\", \"xlsx\", \"html\", \"wysiwyg_pdf\", \"assembled_pdf\", \"wysiwyg_png\", \"csv_zip\". :param supported_formats: The supported_formats of this Integration. :type: list[str] """ self._supported_formats = supported_formats @property def supported_action_types(self): """ Gets the supported_action_types of this Integration. A list of action types the integration supports. Valid values are: \"cell\", \"query\", \"dashboard\". :return: The supported_action_types of this Integration. :rtype: list[str] """ return self._supported_action_types @supported_action_types.setter def supported_action_types(self, supported_action_types): """ Sets the supported_action_types of this Integration. A list of action types the integration supports. Valid values are: \"cell\", \"query\", \"dashboard\". :param supported_action_types: The supported_action_types of this Integration. :type: list[str] """ self._supported_action_types = supported_action_types @property def supported_formattings(self): """ Gets the supported_formattings of this Integration. A list of formatting options the integration supports. Valid values are: \"formatted\", \"unformatted\". :return: The supported_formattings of this Integration. :rtype: list[str] """ return self._supported_formattings @supported_formattings.setter def supported_formattings(self, supported_formattings): """ Sets the supported_formattings of this Integration. A list of formatting options the integration supports. Valid values are: \"formatted\", \"unformatted\". :param supported_formattings: The supported_formattings of this Integration. :type: list[str] """ self._supported_formattings = supported_formattings @property def supported_visualization_formattings(self): """ Gets the supported_visualization_formattings of this Integration. A list of visualization formatting options the integration supports. Valid values are: \"apply\", \"noapply\". :return: The supported_visualization_formattings of this Integration. :rtype: list[str] """ return self._supported_visualization_formattings @supported_visualization_formattings.setter def supported_visualization_formattings(self, supported_visualization_formattings): """ Sets the supported_visualization_formattings of this Integration. A list of visualization formatting options the integration supports. Valid values are: \"apply\", \"noapply\". :param supported_visualization_formattings: The supported_visualization_formattings of this Integration. :type: list[str] """ self._supported_visualization_formattings = supported_visualization_formattings @property def supported_download_settings(self): """ Gets the supported_download_settings of this Integration. A list of streaming options the integration supports. Valid values are: \"push\", \"url\". :return: The supported_download_settings of this Integration. :rtype: list[str] """ return self._supported_download_settings @supported_download_settings.setter def supported_download_settings(self, supported_download_settings): """ Sets the supported_download_settings of this Integration. A list of streaming options the integration supports. Valid values are: \"push\", \"url\". :param supported_download_settings: The supported_download_settings of this Integration. :type: list[str] """ self._supported_download_settings = supported_download_settings @property def icon_url(self): """ Gets the icon_url of this Integration. URL to an icon for the integration. :return: The icon_url of this Integration. :rtype: str """ return self._icon_url @icon_url.setter def icon_url(self, icon_url): """ Sets the icon_url of this Integration. URL to an icon for the integration. :param icon_url: The icon_url of this Integration. :type: str """ self._icon_url = icon_url @property def required_fields(self): """ Gets the required_fields of this Integration. A list of descriptions of required fields that this integration is compatible with. If there are multiple entries in this list, the integration requires more than one field. :return: The required_fields of this Integration. :rtype: list[IntegrationRequiredField] """ return self._required_fields @required_fields.setter def required_fields(self, required_fields): """ Sets the required_fields of this Integration. A list of descriptions of required fields that this integration is compatible with. If there are multiple entries in this list, the integration requires more than one field. :param required_fields: The required_fields of this Integration. :type: list[IntegrationRequiredField] """ self._required_fields = required_fields @property def can(self): """ Gets the can of this Integration. Operations the current user is able to perform on this object :return: The can of this Integration. :rtype: dict(str, bool) """ return self._can @can.setter def can(self, can): """ Sets the can of this Integration. Operations the current user is able to perform on this object :param can: The can of this Integration. :type: dict(str, bool) """ self._can = can def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, Integration): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
mit
anthraxx/diffoscope
diffoscope/comparators/rpm_fallback.py
2
1199
# -*- coding: utf-8 -*- # # diffoscope: in-depth comparison of files, archives, and directories # # Copyright © 2015 Jérémy Bobbio <lunar@debian.org> # # diffoscope is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # diffoscope is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with diffoscope. If not, see <https://www.gnu.org/licenses/>. import re from .utils.file import File class AbstractRpmFile(File): RE_FILE_TYPE = re.compile('^RPM\s') class RpmFile(AbstractRpmFile): def compare(self, other, source=None): difference = self.compare_bytes(other) if not difference: return None difference.add_comment('Unable to find Python rpm module. Falling back to binary comparison.') return difference
gpl-3.0
madjelan/scikit-learn
sklearn/utils/stats.py
299
1692
import numpy as np from scipy.stats import rankdata as _sp_rankdata from .fixes import bincount # To remove when we support scipy 0.13 def _rankdata(a, method="average"): """Assign ranks to data, dealing with ties appropriately. Ranks begin at 1. The method argument controls how ranks are assigned to equal values. Parameters ---------- a : array_like The array of values to be ranked. The array is first flattened. method : str, optional The method used to assign ranks to tied elements. The options are 'max'. 'max': The maximum of the ranks that would have been assigned to all the tied values is assigned to each value. Returns ------- ranks : ndarray An array of length equal to the size of a, containing rank scores. Notes ----- We only backport the 'max' method """ if method != "max": raise NotImplementedError() unique_all, inverse = np.unique(a, return_inverse=True) count = bincount(inverse, minlength=unique_all.size) cum_count = count.cumsum() rank = cum_count[inverse] return rank try: _sp_rankdata([1.], 'max') rankdata = _sp_rankdata except TypeError as e: rankdata = _rankdata def _weighted_percentile(array, sample_weight, percentile=50): """Compute the weighted ``percentile`` of ``array`` with ``sample_weight``. """ sorted_idx = np.argsort(array) # Find index of median prediction for each sample weight_cdf = sample_weight[sorted_idx].cumsum() percentile_idx = np.searchsorted( weight_cdf, (percentile / 100.) * weight_cdf[-1]) return array[sorted_idx[percentile_idx]]
bsd-3-clause
linuxium/ubuntu-yakkety
arch/ia64/scripts/unwcheck.py
13143
1714
#!/usr/bin/python # # Usage: unwcheck.py FILE # # This script checks the unwind info of each function in file FILE # and verifies that the sum of the region-lengths matches the total # length of the function. # # Based on a shell/awk script originally written by Harish Patil, # which was converted to Perl by Matthew Chapman, which was converted # to Python by David Mosberger. # import os import re import sys if len(sys.argv) != 2: print "Usage: %s FILE" % sys.argv[0] sys.exit(2) readelf = os.getenv("READELF", "readelf") start_pattern = re.compile("<([^>]*)>: \[0x([0-9a-f]+)-0x([0-9a-f]+)\]") rlen_pattern = re.compile(".*rlen=([0-9]+)") def check_func (func, slots, rlen_sum): if slots != rlen_sum: global num_errors num_errors += 1 if not func: func = "[%#x-%#x]" % (start, end) print "ERROR: %s: %lu slots, total region length = %lu" % (func, slots, rlen_sum) return num_funcs = 0 num_errors = 0 func = False slots = 0 rlen_sum = 0 for line in os.popen("%s -u %s" % (readelf, sys.argv[1])): m = start_pattern.match(line) if m: check_func(func, slots, rlen_sum) func = m.group(1) start = long(m.group(2), 16) end = long(m.group(3), 16) slots = 3 * (end - start) / 16 rlen_sum = 0L num_funcs += 1 else: m = rlen_pattern.match(line) if m: rlen_sum += long(m.group(1)) check_func(func, slots, rlen_sum) if num_errors == 0: print "No errors detected in %u functions." % num_funcs else: if num_errors > 1: err="errors" else: err="error" print "%u %s detected in %u functions." % (num_errors, err, num_funcs) sys.exit(1)
gpl-2.0
Mirdrack/4chanscrapper
lib/python2.7/site-packages/pip/_vendor/html5lib/treewalkers/pulldom.py
1729
2302
from __future__ import absolute_import, division, unicode_literals from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS from . import _base from ..constants import voidElements class TreeWalker(_base.TreeWalker): def __iter__(self): ignore_until = None previous = None for event in self.tree: if previous is not None and \ (ignore_until is None or previous[1] is ignore_until): if previous[1] is ignore_until: ignore_until = None for token in self.tokens(previous, event): yield token if token["type"] == "EmptyTag": ignore_until = previous[1] previous = event if ignore_until is None or previous[1] is ignore_until: for token in self.tokens(previous, None): yield token elif ignore_until is not None: raise ValueError("Illformed DOM event stream: void element without END_ELEMENT") def tokens(self, event, next): type, node = event if type == START_ELEMENT: name = node.nodeName namespace = node.namespaceURI attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) attrs[(attr.namespaceURI, attr.localName)] = attr.value if name in voidElements: for token in self.emptyTag(namespace, name, attrs, not next or next[1] is not node): yield token else: yield self.startTag(namespace, name, attrs) elif type == END_ELEMENT: name = node.nodeName namespace = node.namespaceURI if name not in voidElements: yield self.endTag(namespace, name) elif type == COMMENT: yield self.comment(node.nodeValue) elif type in (IGNORABLE_WHITESPACE, CHARACTERS): for token in self.text(node.nodeValue): yield token else: yield self.unknown(type)
mit
Beyond-Imagination/BlubBlub
ChatbotServer/ChatbotEnv/Lib/site-packages/numpy/add_newdocs.py
12
228205
""" This is only meant to add docs to objects defined in C-extension modules. The purpose is to allow easier editing of the docstrings without requiring a re-compile. NOTE: Many of the methods of ndarray have corresponding functions. If you update these docstrings, please keep also the ones in core/fromnumeric.py, core/defmatrix.py up-to-date. """ from __future__ import division, absolute_import, print_function from numpy.lib import add_newdoc ############################################################################### # # flatiter # # flatiter needs a toplevel description # ############################################################################### add_newdoc('numpy.core', 'flatiter', """ Flat iterator object to iterate over arrays. A `flatiter` iterator is returned by ``x.flat`` for any array `x`. It allows iterating over the array as if it were a 1-D array, either in a for-loop or by calling its `next` method. Iteration is done in row-major, C-style order (the last index varying the fastest). The iterator can also be indexed using basic slicing or advanced indexing. See Also -------- ndarray.flat : Return a flat iterator over an array. ndarray.flatten : Returns a flattened copy of an array. Notes ----- A `flatiter` iterator can not be constructed directly from Python code by calling the `flatiter` constructor. Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> fl = x.flat >>> type(fl) <type 'numpy.flatiter'> >>> for item in fl: ... print(item) ... 0 1 2 3 4 5 >>> fl[2:4] array([2, 3]) """) # flatiter attributes add_newdoc('numpy.core', 'flatiter', ('base', """ A reference to the array that is iterated over. Examples -------- >>> x = np.arange(5) >>> fl = x.flat >>> fl.base is x True """)) add_newdoc('numpy.core', 'flatiter', ('coords', """ An N-dimensional tuple of current coordinates. Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> fl = x.flat >>> fl.coords (0, 0) >>> fl.next() 0 >>> fl.coords (0, 1) """)) add_newdoc('numpy.core', 'flatiter', ('index', """ Current flat index into the array. Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> fl = x.flat >>> fl.index 0 >>> fl.next() 0 >>> fl.index 1 """)) # flatiter functions add_newdoc('numpy.core', 'flatiter', ('__array__', """__array__(type=None) Get array from iterator """)) add_newdoc('numpy.core', 'flatiter', ('copy', """ copy() Get a copy of the iterator as a 1-D array. Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> fl = x.flat >>> fl.copy() array([0, 1, 2, 3, 4, 5]) """)) ############################################################################### # # nditer # ############################################################################### add_newdoc('numpy.core', 'nditer', """ Efficient multi-dimensional iterator object to iterate over arrays. To get started using this object, see the :ref:`introductory guide to array iteration <arrays.nditer>`. Parameters ---------- op : ndarray or sequence of array_like The array(s) to iterate over. flags : sequence of str, optional Flags to control the behavior of the iterator. * "buffered" enables buffering when required. * "c_index" causes a C-order index to be tracked. * "f_index" causes a Fortran-order index to be tracked. * "multi_index" causes a multi-index, or a tuple of indices with one per iteration dimension, to be tracked. * "common_dtype" causes all the operands to be converted to a common data type, with copying or buffering as necessary. * "copy_if_overlap" causes the iterator to determine if read operands have overlap with write operands, and make temporary copies as necessary to avoid overlap. False positives (needless copying) are possible in some cases. * "delay_bufalloc" delays allocation of the buffers until a reset() call is made. Allows "allocate" operands to be initialized before their values are copied into the buffers. * "external_loop" causes the `values` given to be one-dimensional arrays with multiple values instead of zero-dimensional arrays. * "grow_inner" allows the `value` array sizes to be made larger than the buffer size when both "buffered" and "external_loop" is used. * "ranged" allows the iterator to be restricted to a sub-range of the iterindex values. * "refs_ok" enables iteration of reference types, such as object arrays. * "reduce_ok" enables iteration of "readwrite" operands which are broadcasted, also known as reduction operands. * "zerosize_ok" allows `itersize` to be zero. op_flags : list of list of str, optional This is a list of flags for each operand. At minimum, one of "readonly", "readwrite", or "writeonly" must be specified. * "readonly" indicates the operand will only be read from. * "readwrite" indicates the operand will be read from and written to. * "writeonly" indicates the operand will only be written to. * "no_broadcast" prevents the operand from being broadcasted. * "contig" forces the operand data to be contiguous. * "aligned" forces the operand data to be aligned. * "nbo" forces the operand data to be in native byte order. * "copy" allows a temporary read-only copy if required. * "updateifcopy" allows a temporary read-write copy if required. * "allocate" causes the array to be allocated if it is None in the `op` parameter. * "no_subtype" prevents an "allocate" operand from using a subtype. * "arraymask" indicates that this operand is the mask to use for selecting elements when writing to operands with the 'writemasked' flag set. The iterator does not enforce this, but when writing from a buffer back to the array, it only copies those elements indicated by this mask. * 'writemasked' indicates that only elements where the chosen 'arraymask' operand is True will be written to. * "overlap_assume_elementwise" can be used to mark operands that are accessed only in the iterator order, to allow less conservative copying when "copy_if_overlap" is present. op_dtypes : dtype or tuple of dtype(s), optional The required data type(s) of the operands. If copying or buffering is enabled, the data will be converted to/from their original types. order : {'C', 'F', 'A', 'K'}, optional Controls the iteration order. 'C' means C order, 'F' means Fortran order, 'A' means 'F' order if all the arrays are Fortran contiguous, 'C' order otherwise, and 'K' means as close to the order the array elements appear in memory as possible. This also affects the element memory order of "allocate" operands, as they are allocated to be compatible with iteration order. Default is 'K'. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur when making a copy or buffering. Setting this to 'unsafe' is not recommended, as it can adversely affect accumulations. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. op_axes : list of list of ints, optional If provided, is a list of ints or None for each operands. The list of axes for an operand is a mapping from the dimensions of the iterator to the dimensions of the operand. A value of -1 can be placed for entries, causing that dimension to be treated as "newaxis". itershape : tuple of ints, optional The desired shape of the iterator. This allows "allocate" operands with a dimension mapped by op_axes not corresponding to a dimension of a different operand to get a value not equal to 1 for that dimension. buffersize : int, optional When buffering is enabled, controls the size of the temporary buffers. Set to 0 for the default value. Attributes ---------- dtypes : tuple of dtype(s) The data types of the values provided in `value`. This may be different from the operand data types if buffering is enabled. finished : bool Whether the iteration over the operands is finished or not. has_delayed_bufalloc : bool If True, the iterator was created with the "delay_bufalloc" flag, and no reset() function was called on it yet. has_index : bool If True, the iterator was created with either the "c_index" or the "f_index" flag, and the property `index` can be used to retrieve it. has_multi_index : bool If True, the iterator was created with the "multi_index" flag, and the property `multi_index` can be used to retrieve it. index When the "c_index" or "f_index" flag was used, this property provides access to the index. Raises a ValueError if accessed and `has_index` is False. iterationneedsapi : bool Whether iteration requires access to the Python API, for example if one of the operands is an object array. iterindex : int An index which matches the order of iteration. itersize : int Size of the iterator. itviews Structured view(s) of `operands` in memory, matching the reordered and optimized iterator access pattern. multi_index When the "multi_index" flag was used, this property provides access to the index. Raises a ValueError if accessed accessed and `has_multi_index` is False. ndim : int The iterator's dimension. nop : int The number of iterator operands. operands : tuple of operand(s) The array(s) to be iterated over. shape : tuple of ints Shape tuple, the shape of the iterator. value Value of `operands` at current iteration. Normally, this is a tuple of array scalars, but if the flag "external_loop" is used, it is a tuple of one dimensional arrays. Notes ----- `nditer` supersedes `flatiter`. The iterator implementation behind `nditer` is also exposed by the NumPy C API. The Python exposure supplies two iteration interfaces, one which follows the Python iterator protocol, and another which mirrors the C-style do-while pattern. The native Python approach is better in most cases, but if you need the iterator's coordinates or index, use the C-style pattern. Examples -------- Here is how we might write an ``iter_add`` function, using the Python iterator protocol:: def iter_add_py(x, y, out=None): addop = np.add it = np.nditer([x, y, out], [], [['readonly'], ['readonly'], ['writeonly','allocate']]) for (a, b, c) in it: addop(a, b, out=c) return it.operands[2] Here is the same function, but following the C-style pattern:: def iter_add(x, y, out=None): addop = np.add it = np.nditer([x, y, out], [], [['readonly'], ['readonly'], ['writeonly','allocate']]) while not it.finished: addop(it[0], it[1], out=it[2]) it.iternext() return it.operands[2] Here is an example outer product function:: def outer_it(x, y, out=None): mulop = np.multiply it = np.nditer([x, y, out], ['external_loop'], [['readonly'], ['readonly'], ['writeonly', 'allocate']], op_axes=[range(x.ndim)+[-1]*y.ndim, [-1]*x.ndim+range(y.ndim), None]) for (a, b, c) in it: mulop(a, b, out=c) return it.operands[2] >>> a = np.arange(2)+1 >>> b = np.arange(3)+1 >>> outer_it(a,b) array([[1, 2, 3], [2, 4, 6]]) Here is an example function which operates like a "lambda" ufunc:: def luf(lamdaexpr, *args, **kwargs): "luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)" nargs = len(args) op = (kwargs.get('out',None),) + args it = np.nditer(op, ['buffered','external_loop'], [['writeonly','allocate','no_broadcast']] + [['readonly','nbo','aligned']]*nargs, order=kwargs.get('order','K'), casting=kwargs.get('casting','safe'), buffersize=kwargs.get('buffersize',0)) while not it.finished: it[0] = lamdaexpr(*it[1:]) it.iternext() return it.operands[0] >>> a = np.arange(5) >>> b = np.ones(5) >>> luf(lambda i,j:i*i + j/2, a, b) array([ 0.5, 1.5, 4.5, 9.5, 16.5]) """) # nditer methods add_newdoc('numpy.core', 'nditer', ('copy', """ copy() Get a copy of the iterator in its current state. Examples -------- >>> x = np.arange(10) >>> y = x + 1 >>> it = np.nditer([x, y]) >>> it.next() (array(0), array(1)) >>> it2 = it.copy() >>> it2.next() (array(1), array(2)) """)) add_newdoc('numpy.core', 'nditer', ('debug_print', """ debug_print() Print the current state of the `nditer` instance and debug info to stdout. """)) add_newdoc('numpy.core', 'nditer', ('enable_external_loop', """ enable_external_loop() When the "external_loop" was not used during construction, but is desired, this modifies the iterator to behave as if the flag was specified. """)) add_newdoc('numpy.core', 'nditer', ('iternext', """ iternext() Check whether iterations are left, and perform a single internal iteration without returning the result. Used in the C-style pattern do-while pattern. For an example, see `nditer`. Returns ------- iternext : bool Whether or not there are iterations left. """)) add_newdoc('numpy.core', 'nditer', ('remove_axis', """ remove_axis(i) Removes axis `i` from the iterator. Requires that the flag "multi_index" be enabled. """)) add_newdoc('numpy.core', 'nditer', ('remove_multi_index', """ remove_multi_index() When the "multi_index" flag was specified, this removes it, allowing the internal iteration structure to be optimized further. """)) add_newdoc('numpy.core', 'nditer', ('reset', """ reset() Reset the iterator to its initial state. """)) ############################################################################### # # broadcast # ############################################################################### add_newdoc('numpy.core', 'broadcast', """ Produce an object that mimics broadcasting. Parameters ---------- in1, in2, ... : array_like Input parameters. Returns ------- b : broadcast object Broadcast the input parameters against one another, and return an object that encapsulates the result. Amongst others, it has ``shape`` and ``nd`` properties, and may be used as an iterator. See Also -------- broadcast_arrays broadcast_to Examples -------- Manually adding two vectors, using broadcasting: >>> x = np.array([[1], [2], [3]]) >>> y = np.array([4, 5, 6]) >>> b = np.broadcast(x, y) >>> out = np.empty(b.shape) >>> out.flat = [u+v for (u,v) in b] >>> out array([[ 5., 6., 7.], [ 6., 7., 8.], [ 7., 8., 9.]]) Compare against built-in broadcasting: >>> x + y array([[5, 6, 7], [6, 7, 8], [7, 8, 9]]) """) # attributes add_newdoc('numpy.core', 'broadcast', ('index', """ current index in broadcasted result Examples -------- >>> x = np.array([[1], [2], [3]]) >>> y = np.array([4, 5, 6]) >>> b = np.broadcast(x, y) >>> b.index 0 >>> b.next(), b.next(), b.next() ((1, 4), (1, 5), (1, 6)) >>> b.index 3 """)) add_newdoc('numpy.core', 'broadcast', ('iters', """ tuple of iterators along ``self``'s "components." Returns a tuple of `numpy.flatiter` objects, one for each "component" of ``self``. See Also -------- numpy.flatiter Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> row, col = b.iters >>> row.next(), col.next() (1, 4) """)) add_newdoc('numpy.core', 'broadcast', ('ndim', """ Number of dimensions of broadcasted result. Alias for `nd`. .. versionadded:: 1.12.0 Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> b.ndim 2 """)) add_newdoc('numpy.core', 'broadcast', ('nd', """ Number of dimensions of broadcasted result. For code intended for NumPy 1.12.0 and later the more consistent `ndim` is preferred. Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> b.nd 2 """)) add_newdoc('numpy.core', 'broadcast', ('numiter', """ Number of iterators possessed by the broadcasted result. Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> b.numiter 2 """)) add_newdoc('numpy.core', 'broadcast', ('shape', """ Shape of broadcasted result. Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> b.shape (3, 3) """)) add_newdoc('numpy.core', 'broadcast', ('size', """ Total size of broadcasted result. Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> b.size 9 """)) add_newdoc('numpy.core', 'broadcast', ('reset', """ reset() Reset the broadcasted result's iterator(s). Parameters ---------- None Returns ------- None Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]] >>> b = np.broadcast(x, y) >>> b.index 0 >>> b.next(), b.next(), b.next() ((1, 4), (2, 4), (3, 4)) >>> b.index 3 >>> b.reset() >>> b.index 0 """)) ############################################################################### # # numpy functions # ############################################################################### add_newdoc('numpy.core.multiarray', 'array', """ array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0) Create an array. Parameters ---------- object : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (`dtype`, `order`, etc.). order : {'K', 'A', 'C', 'F'}, optional Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless 'F' is specified, in which case it will be in Fortran order (column major). If object is an array the following holds. ===== ========= =================================================== order no copy copy=True ===== ========= =================================================== 'K' unchanged F & C order preserved, otherwise most similar order 'A' unchanged F order if input is F and not C, otherwise C order 'C' C order C order 'F' F order F order ===== ========= =================================================== When ``copy=False`` and a copy is made for other reasons, the result is the same as if ``copy=True``, with some exceptions for `A`, see the Notes section. The default order is 'K'. subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). ndmin : int, optional Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement. Returns ------- out : ndarray An array object satisfying the specified requirements. See Also -------- empty, empty_like, zeros, zeros_like, ones, ones_like, full, full_like Notes ----- When order is 'A' and `object` is an array in neither 'C' nor 'F' order, and a copy is forced by a change in dtype, then the order of the result is not necessarily 'C' as expected. This is likely a bug. Examples -------- >>> np.array([1, 2, 3]) array([1, 2, 3]) Upcasting: >>> np.array([1, 2, 3.0]) array([ 1., 2., 3.]) More than one dimension: >>> np.array([[1, 2], [3, 4]]) array([[1, 2], [3, 4]]) Minimum dimensions 2: >>> np.array([1, 2, 3], ndmin=2) array([[1, 2, 3]]) Type provided: >>> np.array([1, 2, 3], dtype=complex) array([ 1.+0.j, 2.+0.j, 3.+0.j]) Data-type consisting of more than one element: >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')]) >>> x['a'] array([1, 3]) Creating an array from sub-classes: >>> np.array(np.mat('1 2; 3 4')) array([[1, 2], [3, 4]]) >>> np.array(np.mat('1 2; 3 4'), subok=True) matrix([[1, 2], [3, 4]]) """) add_newdoc('numpy.core.multiarray', 'empty', """ empty(shape, dtype=float, order='C') Return a new array of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int Shape of the empty array dtype : data-type, optional Desired output data-type. order : {'C', 'F'}, optional Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory. Returns ------- out : ndarray Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. See Also -------- empty_like, zeros, ones Notes ----- `empty`, unlike `zeros`, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution. Examples -------- >>> np.empty([2, 2]) array([[ -9.74499359e+001, 6.69583040e-309], [ 2.13182611e-314, 3.06959433e-309]]) #random >>> np.empty([2, 2], dtype=int) array([[-1073741821, -1067949133], [ 496041986, 19249760]]) #random """) add_newdoc('numpy.core.multiarray', 'empty_like', """ empty_like(a, dtype=None, order='K', subok=True) Return a new array with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional Overrides the data type of the result. .. versionadded:: 1.6.0 order : {'C', 'F', 'A', or 'K'}, optional Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if ``a`` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of ``a`` as closely as possible. .. versionadded:: 1.6.0 subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. Returns ------- out : ndarray Array of uninitialized (arbitrary) data with the same shape and type as `a`. See Also -------- ones_like : Return an array of ones with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. empty : Return a new uninitialized array. ones : Return a new array setting values to one. zeros : Return a new array setting values to zero. Notes ----- This function does *not* initialize the returned array; to do that use `zeros_like` or `ones_like` instead. It may be marginally faster than the functions that do set the array values. Examples -------- >>> a = ([1,2,3], [4,5,6]) # a is array-like >>> np.empty_like(a) array([[-1073741821, -1073741821, 3], #random [ 0, 0, -1073741821]]) >>> a = np.array([[1., 2., 3.],[4.,5.,6.]]) >>> np.empty_like(a) array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000],#random [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]]) """) add_newdoc('numpy.core.multiarray', 'scalar', """ scalar(dtype, obj) Return a new scalar array of the given type initialized with obj. This function is meant mainly for pickle support. `dtype` must be a valid data-type descriptor. If `dtype` corresponds to an object descriptor, then `obj` can be any object, otherwise `obj` must be a string. If `obj` is not given, it will be interpreted as None for object type and as zeros for all other types. """) add_newdoc('numpy.core.multiarray', 'zeros', """ zeros(shape, dtype=float, order='C') Return a new array of given shape and type, filled with zeros. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Returns ------- out : ndarray Array of zeros with the given shape, dtype, and order. See Also -------- zeros_like : Return an array of zeros with shape and type of input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. ones : Return a new array setting values to one. empty : Return a new uninitialized array. Examples -------- >>> np.zeros(5) array([ 0., 0., 0., 0., 0.]) >>> np.zeros((5,), dtype=np.int) array([0, 0, 0, 0, 0]) >>> np.zeros((2, 1)) array([[ 0.], [ 0.]]) >>> s = (2,2) >>> np.zeros(s) array([[ 0., 0.], [ 0., 0.]]) >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype array([(0, 0), (0, 0)], dtype=[('x', '<i4'), ('y', '<i4')]) """) add_newdoc('numpy.core.multiarray', 'set_typeDict', """set_typeDict(dict) Set the internal dictionary that can look up an array type using a registered code. """) add_newdoc('numpy.core.multiarray', 'fromstring', """ fromstring(string, dtype=float, count=-1, sep='') A new 1-D array initialized from raw binary or text data in a string. Parameters ---------- string : str A string containing the data. dtype : data-type, optional The data type of the array; default: float. For binary input data, the data must be in exactly this format. count : int, optional Read this number of `dtype` elements from the data. If this is negative (the default), the count will be determined from the length of the data. sep : str, optional If not provided or, equivalently, the empty string, the data will be interpreted as binary data; otherwise, as ASCII text with decimal numbers. Also in this latter case, this argument is interpreted as the string separating numbers in the data; extra whitespace between elements is also ignored. Returns ------- arr : ndarray The constructed array. Raises ------ ValueError If the string is not the correct size to satisfy the requested `dtype` and `count`. See Also -------- frombuffer, fromfile, fromiter Examples -------- >>> np.fromstring('\\x01\\x02', dtype=np.uint8) array([1, 2], dtype=uint8) >>> np.fromstring('1 2', dtype=int, sep=' ') array([1, 2]) >>> np.fromstring('1, 2', dtype=int, sep=',') array([1, 2]) >>> np.fromstring('\\x01\\x02\\x03\\x04\\x05', dtype=np.uint8, count=3) array([1, 2, 3], dtype=uint8) """) add_newdoc('numpy.core.multiarray', 'fromiter', """ fromiter(iterable, dtype, count=-1) Create a new 1-dimensional array from an iterable object. Parameters ---------- iterable : iterable object An iterable object providing data for the array. dtype : data-type The data-type of the returned array. count : int, optional The number of items to read from *iterable*. The default is -1, which means all data is read. Returns ------- out : ndarray The output array. Notes ----- Specify `count` to improve performance. It allows ``fromiter`` to pre-allocate the output array, instead of resizing it on demand. Examples -------- >>> iterable = (x*x for x in range(5)) >>> np.fromiter(iterable, np.float) array([ 0., 1., 4., 9., 16.]) """) add_newdoc('numpy.core.multiarray', 'fromfile', """ fromfile(file, dtype=float, count=-1, sep='') Construct an array from data in a text or binary file. A highly efficient way of reading binary data with a known data-type, as well as parsing simply formatted text files. Data written using the `tofile` method can be read using this function. Parameters ---------- file : file or str Open file object or filename. dtype : data-type Data type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file. count : int Number of items to read. ``-1`` means all items (i.e., the complete file). sep : str Separator between items if file is a text file. Empty ("") separator means the file should be treated as binary. Spaces (" ") in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace. See also -------- load, save ndarray.tofile loadtxt : More flexible way of loading data from a text file. Notes ----- Do not rely on the combination of `tofile` and `fromfile` for data storage, as the binary files generated are are not platform independent. In particular, no byte-order or data-type information is saved. Data can be stored in the platform independent ``.npy`` format using `save` and `load` instead. Examples -------- Construct an ndarray: >>> dt = np.dtype([('time', [('min', int), ('sec', int)]), ... ('temp', float)]) >>> x = np.zeros((1,), dtype=dt) >>> x['time']['min'] = 10; x['temp'] = 98.25 >>> x array([((10, 0), 98.25)], dtype=[('time', [('min', '<i4'), ('sec', '<i4')]), ('temp', '<f8')]) Save the raw data to disk: >>> import os >>> fname = os.tmpnam() >>> x.tofile(fname) Read the raw data from disk: >>> np.fromfile(fname, dtype=dt) array([((10, 0), 98.25)], dtype=[('time', [('min', '<i4'), ('sec', '<i4')]), ('temp', '<f8')]) The recommended way to store and load data: >>> np.save(fname, x) >>> np.load(fname + '.npy') array([((10, 0), 98.25)], dtype=[('time', [('min', '<i4'), ('sec', '<i4')]), ('temp', '<f8')]) """) add_newdoc('numpy.core.multiarray', 'frombuffer', """ frombuffer(buffer, dtype=float, count=-1, offset=0) Interpret a buffer as a 1-dimensional array. Parameters ---------- buffer : buffer_like An object that exposes the buffer interface. dtype : data-type, optional Data-type of the returned array; default: float. count : int, optional Number of items to read. ``-1`` means all data in the buffer. offset : int, optional Start reading the buffer from this offset (in bytes); default: 0. Notes ----- If the buffer has data that is not in machine byte-order, this should be specified as part of the data-type, e.g.:: >>> dt = np.dtype(int) >>> dt = dt.newbyteorder('>') >>> np.frombuffer(buf, dtype=dt) The data of the resulting array will not be byteswapped, but will be interpreted correctly. Examples -------- >>> s = 'hello world' >>> np.frombuffer(s, dtype='S1', count=5, offset=6) array(['w', 'o', 'r', 'l', 'd'], dtype='|S1') """) add_newdoc('numpy.core.multiarray', 'concatenate', """ concatenate((a1, a2, ...), axis=0) Join a sequence of arrays along an existing axis. Parameters ---------- a1, a2, ... : sequence of array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int, optional The axis along which the arrays will be joined. Default is 0. Returns ------- res : ndarray The concatenated array. See Also -------- ma.concatenate : Concatenate function that preserves input masks. array_split : Split an array into multiple sub-arrays of equal or near-equal size. split : Split array into a list of multiple sub-arrays of equal size. hsplit : Split array into multiple sub-arrays horizontally (column wise) vsplit : Split array into multiple sub-arrays vertically (row wise) dsplit : Split array into multiple sub-arrays along the 3rd axis (depth). stack : Stack a sequence of arrays along a new axis. hstack : Stack arrays in sequence horizontally (column wise) vstack : Stack arrays in sequence vertically (row wise) dstack : Stack arrays in sequence depth wise (along third dimension) Notes ----- When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are *not* preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead. Examples -------- >>> a = np.array([[1, 2], [3, 4]]) >>> b = np.array([[5, 6]]) >>> np.concatenate((a, b), axis=0) array([[1, 2], [3, 4], [5, 6]]) >>> np.concatenate((a, b.T), axis=1) array([[1, 2, 5], [3, 4, 6]]) This function will not preserve masking of MaskedArray inputs. >>> a = np.ma.arange(3) >>> a[1] = np.ma.masked >>> b = np.arange(2, 5) >>> a masked_array(data = [0 -- 2], mask = [False True False], fill_value = 999999) >>> b array([2, 3, 4]) >>> np.concatenate([a, b]) masked_array(data = [0 1 2 2 3 4], mask = False, fill_value = 999999) >>> np.ma.concatenate([a, b]) masked_array(data = [0 -- 2 2 3 4], mask = [False True False False False False], fill_value = 999999) """) add_newdoc('numpy.core', 'inner', """ inner(a, b) Inner product of two arrays. Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum product over the last axes. Parameters ---------- a, b : array_like If `a` and `b` are nonscalar, their last dimensions must match. Returns ------- out : ndarray `out.shape = a.shape[:-1] + b.shape[:-1]` Raises ------ ValueError If the last dimension of `a` and `b` has different size. See Also -------- tensordot : Sum products over arbitrary axes. dot : Generalised matrix product, using second last dimension of `b`. einsum : Einstein summation convention. Notes ----- For vectors (1-D arrays) it computes the ordinary inner-product:: np.inner(a, b) = sum(a[:]*b[:]) More generally, if `ndim(a) = r > 0` and `ndim(b) = s > 0`:: np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1)) or explicitly:: np.inner(a, b)[i0,...,ir-1,j0,...,js-1] = sum(a[i0,...,ir-1,:]*b[j0,...,js-1,:]) In addition `a` or `b` may be scalars, in which case:: np.inner(a,b) = a*b Examples -------- Ordinary inner product for vectors: >>> a = np.array([1,2,3]) >>> b = np.array([0,1,0]) >>> np.inner(a, b) 2 A multidimensional example: >>> a = np.arange(24).reshape((2,3,4)) >>> b = np.arange(4) >>> np.inner(a, b) array([[ 14, 38, 62], [ 86, 110, 134]]) An example where `b` is a scalar: >>> np.inner(np.eye(2), 7) array([[ 7., 0.], [ 0., 7.]]) """) add_newdoc('numpy.core', 'fastCopyAndTranspose', """_fastCopyAndTranspose(a)""") add_newdoc('numpy.core.multiarray', 'correlate', """cross_correlate(a,v, mode=0)""") add_newdoc('numpy.core.multiarray', 'arange', """ arange([start,] stop[, step,], dtype=None) Return evenly spaced values within a given interval. Values are generated within the half-open interval ``[start, stop)`` (in other words, the interval including `start` but excluding `stop`). For integer arguments the function is equivalent to the Python built-in `range <http://docs.python.org/lib/built-in-funcs.html>`_ function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use ``linspace`` for these cases. Parameters ---------- start : number, optional Start of interval. The interval includes this value. The default start value is 0. stop : number End of interval. The interval does not include this value, except in some cases where `step` is not an integer and floating point round-off affects the length of `out`. step : number, optional Spacing between values. For any output `out`, this is the distance between two adjacent values, ``out[i+1] - out[i]``. The default step size is 1. If `step` is specified, `start` must also be given. dtype : dtype The type of the output array. If `dtype` is not given, infer the data type from the other input arguments. Returns ------- arange : ndarray Array of evenly spaced values. For floating point arguments, the length of the result is ``ceil((stop - start)/step)``. Because of floating point overflow, this rule may result in the last element of `out` being greater than `stop`. See Also -------- linspace : Evenly spaced numbers with careful handling of endpoints. ogrid: Arrays of evenly spaced numbers in N-dimensions. mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions. Examples -------- >>> np.arange(3) array([0, 1, 2]) >>> np.arange(3.0) array([ 0., 1., 2.]) >>> np.arange(3,7) array([3, 4, 5, 6]) >>> np.arange(3,7,2) array([3, 5]) """) add_newdoc('numpy.core.multiarray', '_get_ndarray_c_version', """_get_ndarray_c_version() Return the compile time NDARRAY_VERSION number. """) add_newdoc('numpy.core.multiarray', '_reconstruct', """_reconstruct(subtype, shape, dtype) Construct an empty array. Used by Pickles. """) add_newdoc('numpy.core.multiarray', 'set_string_function', """ set_string_function(f, repr=1) Internal method to set a function to be used when pretty printing arrays. """) add_newdoc('numpy.core.multiarray', 'set_numeric_ops', """ set_numeric_ops(op1=func1, op2=func2, ...) Set numerical operators for array objects. Parameters ---------- op1, op2, ... : callable Each ``op = func`` pair describes an operator to be replaced. For example, ``add = lambda x, y: np.add(x, y) % 5`` would replace addition by modulus 5 addition. Returns ------- saved_ops : list of callables A list of all operators, stored before making replacements. Notes ----- .. WARNING:: Use with care! Incorrect usage may lead to memory errors. A function replacing an operator cannot make use of that operator. For example, when replacing add, you may not use ``+``. Instead, directly call ufuncs. Examples -------- >>> def add_mod5(x, y): ... return np.add(x, y) % 5 ... >>> old_funcs = np.set_numeric_ops(add=add_mod5) >>> x = np.arange(12).reshape((3, 4)) >>> x + x array([[0, 2, 4, 1], [3, 0, 2, 4], [1, 3, 0, 2]]) >>> ignore = np.set_numeric_ops(**old_funcs) # restore operators """) add_newdoc('numpy.core.multiarray', 'where', """ where(condition, [x, y]) Return elements, either from `x` or `y`, depending on `condition`. If only `condition` is given, return ``condition.nonzero()``. Parameters ---------- condition : array_like, bool When True, yield `x`, otherwise yield `y`. x, y : array_like, optional Values from which to choose. `x`, `y` and `condition` need to be broadcastable to some shape. Returns ------- out : ndarray or tuple of ndarrays If both `x` and `y` are specified, the output array contains elements of `x` where `condition` is True, and elements from `y` elsewhere. If only `condition` is given, return the tuple ``condition.nonzero()``, the indices where `condition` is True. See Also -------- nonzero, choose Notes ----- If `x` and `y` are given and input arrays are 1-D, `where` is equivalent to:: [xv if c else yv for (c,xv,yv) in zip(condition,x,y)] Examples -------- >>> np.where([[True, False], [True, True]], ... [[1, 2], [3, 4]], ... [[9, 8], [7, 6]]) array([[1, 8], [3, 4]]) >>> np.where([[0, 1], [1, 0]]) (array([0, 1]), array([1, 0])) >>> x = np.arange(9.).reshape(3, 3) >>> np.where( x > 5 ) (array([2, 2, 2]), array([0, 1, 2])) >>> x[np.where( x > 3.0 )] # Note: result is 1D. array([ 4., 5., 6., 7., 8.]) >>> np.where(x < 5, x, -1) # Note: broadcasting. array([[ 0., 1., 2.], [ 3., 4., -1.], [-1., -1., -1.]]) Find the indices of elements of `x` that are in `goodvalues`. >>> goodvalues = [3, 4, 7] >>> ix = np.isin(x, goodvalues) >>> ix array([[False, False, False], [ True, True, False], [False, True, False]], dtype=bool) >>> np.where(ix) (array([1, 1, 2]), array([0, 1, 1])) """) add_newdoc('numpy.core.multiarray', 'lexsort', """ lexsort(keys, axis=-1) Perform an indirect sort using a sequence of keys. Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, it's rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc. Parameters ---------- keys : (k, N) array or tuple containing k (N,)-shaped sequences The `k` different "columns" to be sorted. The last column (or row if `keys` is a 2D array) is the primary sort key. axis : int, optional Axis to be indirectly sorted. By default, sort over the last axis. Returns ------- indices : (N,) ndarray of ints Array of indices that sort the keys along the specified axis. See Also -------- argsort : Indirect sort. ndarray.sort : In-place sort. sort : Return a sorted copy of an array. Examples -------- Sort names: first by surname, then by name. >>> surnames = ('Hertz', 'Galilei', 'Hertz') >>> first_names = ('Heinrich', 'Galileo', 'Gustav') >>> ind = np.lexsort((first_names, surnames)) >>> ind array([1, 2, 0]) >>> [surnames[i] + ", " + first_names[i] for i in ind] ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich'] Sort two columns of numbers: >>> a = [1,5,1,4,3,4,4] # First column >>> b = [9,4,0,4,0,2,1] # Second column >>> ind = np.lexsort((b,a)) # Sort by a, then by b >>> print(ind) [2 0 4 6 5 3 1] >>> [(a[i],b[i]) for i in ind] [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)] Note that sorting is first according to the elements of ``a``. Secondary sorting is according to the elements of ``b``. A normal ``argsort`` would have yielded: >>> [(a[i],b[i]) for i in np.argsort(a)] [(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)] Structured arrays are sorted lexically by ``argsort``: >>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)], ... dtype=np.dtype([('x', int), ('y', int)])) >>> np.argsort(x) # or np.argsort(x, order=('x', 'y')) array([2, 0, 4, 6, 5, 3, 1]) """) add_newdoc('numpy.core.multiarray', 'can_cast', """ can_cast(from, totype, casting = 'safe') Returns True if cast between data types can occur according to the casting rule. If from is a scalar or array scalar, also returns True if the scalar value can be cast without overflow or truncation to an integer. Parameters ---------- from : dtype, dtype specifier, scalar, or array Data type, scalar, or array to cast from. totype : dtype or dtype specifier Data type to cast to. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. Returns ------- out : bool True if cast can occur according to the casting rule. Notes ----- Starting in NumPy 1.9, can_cast function now returns False in 'safe' casting mode for integer/float dtype and string dtype if the string dtype length is not long enough to store the max integer/float value converted to a string. Previously can_cast in 'safe' mode returned True for integer/float dtype and a string dtype of any length. See also -------- dtype, result_type Examples -------- Basic examples >>> np.can_cast(np.int32, np.int64) True >>> np.can_cast(np.float64, np.complex) True >>> np.can_cast(np.complex, np.float) False >>> np.can_cast('i8', 'f8') True >>> np.can_cast('i8', 'f4') False >>> np.can_cast('i4', 'S4') False Casting scalars >>> np.can_cast(100, 'i1') True >>> np.can_cast(150, 'i1') False >>> np.can_cast(150, 'u1') True >>> np.can_cast(3.5e100, np.float32) False >>> np.can_cast(1000.0, np.float32) True Array scalar checks the value, array does not >>> np.can_cast(np.array(1000.0), np.float32) True >>> np.can_cast(np.array([1000.0]), np.float32) False Using the casting rules >>> np.can_cast('i8', 'i8', 'no') True >>> np.can_cast('<i8', '>i8', 'no') False >>> np.can_cast('<i8', '>i8', 'equiv') True >>> np.can_cast('<i4', '>i8', 'equiv') False >>> np.can_cast('<i4', '>i8', 'safe') True >>> np.can_cast('<i8', '>i4', 'safe') False >>> np.can_cast('<i8', '>i4', 'same_kind') True >>> np.can_cast('<i8', '>u4', 'same_kind') False >>> np.can_cast('<i8', '>u4', 'unsafe') True """) add_newdoc('numpy.core.multiarray', 'promote_types', """ promote_types(type1, type2) Returns the data type with the smallest size and smallest scalar kind to which both ``type1`` and ``type2`` may be safely cast. The returned data type is always in native byte order. This function is symmetric and associative. Parameters ---------- type1 : dtype or dtype specifier First data type. type2 : dtype or dtype specifier Second data type. Returns ------- out : dtype The promoted data type. Notes ----- .. versionadded:: 1.6.0 Starting in NumPy 1.9, promote_types function now returns a valid string length when given an integer or float dtype as one argument and a string dtype as another argument. Previously it always returned the input string dtype, even if it wasn't long enough to store the max integer/float value converted to a string. See Also -------- result_type, dtype, can_cast Examples -------- >>> np.promote_types('f4', 'f8') dtype('float64') >>> np.promote_types('i8', 'f4') dtype('float64') >>> np.promote_types('>i8', '<c8') dtype('complex128') >>> np.promote_types('i4', 'S8') dtype('S11') """) add_newdoc('numpy.core.multiarray', 'min_scalar_type', """ min_scalar_type(a) For scalar ``a``, returns the data type with the smallest size and smallest scalar kind which can hold its value. For non-scalar array ``a``, returns the vector's dtype unmodified. Floating point values are not demoted to integers, and complex values are not demoted to floats. Parameters ---------- a : scalar or array_like The value whose minimal data type is to be found. Returns ------- out : dtype The minimal data type. Notes ----- .. versionadded:: 1.6.0 See Also -------- result_type, promote_types, dtype, can_cast Examples -------- >>> np.min_scalar_type(10) dtype('uint8') >>> np.min_scalar_type(-260) dtype('int16') >>> np.min_scalar_type(3.1) dtype('float16') >>> np.min_scalar_type(1e50) dtype('float64') >>> np.min_scalar_type(np.arange(4,dtype='f8')) dtype('float64') """) add_newdoc('numpy.core.multiarray', 'result_type', """ result_type(*arrays_and_dtypes) Returns the type that results from applying the NumPy type promotion rules to the arguments. Type promotion in NumPy works similarly to the rules in languages like C++, with some slight differences. When both scalars and arrays are used, the array's type takes precedence and the actual value of the scalar is taken into account. For example, calculating 3*a, where a is an array of 32-bit floats, intuitively should result in a 32-bit float output. If the 3 is a 32-bit integer, the NumPy rules indicate it can't convert losslessly into a 32-bit float, so a 64-bit float should be the result type. By examining the value of the constant, '3', we see that it fits in an 8-bit integer, which can be cast losslessly into the 32-bit float. Parameters ---------- arrays_and_dtypes : list of arrays and dtypes The operands of some operation whose result type is needed. Returns ------- out : dtype The result type. See also -------- dtype, promote_types, min_scalar_type, can_cast Notes ----- .. versionadded:: 1.6.0 The specific algorithm used is as follows. Categories are determined by first checking which of boolean, integer (int/uint), or floating point (float/complex) the maximum kind of all the arrays and the scalars are. If there are only scalars or the maximum category of the scalars is higher than the maximum category of the arrays, the data types are combined with :func:`promote_types` to produce the return value. Otherwise, `min_scalar_type` is called on each array, and the resulting data types are all combined with :func:`promote_types` to produce the return value. The set of int values is not a subset of the uint values for types with the same number of bits, something not reflected in :func:`min_scalar_type`, but handled as a special case in `result_type`. Examples -------- >>> np.result_type(3, np.arange(7, dtype='i1')) dtype('int8') >>> np.result_type('i4', 'c8') dtype('complex128') >>> np.result_type(3.0, -2) dtype('float64') """) add_newdoc('numpy.core.multiarray', 'newbuffer', """ newbuffer(size) Return a new uninitialized buffer object. Parameters ---------- size : int Size in bytes of returned buffer object. Returns ------- newbuffer : buffer object Returned, uninitialized buffer object of `size` bytes. """) add_newdoc('numpy.core.multiarray', 'getbuffer', """ getbuffer(obj [,offset[, size]]) Create a buffer object from the given object referencing a slice of length size starting at offset. Default is the entire buffer. A read-write buffer is attempted followed by a read-only buffer. Parameters ---------- obj : object offset : int, optional size : int, optional Returns ------- buffer_obj : buffer Examples -------- >>> buf = np.getbuffer(np.ones(5), 1, 3) >>> len(buf) 3 >>> buf[0] '\\x00' >>> buf <read-write buffer for 0x8af1e70, size 3, offset 1 at 0x8ba4ec0> """) add_newdoc('numpy.core', 'dot', """ dot(a, b, out=None) Dot product of two arrays. For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of `a` and the second-to-last of `b`:: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) Parameters ---------- a : array_like First argument. b : array_like Second argument. out : ndarray, optional Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for `dot(a,b)`. This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. Returns ------- output : ndarray Returns the dot product of `a` and `b`. If `a` and `b` are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If `out` is given, then it is returned. Raises ------ ValueError If the last dimension of `a` is not the same size as the second-to-last dimension of `b`. See Also -------- vdot : Complex-conjugating dot product. tensordot : Sum products over arbitrary axes. einsum : Einstein summation convention. matmul : '@' operator as method with out parameter. Examples -------- >>> np.dot(3, 4) 12 Neither argument is complex-conjugated: >>> np.dot([2j, 3j], [2j, 3j]) (-13+0j) For 2-D arrays it is the matrix product: >>> a = [[1, 0], [0, 1]] >>> b = [[4, 1], [2, 2]] >>> np.dot(a, b) array([[4, 1], [2, 2]]) >>> a = np.arange(3*4*5*6).reshape((3,4,5,6)) >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3)) >>> np.dot(a, b)[2,3,2,1,2,2] 499128 >>> sum(a[2,3,2,:] * b[1,2,:,2]) 499128 """) add_newdoc('numpy.core', 'matmul', """ matmul(a, b, out=None) Matrix product of two arrays. The behavior depends on the arguments in the following way. - If both arguments are 2-D they are multiplied like conventional matrices. - If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly. - If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. - If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. Multiplication by a scalar is not allowed, use ``*`` instead. Note that multiplying a stack of matrices with a vector will result in a stack of vectors, but matmul will not recognize it as such. ``matmul`` differs from ``dot`` in two important ways. - Multiplication by scalars is not allowed. - Stacks of matrices are broadcast together as if the matrices were elements. .. warning:: This function is preliminary and included in NumPy 1.10.0 for testing and documentation. Its semantics will not change, but the number and order of the optional arguments will. .. versionadded:: 1.10.0 Parameters ---------- a : array_like First argument. b : array_like Second argument. out : ndarray, optional Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for `dot(a,b)`. This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. Returns ------- output : ndarray Returns the dot product of `a` and `b`. If `a` and `b` are both 1-D arrays then a scalar is returned; otherwise an array is returned. If `out` is given, then it is returned. Raises ------ ValueError If the last dimension of `a` is not the same size as the second-to-last dimension of `b`. If scalar value is passed. See Also -------- vdot : Complex-conjugating dot product. tensordot : Sum products over arbitrary axes. einsum : Einstein summation convention. dot : alternative matrix product with different broadcasting rules. Notes ----- The matmul function implements the semantics of the `@` operator introduced in Python 3.5 following PEP465. Examples -------- For 2-D arrays it is the matrix product: >>> a = [[1, 0], [0, 1]] >>> b = [[4, 1], [2, 2]] >>> np.matmul(a, b) array([[4, 1], [2, 2]]) For 2-D mixed with 1-D, the result is the usual. >>> a = [[1, 0], [0, 1]] >>> b = [1, 2] >>> np.matmul(a, b) array([1, 2]) >>> np.matmul(b, a) array([1, 2]) Broadcasting is conventional for stacks of arrays >>> a = np.arange(2*2*4).reshape((2,2,4)) >>> b = np.arange(2*2*4).reshape((2,4,2)) >>> np.matmul(a,b).shape (2, 2, 2) >>> np.matmul(a,b)[0,1,1] 98 >>> sum(a[0,1,:] * b[0,:,1]) 98 Vector, vector returns the scalar inner product, but neither argument is complex-conjugated: >>> np.matmul([2j, 3j], [2j, 3j]) (-13+0j) Scalar multiplication raises an error. >>> np.matmul([1,2], 3) Traceback (most recent call last): ... ValueError: Scalar operands are not allowed, use '*' instead """) add_newdoc('numpy.core', 'c_einsum', """ c_einsum(subscripts, *operands, out=None, dtype=None, order='K', casting='safe') Evaluates the Einstein summation convention on the operands. Using the Einstein summation convention, many common multi-dimensional array operations can be represented in a simple fashion. This function provides a way to compute such summations. The best way to understand this function is to try the examples below, which show how many common NumPy functions can be implemented as calls to `einsum`. This is the core C function. Parameters ---------- subscripts : str Specifies the subscripts for summation. operands : list of array_like These are the arrays for the operation. out : ndarray, optional If provided, the calculation is done into this array. dtype : {data-type, None}, optional If provided, forces the calculation to use the data type specified. Note that you may have to also give a more liberal `casting` parameter to allow the conversions. Default is None. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the output. 'C' means it should be C contiguous. 'F' means it should be Fortran contiguous, 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise. 'K' means it should be as close to the layout as the inputs as is possible, including arbitrarily permuted axes. Default is 'K'. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. Setting this to 'unsafe' is not recommended, as it can adversely affect accumulations. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. Default is 'safe'. Returns ------- output : ndarray The calculation based on the Einstein summation convention. See Also -------- einsum, dot, inner, outer, tensordot Notes ----- .. versionadded:: 1.6.0 The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand. Repeated subscripts labels in one operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent to ``np.trace(a)``. Whenever a label is repeated, it is summed, so ``np.einsum('i,i', a, b)`` is equivalent to ``np.inner(a,b)``. If a label appears only once, it is not summed, so ``np.einsum('i', a)`` produces a view of ``a`` with no changes. The order of labels in the output is by default alphabetical. This means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while ``np.einsum('ji', a)`` takes its transpose. The output can be controlled by specifying output subscript labels as well. This specifies the label order, and allows summing to be disallowed or forced when desired. The call ``np.einsum('i->', a)`` is like ``np.sum(a, axis=-1)``, and ``np.einsum('ii->i', a)`` is like ``np.diag(a)``. The difference is that `einsum` does not allow broadcasting by default. To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like ``np.einsum('...ii->...i', a)``. To take the trace along the first and last axes, you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix product with the left-most indices instead of rightmost, you can do ``np.einsum('ij...,jk...->ik...', a, b)``. When there is only one operand, no axes are summed, and no output parameter is provided, a view into the operand is returned instead of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)`` produces a view. An alternative way to provide the subscripts and operands is as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``. The examples below have corresponding `einsum` calls with the two parameter methods. .. versionadded:: 1.10.0 Views returned from einsum are now writeable whenever the input array is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now have the same effect as ``np.swapaxes(a, 0, 2)`` and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal of a 2D array. Examples -------- >>> a = np.arange(25).reshape(5,5) >>> b = np.arange(5) >>> c = np.arange(6).reshape(2,3) >>> np.einsum('ii', a) 60 >>> np.einsum(a, [0,0]) 60 >>> np.trace(a) 60 >>> np.einsum('ii->i', a) array([ 0, 6, 12, 18, 24]) >>> np.einsum(a, [0,0], [0]) array([ 0, 6, 12, 18, 24]) >>> np.diag(a) array([ 0, 6, 12, 18, 24]) >>> np.einsum('ij,j', a, b) array([ 30, 80, 130, 180, 230]) >>> np.einsum(a, [0,1], b, [1]) array([ 30, 80, 130, 180, 230]) >>> np.dot(a, b) array([ 30, 80, 130, 180, 230]) >>> np.einsum('...j,j', a, b) array([ 30, 80, 130, 180, 230]) >>> np.einsum('ji', c) array([[0, 3], [1, 4], [2, 5]]) >>> np.einsum(c, [1,0]) array([[0, 3], [1, 4], [2, 5]]) >>> c.T array([[0, 3], [1, 4], [2, 5]]) >>> np.einsum('..., ...', 3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.einsum(3, [Ellipsis], c, [Ellipsis]) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.multiply(3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.einsum('i,i', b, b) 30 >>> np.einsum(b, [0], b, [0]) 30 >>> np.inner(b,b) 30 >>> np.einsum('i,j', np.arange(2)+1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.einsum(np.arange(2)+1, [0], b, [1]) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.outer(np.arange(2)+1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.einsum('i...->...', a) array([50, 55, 60, 65, 70]) >>> np.einsum(a, [0,Ellipsis], [Ellipsis]) array([50, 55, 60, 65, 70]) >>> np.sum(a, axis=0) array([50, 55, 60, 65, 70]) >>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> np.einsum('ijk,jil->kl', a, b) array([[ 4400., 4730.], [ 4532., 4874.], [ 4664., 5018.], [ 4796., 5162.], [ 4928., 5306.]]) >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3]) array([[ 4400., 4730.], [ 4532., 4874.], [ 4664., 5018.], [ 4796., 5162.], [ 4928., 5306.]]) >>> np.tensordot(a,b, axes=([1,0],[0,1])) array([[ 4400., 4730.], [ 4532., 4874.], [ 4664., 5018.], [ 4796., 5162.], [ 4928., 5306.]]) >>> a = np.arange(6).reshape((3,2)) >>> b = np.arange(12).reshape((4,3)) >>> np.einsum('ki,jk->ij', a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) >>> np.einsum('ki,...k->i...', a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) >>> np.einsum('k...,jk', a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) >>> # since version 1.10.0 >>> a = np.zeros((3, 3)) >>> np.einsum('ii->i', a)[:] = 1 >>> a array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) """) add_newdoc('numpy.core', 'vdot', """ vdot(a, b) Return the dot product of two vectors. The vdot(`a`, `b`) function handles complex numbers differently than dot(`a`, `b`). If the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product. Note that `vdot` handles multidimensional arrays differently than `dot`: it does *not* perform a matrix product, but flattens input arguments to 1-D vectors first. Consequently, it should only be used for vectors. Parameters ---------- a : array_like If `a` is complex the complex conjugate is taken before calculation of the dot product. b : array_like Second argument to the dot product. Returns ------- output : ndarray Dot product of `a` and `b`. Can be an int, float, or complex depending on the types of `a` and `b`. See Also -------- dot : Return the dot product without using the complex conjugate of the first argument. Examples -------- >>> a = np.array([1+2j,3+4j]) >>> b = np.array([5+6j,7+8j]) >>> np.vdot(a, b) (70-8j) >>> np.vdot(b, a) (70+8j) Note that higher-dimensional arrays are flattened! >>> a = np.array([[1, 4], [5, 6]]) >>> b = np.array([[4, 1], [2, 2]]) >>> np.vdot(a, b) 30 >>> np.vdot(b, a) 30 >>> 1*4 + 4*1 + 5*2 + 6*2 30 """) ############################################################################## # # Documentation for ndarray attributes and methods # ############################################################################## ############################################################################## # # ndarray object # ############################################################################## add_newdoc('numpy.core.multiarray', 'ndarray', """ ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None) An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using `array`, `zeros` or `empty` (refer to the See Also section below). The parameters given here refer to a low-level method (`ndarray(...)`) for instantiating an array. For more information, refer to the `numpy` module and examine the methods and attributes of an array. Parameters ---------- (for the __new__ method; see Notes below) shape : tuple of ints Shape of created array. dtype : data-type, optional Any object that can be interpreted as a numpy data type. buffer : object exposing buffer interface, optional Used to fill the array with data. offset : int, optional Offset of array data in buffer. strides : tuple of ints, optional Strides of data in memory. order : {'C', 'F'}, optional Row-major (C-style) or column-major (Fortran-style) order. Attributes ---------- T : ndarray Transpose of the array. data : buffer The array's elements, in memory. dtype : dtype object Describes the format of the elements in the array. flags : dict Dictionary containing information related to memory use, e.g., 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc. flat : numpy.flatiter object Flattened version of the array as an iterator. The iterator allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for assignment examples; TODO). imag : ndarray Imaginary part of the array. real : ndarray Real part of the array. size : int Number of elements in the array. itemsize : int The memory use of each array element in bytes. nbytes : int The total number of bytes required to store the array data, i.e., ``itemsize * size``. ndim : int The array's number of dimensions. shape : tuple of ints Shape of the array. strides : tuple of ints The step-size required to move from one element to the next in memory. For example, a contiguous ``(3, 4)`` array of type ``int16`` in C-order has strides ``(8, 2)``. This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (``2 * 4``). ctypes : ctypes object Class containing properties of the array needed for interaction with ctypes. base : ndarray If the array is a view into another array, that array is its `base` (unless that array is also a view). The `base` array is where the array data is actually stored. See Also -------- array : Construct an array. zeros : Create an array, each element of which is zero. empty : Create an array, but leave its allocated memory unchanged (i.e., it contains "garbage"). dtype : Create a data-type. Notes ----- There are two modes of creating an array using ``__new__``: 1. If `buffer` is None, then only `shape`, `dtype`, and `order` are used. 2. If `buffer` is an object exposing the buffer interface, then all keywords are interpreted. No ``__init__`` method is needed because the array is fully initialized after the ``__new__`` method. Examples -------- These examples illustrate the low-level `ndarray` constructor. Refer to the `See Also` section above for easier ways of constructing an ndarray. First mode, `buffer` is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F') array([[ -1.13698227e+002, 4.25087011e-303], [ 2.88528414e-306, 3.27025015e-309]]) #random Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3]) """) ############################################################################## # # ndarray attributes # ############################################################################## add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_interface__', """Array protocol: Python side.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_finalize__', """None.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_priority__', """Array priority.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_struct__', """Array protocol: C-struct side.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('_as_parameter_', """Allow the array to be interpreted as a ctypes object by returning the data-memory location as an integer """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('base', """ Base object if memory is from some other object. Examples -------- The base of an array that owns its memory is None: >>> x = np.array([1,2,3,4]) >>> x.base is None True Slicing creates a view, whose memory is shared with x: >>> y = x[2:] >>> y.base is x True """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('ctypes', """ An object to simplify the interaction of the array with the ctypes module. This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library. Parameters ---------- None Returns ------- c : Python object Possessing attributes data, shape, strides, etc. See Also -------- numpy.ctypeslib Notes ----- Below are the public attributes of this object which were documented in "Guide to NumPy" (we have omitted undocumented public attributes, as well as documented private attributes): * data: A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as self._array_interface_['data'][0]. * shape (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corresponding to dtype('p') on this platform. This base-type could be c_int, c_long, or c_longlong depending on the platform. The c_intp type is defined accordingly in numpy.ctypeslib. The ctypes array contains the shape of the underlying array. * strides (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array. * data_as(obj): Return the data pointer cast to a particular c-types object. For example, calling self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)). * shape_as(obj): Return the shape tuple as an array of some other c-types type. For example: self.shape_as(ctypes.c_short). * strides_as(obj): Return the strides tuple as an array of some other c-types type. For example: self.strides_as(ctypes.c_longlong). Be careful using the ctypes attribute - especially on temporary arrays or arrays constructed on the fly. For example, calling ``(a+b).ctypes.data_as(ctypes.c_void_p)`` returns a pointer to memory that is invalid because the array created as (a+b) is deallocated before the next Python statement. You can avoid this problem using either ``c=a+b`` or ``ct=(a+b).ctypes``. In the latter case, ct will hold a reference to the array until ct is deleted or re-assigned. If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as parameter attribute which will return an integer equal to the data attribute. Examples -------- >>> import ctypes >>> x array([[0, 1], [2, 3]]) >>> x.ctypes.data 30439712 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_long)) <ctypes.LP_c_long object at 0x01F01300> >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_long)).contents c_long(0) >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_longlong)).contents c_longlong(4294967296L) >>> x.ctypes.shape <numpy.core._internal.c_long_Array_2 object at 0x01FFD580> >>> x.ctypes.shape_as(ctypes.c_long) <numpy.core._internal.c_long_Array_2 object at 0x01FCE620> >>> x.ctypes.strides <numpy.core._internal.c_long_Array_2 object at 0x01FCE620> >>> x.ctypes.strides_as(ctypes.c_longlong) <numpy.core._internal.c_longlong_Array_2 object at 0x01F01300> """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('data', """Python buffer object pointing to the start of the array's data.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('dtype', """ Data-type of the array's elements. Parameters ---------- None Returns ------- d : numpy dtype object See Also -------- numpy.dtype Examples -------- >>> x array([[0, 1], [2, 3]]) >>> x.dtype dtype('int32') >>> type(x.dtype) <type 'numpy.dtype'> """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('imag', """ The imaginary part of the array. Examples -------- >>> x = np.sqrt([1+0j, 0+1j]) >>> x.imag array([ 0. , 0.70710678]) >>> x.imag.dtype dtype('float64') """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('itemsize', """ Length of one array element in bytes. Examples -------- >>> x = np.array([1,2,3], dtype=np.float64) >>> x.itemsize 8 >>> x = np.array([1,2,3], dtype=np.complex128) >>> x.itemsize 16 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('flags', """ Information about the memory layout of the array. Attributes ---------- C_CONTIGUOUS (C) The data is in a single, C-style contiguous segment. F_CONTIGUOUS (F) The data is in a single, Fortran-style contiguous segment. OWNDATA (O) The array owns the memory it uses or borrows it from another object. WRITEABLE (W) The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception. ALIGNED (A) The data and all elements are aligned appropriately for the hardware. UPDATEIFCOPY (U) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array. FNC F_CONTIGUOUS and not C_CONTIGUOUS. FORC F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). BEHAVED (B) ALIGNED and WRITEABLE. CARRAY (CA) BEHAVED and C_CONTIGUOUS. FARRAY (FA) BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS. Notes ----- The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``), or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag names are only supported in dictionary access. Only the UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling `ndarray.setflags`. The array flags cannot be set arbitrarily: - UPDATEIFCOPY can only be set ``False``. - ALIGNED can only be set ``True`` if the data is truly aligned. - WRITEABLE can only be set ``True`` if the array owns its own memory or the ultimate owner of the memory exposes a writeable buffer interface or is a string. Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays. Even for contiguous arrays a stride for a given dimension ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1`` or the array has no elements. It does *not* generally hold that ``self.strides[-1] == self.itemsize`` for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for Fortran-style contiguous arrays is true. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('flat', """ A 1-D iterator over the array. This is a `numpy.flatiter` instance, which acts similarly to, but is not a subclass of, Python's built-in iterator object. See Also -------- flatten : Return a copy of the array collapsed into one dimension. flatiter Examples -------- >>> x = np.arange(1, 7).reshape(2, 3) >>> x array([[1, 2, 3], [4, 5, 6]]) >>> x.flat[3] 4 >>> x.T array([[1, 4], [2, 5], [3, 6]]) >>> x.T.flat[3] 5 >>> type(x.flat) <type 'numpy.flatiter'> An assignment example: >>> x.flat = 3; x array([[3, 3, 3], [3, 3, 3]]) >>> x.flat[[1,4]] = 1; x array([[3, 1, 3], [3, 1, 3]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('nbytes', """ Total bytes consumed by the elements of the array. Notes ----- Does not include memory consumed by non-element attributes of the array object. Examples -------- >>> x = np.zeros((3,5,2), dtype=np.complex128) >>> x.nbytes 480 >>> np.prod(x.shape) * x.itemsize 480 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('ndim', """ Number of array dimensions. Examples -------- >>> x = np.array([1, 2, 3]) >>> x.ndim 1 >>> y = np.zeros((2, 3, 4)) >>> y.ndim 3 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('real', """ The real part of the array. Examples -------- >>> x = np.sqrt([1+0j, 0+1j]) >>> x.real array([ 1. , 0.70710678]) >>> x.real.dtype dtype('float64') See Also -------- numpy.real : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('shape', """ Tuple of array dimensions. Notes ----- May be used to "reshape" the array, as long as this would not require a change in the total number of elements Examples -------- >>> x = np.array([1, 2, 3, 4]) >>> x.shape (4,) >>> y = np.zeros((2, 3, 4)) >>> y.shape (2, 3, 4) >>> y.shape = (3, 8) >>> y array([[ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.]]) >>> y.shape = (3, 6) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: total size of new array must be unchanged """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('size', """ Number of elements in the array. Equivalent to ``np.prod(a.shape)``, i.e., the product of the array's dimensions. Examples -------- >>> x = np.zeros((3, 5, 2), dtype=np.complex128) >>> x.size 30 >>> np.prod(x.shape) 30 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('strides', """ Tuple of bytes to step in each dimension when traversing an array. The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a` is:: offset = sum(np.array(i) * a.strides) A more detailed explanation of strides can be found in the "ndarray.rst" file in the NumPy reference guide. Notes ----- Imagine an array of 32-bit integers (each 4 bytes):: x = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=np.int32) This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array `x` will be ``(20, 4)``. See Also -------- numpy.lib.stride_tricks.as_strided Examples -------- >>> y = np.reshape(np.arange(2*3*4), (2,3,4)) >>> y array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]) >>> y.strides (48, 16, 4) >>> y[1,1,1] 17 >>> offset=sum(y.strides * np.array((1,1,1))) >>> offset/y.itemsize 17 >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0) >>> x.strides (32, 4, 224, 1344) >>> i = np.array([3,5,2,2]) >>> offset = sum(i * x.strides) >>> x[3,5,2,2] 813 >>> offset / x.itemsize 813 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('T', """ Same as self.transpose(), except that self is returned if self.ndim < 2. Examples -------- >>> x = np.array([[1.,2.],[3.,4.]]) >>> x array([[ 1., 2.], [ 3., 4.]]) >>> x.T array([[ 1., 3.], [ 2., 4.]]) >>> x = np.array([1.,2.,3.,4.]) >>> x array([ 1., 2., 3., 4.]) >>> x.T array([ 1., 2., 3., 4.]) """)) ############################################################################## # # ndarray methods # ############################################################################## add_newdoc('numpy.core.multiarray', 'ndarray', ('__array__', """ a.__array__(|dtype) -> reference if type unchanged, copy otherwise. Returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_prepare__', """a.__array_prepare__(obj) -> Object of same type as ndarray object obj. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_wrap__', """a.__array_wrap__(obj) -> Object of same type as ndarray object a. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__copy__', """a.__copy__([order]) Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A'}, optional If order is 'C' (False) then the result is contiguous (default). If order is 'Fortran' (True) then the result has fortran order. If order is 'Any' (None) then the result has fortran order only if the array already is in fortran order. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__deepcopy__', """a.__deepcopy__() -> Deep copy of array. Used if copy.deepcopy is called on an array. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__reduce__', """a.__reduce__() For pickling. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__setstate__', """a.__setstate__(version, shape, dtype, isfortran, rawdata) For unpickling. Parameters ---------- version : int optional pickle version. If omitted defaults to 0. shape : tuple dtype : data-type isFortran : bool rawdata : string or list a binary string with the data (or a list if 'a' is an object array) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('all', """ a.all(axis=None, out=None, keepdims=False) Returns True if all elements evaluate to True. Refer to `numpy.all` for full documentation. See Also -------- numpy.all : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('any', """ a.any(axis=None, out=None, keepdims=False) Returns True if any of the elements of `a` evaluate to True. Refer to `numpy.any` for full documentation. See Also -------- numpy.any : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('argmax', """ a.argmax(axis=None, out=None) Return indices of the maximum values along the given axis. Refer to `numpy.argmax` for full documentation. See Also -------- numpy.argmax : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('argmin', """ a.argmin(axis=None, out=None) Return indices of the minimum values along the given axis of `a`. Refer to `numpy.argmin` for detailed documentation. See Also -------- numpy.argmin : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort', """ a.argsort(axis=-1, kind='quicksort', order=None) Returns the indices that would sort this array. Refer to `numpy.argsort` for full documentation. See Also -------- numpy.argsort : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('argpartition', """ a.argpartition(kth, axis=-1, kind='introselect', order=None) Returns the indices that would partition this array. Refer to `numpy.argpartition` for full documentation. .. versionadded:: 1.8.0 See Also -------- numpy.argpartition : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('astype', """ a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True) Copy of the array, cast to a specified type. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout order of the result. 'C' means C order, 'F' means Fortran order, 'A' means 'F' order if all the arrays are Fortran contiguous, 'C' order otherwise, and 'K' means as close to the order the array elements appear in memory as possible. Default is 'K'. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. Defaults to 'unsafe' for backwards compatibility. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. subok : bool, optional If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array. copy : bool, optional By default, astype always returns a newly allocated array. If this is set to false, and the `dtype`, `order`, and `subok` requirements are satisfied, the input array is returned instead of a copy. Returns ------- arr_t : ndarray Unless `copy` is False and the other conditions for returning the input array are satisfied (see description for `copy` input parameter), `arr_t` is a new array of the same shape as the input array, with dtype, order given by `dtype`, `order`. Notes ----- Starting in NumPy 1.9, astype method now returns an error if the string dtype to cast to is not long enough in 'safe' casting mode to hold the max value of integer/float array that is being casted. Previously the casting was allowed even if the result was truncated. Raises ------ ComplexWarning When casting from complex to float or int. To avoid this, one should use ``a.real.astype(t)``. Examples -------- >>> x = np.array([1, 2, 2.5]) >>> x array([ 1. , 2. , 2.5]) >>> x.astype(int) array([1, 2, 2]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('byteswap', """ a.byteswap(inplace) Swap the bytes of the array elements Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Parameters ---------- inplace : bool, optional If ``True``, swap bytes in-place, default is ``False``. Returns ------- out : ndarray The byteswapped array. If `inplace` is ``True``, this is a view to self. Examples -------- >>> A = np.array([1, 256, 8755], dtype=np.int16) >>> map(hex, A) ['0x1', '0x100', '0x2233'] >>> A.byteswap(True) array([ 256, 1, 13090], dtype=int16) >>> map(hex, A) ['0x100', '0x1', '0x3322'] Arrays of strings are not swapped >>> A = np.array(['ceg', 'fac']) >>> A.byteswap() array(['ceg', 'fac'], dtype='|S3') """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('choose', """ a.choose(choices, out=None, mode='raise') Use an index array to construct a new array from a set of choices. Refer to `numpy.choose` for full documentation. See Also -------- numpy.choose : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('clip', """ a.clip(min=None, max=None, out=None) Return an array whose values are limited to ``[min, max]``. One of max or min must be given. Refer to `numpy.clip` for full documentation. See Also -------- numpy.clip : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('compress', """ a.compress(condition, axis=None, out=None) Return selected slices of this array along given axis. Refer to `numpy.compress` for full documentation. See Also -------- numpy.compress : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('conj', """ a.conj() Complex-conjugate all elements. Refer to `numpy.conjugate` for full documentation. See Also -------- numpy.conjugate : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('conjugate', """ a.conjugate() Return the complex conjugate, element-wise. Refer to `numpy.conjugate` for full documentation. See Also -------- numpy.conjugate : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('copy', """ a.copy(order='C') Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :func:numpy.copy are very similar, but have different default values for their order= arguments.) See also -------- numpy.copy numpy.copyto Examples -------- >>> x = np.array([[1,2,3],[4,5,6]], order='F') >>> y = x.copy() >>> x.fill(0) >>> x array([[0, 0, 0], [0, 0, 0]]) >>> y array([[1, 2, 3], [4, 5, 6]]) >>> y.flags['C_CONTIGUOUS'] True """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('cumprod', """ a.cumprod(axis=None, dtype=None, out=None) Return the cumulative product of the elements along the given axis. Refer to `numpy.cumprod` for full documentation. See Also -------- numpy.cumprod : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('cumsum', """ a.cumsum(axis=None, dtype=None, out=None) Return the cumulative sum of the elements along the given axis. Refer to `numpy.cumsum` for full documentation. See Also -------- numpy.cumsum : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('diagonal', """ a.diagonal(offset=0, axis1=0, axis2=1) Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed. Refer to :func:`numpy.diagonal` for full documentation. See Also -------- numpy.diagonal : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('dot', """ a.dot(b, out=None) Dot product of two arrays. Refer to `numpy.dot` for full documentation. See Also -------- numpy.dot : equivalent function Examples -------- >>> a = np.eye(2) >>> b = np.ones((2, 2)) * 2 >>> a.dot(b) array([[ 2., 2.], [ 2., 2.]]) This array method can be conveniently chained: >>> a.dot(b).dot(b) array([[ 8., 8.], [ 8., 8.]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('dump', """a.dump(file) Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load. Parameters ---------- file : str A string naming the dump file. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('dumps', """ a.dumps() Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an array. Parameters ---------- None """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('fill', """ a.fill(value) Fill the array with a scalar value. Parameters ---------- value : scalar All elements of `a` will be assigned this value. Examples -------- >>> a = np.array([1, 2]) >>> a.fill(0) >>> a array([0, 0]) >>> a = np.empty(2) >>> a.fill(1) >>> a array([ 1., 1.]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('flatten', """ a.flatten(order='C') Return a copy of the array collapsed into one dimension. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional 'C' means to flatten in row-major (C-style) order. 'F' means to flatten in column-major (Fortran- style) order. 'A' means to flatten in column-major order if `a` is Fortran *contiguous* in memory, row-major order otherwise. 'K' means to flatten `a` in the order the elements occur in memory. The default is 'C'. Returns ------- y : ndarray A copy of the input array, flattened to one dimension. See Also -------- ravel : Return a flattened array. flat : A 1-D flat iterator over the array. Examples -------- >>> a = np.array([[1,2], [3,4]]) >>> a.flatten() array([1, 2, 3, 4]) >>> a.flatten('F') array([1, 3, 2, 4]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('getfield', """ a.getfield(dtype, offset=0) Returns a field of the given array as a certain type. A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes. Parameters ---------- dtype : str or dtype The data type of the view. The dtype size of the view can not be larger than that of the array itself. offset : int Number of bytes to skip before beginning the element view. Examples -------- >>> x = np.diag([1.+1.j]*2) >>> x[1, 1] = 2 + 4.j >>> x array([[ 1.+1.j, 0.+0.j], [ 0.+0.j, 2.+4.j]]) >>> x.getfield(np.float64) array([[ 1., 0.], [ 0., 2.]]) By choosing an offset of 8 bytes we can select the complex part of the array for our view: >>> x.getfield(np.float64, offset=8) array([[ 1., 0.], [ 0., 4.]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('item', """ a.item(*args) Copy an element of an array to a standard Python scalar and return it. Parameters ---------- \\*args : Arguments (variable number and type) * none: in this case, the method only works for arrays with one element (`a.size == 1`), which element is copied into a standard Python scalar object and returned. * int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return. * tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array. Returns ------- z : Standard Python scalar object A copy of the specified element of the array as a suitable Python scalar Notes ----- When the data type of `a` is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned. `item` is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python's optimized math. Examples -------- >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[3, 1, 7], [2, 8, 3], [8, 5, 3]]) >>> x.item(3) 2 >>> x.item(7) 5 >>> x.item((0, 1)) 1 >>> x.item((2, 2)) 3 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('itemset', """ a.itemset(*args) Insert scalar into an array (scalar is cast to array's dtype, if possible) There must be at least 1 argument, and define the last argument as *item*. Then, ``a.itemset(*args)`` is equivalent to but faster than ``a[args] = item``. The item should be a scalar value and `args` must select a single item in the array `a`. Parameters ---------- \\*args : Arguments If one argument: a scalar, only used in case `a` is of size 1. If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple. Notes ----- Compared to indexing syntax, `itemset` provides some speed increase for placing a scalar into a particular location in an `ndarray`, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when using `itemset` (and `item`) inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration. Examples -------- >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[3, 1, 7], [2, 8, 3], [8, 5, 3]]) >>> x.itemset(4, 0) >>> x.itemset((2, 2), 9) >>> x array([[3, 1, 7], [2, 0, 3], [8, 5, 9]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('max', """ a.max(axis=None, out=None) Return the maximum along a given axis. Refer to `numpy.amax` for full documentation. See Also -------- numpy.amax : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('mean', """ a.mean(axis=None, dtype=None, out=None, keepdims=False) Returns the average of the array elements along given axis. Refer to `numpy.mean` for full documentation. See Also -------- numpy.mean : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('min', """ a.min(axis=None, out=None, keepdims=False) Return the minimum along a given axis. Refer to `numpy.amin` for full documentation. See Also -------- numpy.amin : equivalent function """)) add_newdoc('numpy.core.multiarray', 'shares_memory', """ shares_memory(a, b, max_work=None) Determine if two arrays share memory Parameters ---------- a, b : ndarray Input arrays max_work : int, optional Effort to spend on solving the overlap problem (maximum number of candidate solutions to consider). The following special values are recognized: max_work=MAY_SHARE_EXACT (default) The problem is solved exactly. In this case, the function returns True only if there is an element shared between the arrays. max_work=MAY_SHARE_BOUNDS Only the memory bounds of a and b are checked. Raises ------ numpy.TooHardError Exceeded max_work. Returns ------- out : bool See Also -------- may_share_memory Examples -------- >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9])) False """) add_newdoc('numpy.core.multiarray', 'may_share_memory', """ may_share_memory(a, b, max_work=None) Determine if two arrays might share memory A return of True does not necessarily mean that the two arrays share any element. It just means that they *might*. Only the memory bounds of a and b are checked by default. Parameters ---------- a, b : ndarray Input arrays max_work : int, optional Effort to spend on solving the overlap problem. See `shares_memory` for details. Default for ``may_share_memory`` is to do a bounds check. Returns ------- out : bool See Also -------- shares_memory Examples -------- >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9])) False >>> x = np.zeros([3, 4]) >>> np.may_share_memory(x[:,0], x[:,1]) True """) add_newdoc('numpy.core.multiarray', 'ndarray', ('newbyteorder', """ arr.newbyteorder(new_order='S') Return the array with the same data viewed with a different byte order. Equivalent to:: arr.view(arr.dtype.newbytorder(new_order)) Changes are also made in all fields and sub-arrays of the array data type. Parameters ---------- new_order : string, optional Byte order to force; a value from the byte order specifications below. `new_order` codes can be any of: * 'S' - swap dtype from current to opposite endian * {'<', 'L'} - little endian * {'>', 'B'} - big endian * {'=', 'N'} - native order * {'|', 'I'} - ignore (no change to byte order) The default value ('S') results in swapping the current byte order. The code does a case-insensitive check on the first letter of `new_order` for the alternatives above. For example, any of 'B' or 'b' or 'biggish' are valid to specify big-endian. Returns ------- new_arr : array New array object with the dtype reflecting given change to the byte order. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('nonzero', """ a.nonzero() Return the indices of the elements that are non-zero. Refer to `numpy.nonzero` for full documentation. See Also -------- numpy.nonzero : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('prod', """ a.prod(axis=None, dtype=None, out=None, keepdims=False) Return the product of the array elements over the given axis Refer to `numpy.prod` for full documentation. See Also -------- numpy.prod : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('ptp', """ a.ptp(axis=None, out=None) Peak to peak (maximum - minimum) value along a given axis. Refer to `numpy.ptp` for full documentation. See Also -------- numpy.ptp : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('put', """ a.put(indices, values, mode='raise') Set ``a.flat[n] = values[n]`` for all `n` in indices. Refer to `numpy.put` for full documentation. See Also -------- numpy.put : equivalent function """)) add_newdoc('numpy.core.multiarray', 'copyto', """ copyto(dst, src, casting='same_kind', where=None) Copies values from one array to another, broadcasting as necessary. Raises a TypeError if the `casting` rule is violated, and if `where` is provided, it selects which elements to copy. .. versionadded:: 1.7.0 Parameters ---------- dst : ndarray The array into which values are copied. src : array_like The array from which values are copied. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur when copying. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. where : array_like of bool, optional A boolean array which is broadcasted to match the dimensions of `dst`, and selects elements to copy from `src` to `dst` wherever it contains the value True. """) add_newdoc('numpy.core.multiarray', 'putmask', """ putmask(a, mask, values) Changes elements of an array based on conditional and input values. Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``. If `values` is not the same size as `a` and `mask` then it will repeat. This gives behavior different from ``a[mask] = values``. Parameters ---------- a : array_like Target array. mask : array_like Boolean mask array. It has to be the same shape as `a`. values : array_like Values to put into `a` where `mask` is True. If `values` is smaller than `a` it will be repeated. See Also -------- place, put, take, copyto Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> np.putmask(x, x>2, x**2) >>> x array([[ 0, 1, 2], [ 9, 16, 25]]) If `values` is smaller than `a` it is repeated: >>> x = np.arange(5) >>> np.putmask(x, x>1, [-33, -44]) >>> x array([ 0, 1, -33, -44, -33]) """) add_newdoc('numpy.core.multiarray', 'ndarray', ('ravel', """ a.ravel([order]) Return a flattened array. Refer to `numpy.ravel` for full documentation. See Also -------- numpy.ravel : equivalent function ndarray.flat : a flat iterator on the array. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('repeat', """ a.repeat(repeats, axis=None) Repeat elements of an array. Refer to `numpy.repeat` for full documentation. See Also -------- numpy.repeat : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('reshape', """ a.reshape(shape, order='C') Returns an array containing the same data with a new shape. Refer to `numpy.reshape` for full documentation. See Also -------- numpy.reshape : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('resize', """ a.resize(new_shape, refcheck=True) Change shape and size of array in-place. Parameters ---------- new_shape : tuple of ints, or `n` ints Shape of resized array. refcheck : bool, optional If False, reference count will not be checked. Default is True. Returns ------- None Raises ------ ValueError If `a` does not own its own data or references or views to it exist, and the data memory must be changed. PyPy only: will always raise if the data memory must be changed, since there is no reliable way to determine if references or views to it exist. SystemError If the `order` keyword argument is specified. This behaviour is a bug in NumPy. See Also -------- resize : Return a new array with the specified shape. Notes ----- This reallocates space for the data area if necessary. Only contiguous arrays (data elements consecutive in memory) can be resized. The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set `refcheck` to False. Examples -------- Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped: >>> a = np.array([[0, 1], [2, 3]], order='C') >>> a.resize((2, 1)) >>> a array([[0], [1]]) >>> a = np.array([[0, 1], [2, 3]], order='F') >>> a.resize((2, 1)) >>> a array([[0], [2]]) Enlarging an array: as above, but missing entries are filled with zeros: >>> b = np.array([[0, 1], [2, 3]]) >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple >>> b array([[0, 1, 2], [3, 0, 0]]) Referencing an array prevents resizing... >>> c = a >>> a.resize((1, 1)) Traceback (most recent call last): ... ValueError: cannot resize an array that has been referenced ... Unless `refcheck` is False: >>> a.resize((1, 1), refcheck=False) >>> a array([[0]]) >>> c array([[0]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('round', """ a.round(decimals=0, out=None) Return `a` with each element rounded to the given number of decimals. Refer to `numpy.around` for full documentation. See Also -------- numpy.around : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted', """ a.searchsorted(v, side='left', sorter=None) Find indices where elements of v should be inserted in a to maintain order. For full documentation, see `numpy.searchsorted` See Also -------- numpy.searchsorted : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('setfield', """ a.setfield(val, dtype, offset=0) Put a value into a specified place in a field defined by a data-type. Place `val` into `a`'s field defined by `dtype` and beginning `offset` bytes into the field. Parameters ---------- val : object Value to be placed in field. dtype : dtype object Data-type of the field in which to place `val`. offset : int, optional The number of bytes into the field at which to place `val`. Returns ------- None See Also -------- getfield Examples -------- >>> x = np.eye(3) >>> x.getfield(np.float64) array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> x.setfield(3, np.int32) >>> x.getfield(np.int32) array([[3, 3, 3], [3, 3, 3], [3, 3, 3]]) >>> x array([[ 1.00000000e+000, 1.48219694e-323, 1.48219694e-323], [ 1.48219694e-323, 1.00000000e+000, 1.48219694e-323], [ 1.48219694e-323, 1.48219694e-323, 1.00000000e+000]]) >>> x.setfield(np.eye(3), np.int32) >>> x array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags', """ a.setflags(write=None, align=None, uic=None) Set array flags WRITEABLE, ALIGNED, and UPDATEIFCOPY, respectively. These Boolean-valued flags affect how numpy interprets the memory area used by `a` (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The UPDATEIFCOPY flag can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.) Parameters ---------- write : bool, optional Describes whether or not `a` can be written to. align : bool, optional Describes whether or not `a` is aligned properly for its type. uic : bool, optional Describes whether or not `a` is a copy of another "base" array. Notes ----- Array flags provide information about how the memory area used for the array is to be interpreted. There are 6 Boolean flags in use, only three of which can be changed by the user: UPDATEIFCOPY, WRITEABLE, and ALIGNED. WRITEABLE (W) the data area can be written to; ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler); UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .base). When this array is deallocated, the base array will be updated with the contents of this array. All flags can be accessed using their first (upper case) letter as well as the full name. Examples -------- >>> y array([[3, 1, 7], [2, 0, 0], [8, 5, 9]]) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False >>> y.setflags(write=0, align=0) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : False ALIGNED : False UPDATEIFCOPY : False >>> y.setflags(uic=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot set UPDATEIFCOPY flag to True """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('sort', """ a.sort(axis=-1, kind='quicksort', order=None) Sort an array, in-place. Parameters ---------- axis : int, optional Axis along which to sort. Default is -1, which means sort along the last axis. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. Default is 'quicksort'. order : str or list of str, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. See Also -------- numpy.sort : Return a sorted copy of an array. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in sorted array. partition: Partial sort. Notes ----- See ``sort`` for notes on the different sorting algorithms. Examples -------- >>> a = np.array([[1,4], [3,1]]) >>> a.sort(axis=1) >>> a array([[1, 4], [1, 3]]) >>> a.sort(axis=0) >>> a array([[1, 3], [1, 4]]) Use the `order` keyword to specify a field to use when sorting a structured array: >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)]) >>> a.sort(order='y') >>> a array([('c', 1), ('a', 2)], dtype=[('x', '|S1'), ('y', '<i4')]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('partition', """ a.partition(kth, axis=-1, kind='introselect', order=None) Rearranges the elements in the array in such a way that value of the element in kth position is in the position it would be in a sorted array. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined. .. versionadded:: 1.8.0 Parameters ---------- kth : int or sequence of ints Element index to partition by. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order all elements in the partitions is undefined. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once. axis : int, optional Axis along which to sort. Default is -1, which means sort along the last axis. kind : {'introselect'}, optional Selection algorithm. Default is 'introselect'. order : str or list of str, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. See Also -------- numpy.partition : Return a parititioned copy of an array. argpartition : Indirect partition. sort : Full sort. Notes ----- See ``np.partition`` for notes on the different algorithms. Examples -------- >>> a = np.array([3, 4, 2, 1]) >>> a.partition(3) >>> a array([2, 1, 3, 4]) >>> a.partition((1, 3)) array([1, 2, 3, 4]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('squeeze', """ a.squeeze(axis=None) Remove single-dimensional entries from the shape of `a`. Refer to `numpy.squeeze` for full documentation. See Also -------- numpy.squeeze : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('std', """ a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False) Returns the standard deviation of the array elements along given axis. Refer to `numpy.std` for full documentation. See Also -------- numpy.std : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('sum', """ a.sum(axis=None, dtype=None, out=None, keepdims=False) Return the sum of the array elements over the given axis. Refer to `numpy.sum` for full documentation. See Also -------- numpy.sum : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('swapaxes', """ a.swapaxes(axis1, axis2) Return a view of the array with `axis1` and `axis2` interchanged. Refer to `numpy.swapaxes` for full documentation. See Also -------- numpy.swapaxes : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('take', """ a.take(indices, axis=None, out=None, mode='raise') Return an array formed from the elements of `a` at the given indices. Refer to `numpy.take` for full documentation. See Also -------- numpy.take : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile', """ a.tofile(fid, sep="", format="%s") Write array to a file as text or binary (default). Data is always written in 'C' order, independent of the order of `a`. The data produced by this method can be recovered using the function fromfile(). Parameters ---------- fid : file or str An open file object, or a string containing a filename. sep : str Separator between array items for text output. If "" (empty), a binary file is written, equivalent to ``file.write(a.tobytes())``. format : str Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using "format" % item. Notes ----- This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist', """ a.tolist() Return the array as a (possibly nested) list. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible Python type. Parameters ---------- none Returns ------- y : list The possibly nested list of array elements. Notes ----- The array may be recreated, ``a = np.array(a.tolist())``. Examples -------- >>> a = np.array([1, 2]) >>> a.tolist() [1, 2] >>> a = np.array([[1, 2], [3, 4]]) >>> list(a) [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]] """)) tobytesdoc = """ a.{name}(order='C') Construct Python bytes containing the raw data bytes in the array. Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object can be produced in either 'C' or 'Fortran', or 'Any' order (the default is 'C'-order). 'Any' order means C-order unless the F_CONTIGUOUS flag in the array is set, in which case it means 'Fortran' order. {deprecated} Parameters ---------- order : {{'C', 'F', None}}, optional Order of the data for multidimensional arrays: C, Fortran, or the same as for the original array. Returns ------- s : bytes Python bytes exhibiting a copy of `a`'s raw data. Examples -------- >>> x = np.array([[0, 1], [2, 3]]) >>> x.tobytes() b'\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00' >>> x.tobytes('C') == x.tobytes() True >>> x.tobytes('F') b'\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x03\\x00\\x00\\x00' """ add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', tobytesdoc.format(name='tostring', deprecated= 'This function is a compatibility ' 'alias for tobytes. Despite its ' 'name it returns bytes not ' 'strings.'))) add_newdoc('numpy.core.multiarray', 'ndarray', ('tobytes', tobytesdoc.format(name='tobytes', deprecated='.. versionadded:: 1.9.0'))) add_newdoc('numpy.core.multiarray', 'ndarray', ('trace', """ a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) Return the sum along diagonals of the array. Refer to `numpy.trace` for full documentation. See Also -------- numpy.trace : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('transpose', """ a.transpose(*axes) Returns a view of the array with axes transposed. For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a matrix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and ``a.shape = (i[0], i[1], ... i[n-2], i[n-1])``, then ``a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0])``. Parameters ---------- axes : None, tuple of ints, or `n` ints * None or no argument: reverses the order of the axes. * tuple of ints: `i` in the `j`-th place in the tuple means `a`'s `i`-th axis becomes `a.transpose()`'s `j`-th axis. * `n` ints: same as an n-tuple of the same ints (this form is intended simply as a "convenience" alternative to the tuple form) Returns ------- out : ndarray View of `a`, with axes suitably permuted. See Also -------- ndarray.T : Array property returning the array transposed. Examples -------- >>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.transpose() array([[1, 3], [2, 4]]) >>> a.transpose((1, 0)) array([[1, 3], [2, 4]]) >>> a.transpose(1, 0) array([[1, 3], [2, 4]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('var', """ a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False) Returns the variance of the array elements, along given axis. Refer to `numpy.var` for full documentation. See Also -------- numpy.var : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('view', """ a.view(dtype=None, type=None) New view of array with the same data. Parameters ---------- dtype : data-type or ndarray sub-class, optional Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as `a`. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the ``type`` parameter). type : Python type, optional Type of the returned view, e.g., ndarray or matrix. Again, the default None results in type preservation. Notes ----- ``a.view()`` is used two different ways: ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view of the array's memory with a different data-type. This can cause a reinterpretation of the bytes of memory. ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just returns an instance of `ndarray_subclass` that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of ``a`` (shown by ``print(a)``). It also depends on exactly how ``a`` is stored in memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. Examples -------- >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) Viewing array data using a different type and dtype: >>> y = x.view(dtype=np.int16, type=np.matrix) >>> y matrix([[513]], dtype=int16) >>> print(type(y)) <class 'numpy.matrixlib.defmatrix.matrix'> Creating a view on a structured array so it can be used in calculations >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) >>> xv = x.view(dtype=np.int8).reshape(-1,2) >>> xv array([[1, 2], [3, 4]], dtype=int8) >>> xv.mean(0) array([ 2., 3.]) Making changes to the view changes the underlying array >>> xv[0,1] = 20 >>> print(x) [(1, 20) (3, 4)] Using a view to convert an array to a recarray: >>> z = x.view(np.recarray) >>> z.a array([1], dtype=int8) Views share data: >>> x[0] = (9, 10) >>> z[0] (9, 10) Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.: >>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16) >>> y = x[:, 0:2] >>> y array([[1, 2], [4, 5]], dtype=int16) >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: new type not compatible with array. >>> z = y.copy() >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) array([[(1, 2)], [(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')]) """)) ############################################################################## # # umath functions # ############################################################################## add_newdoc('numpy.core.umath', 'frompyfunc', """ frompyfunc(func, nin, nout) Takes an arbitrary Python function and returns a NumPy ufunc. Can be used, for example, to add broadcasting to a built-in Python function (see Examples section). Parameters ---------- func : Python function object An arbitrary Python function. nin : int The number of input arguments. nout : int The number of objects returned by `func`. Returns ------- out : ufunc Returns a NumPy universal function (``ufunc``) object. See Also -------- vectorize : evaluates pyfunc over input arrays using broadcasting rules of numpy Notes ----- The returned ufunc always returns PyObject arrays. Examples -------- Use frompyfunc to add broadcasting to the Python function ``oct``: >>> oct_array = np.frompyfunc(oct, 1, 1) >>> oct_array(np.array((10, 30, 100))) array([012, 036, 0144], dtype=object) >>> np.array((oct(10), oct(30), oct(100))) # for comparison array(['012', '036', '0144'], dtype='|S4') """) add_newdoc('numpy.core.umath', 'geterrobj', """ geterrobj() Return the current object that defines floating-point error handling. The error object contains all information that defines the error handling behavior in NumPy. `geterrobj` is used internally by the other functions that get and set error handling behavior (`geterr`, `seterr`, `geterrcall`, `seterrcall`). Returns ------- errobj : list The error object, a list containing three elements: [internal numpy buffer size, error mask, error callback function]. The error mask is a single integer that holds the treatment information on all four floating point errors. The information for each error type is contained in three bits of the integer. If we print it in base 8, we can see what treatment is set for "invalid", "under", "over", and "divide" (in that order). The printed string can be interpreted with * 0 : 'ignore' * 1 : 'warn' * 2 : 'raise' * 3 : 'call' * 4 : 'print' * 5 : 'log' See Also -------- seterrobj, seterr, geterr, seterrcall, geterrcall getbufsize, setbufsize Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- >>> np.geterrobj() # first get the defaults [10000, 0, None] >>> def err_handler(type, flag): ... print("Floating point error (%s), with flag %s" % (type, flag)) ... >>> old_bufsize = np.setbufsize(20000) >>> old_err = np.seterr(divide='raise') >>> old_handler = np.seterrcall(err_handler) >>> np.geterrobj() [20000, 2, <function err_handler at 0x91dcaac>] >>> old_err = np.seterr(all='ignore') >>> np.base_repr(np.geterrobj()[1], 8) '0' >>> old_err = np.seterr(divide='warn', over='log', under='call', invalid='print') >>> np.base_repr(np.geterrobj()[1], 8) '4351' """) add_newdoc('numpy.core.umath', 'seterrobj', """ seterrobj(errobj) Set the object that defines floating-point error handling. The error object contains all information that defines the error handling behavior in NumPy. `seterrobj` is used internally by the other functions that set error handling behavior (`seterr`, `seterrcall`). Parameters ---------- errobj : list The error object, a list containing three elements: [internal numpy buffer size, error mask, error callback function]. The error mask is a single integer that holds the treatment information on all four floating point errors. The information for each error type is contained in three bits of the integer. If we print it in base 8, we can see what treatment is set for "invalid", "under", "over", and "divide" (in that order). The printed string can be interpreted with * 0 : 'ignore' * 1 : 'warn' * 2 : 'raise' * 3 : 'call' * 4 : 'print' * 5 : 'log' See Also -------- geterrobj, seterr, geterr, seterrcall, geterrcall getbufsize, setbufsize Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- >>> old_errobj = np.geterrobj() # first get the defaults >>> old_errobj [10000, 0, None] >>> def err_handler(type, flag): ... print("Floating point error (%s), with flag %s" % (type, flag)) ... >>> new_errobj = [20000, 12, err_handler] >>> np.seterrobj(new_errobj) >>> np.base_repr(12, 8) # int for divide=4 ('print') and over=1 ('warn') '14' >>> np.geterr() {'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'} >>> np.geterrcall() is err_handler True """) ############################################################################## # # compiled_base functions # ############################################################################## add_newdoc('numpy.core.multiarray', 'digitize', """ digitize(x, bins, right=False) Return the indices of the bins to which each value in input array belongs. Each index ``i`` returned is such that ``bins[i-1] <= x < bins[i]`` if `bins` is monotonically increasing, or ``bins[i-1] > x >= bins[i]`` if `bins` is monotonically decreasing. If values in `x` are beyond the bounds of `bins`, 0 or ``len(bins)`` is returned as appropriate. If right is True, then the right bin is closed so that the index ``i`` is such that ``bins[i-1] < x <= bins[i]`` or ``bins[i-1] >= x > bins[i]`` if `bins` is monotonically increasing or decreasing, respectively. Parameters ---------- x : array_like Input array to be binned. Prior to NumPy 1.10.0, this array had to be 1-dimensional, but can now have any shape. bins : array_like Array of bins. It has to be 1-dimensional and monotonic. right : bool, optional Indicating whether the intervals include the right or the left bin edge. Default behavior is (right==False) indicating that the interval does not include the right edge. The left bin end is open in this case, i.e., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins. Returns ------- out : ndarray of ints Output array of indices, of same shape as `x`. Raises ------ ValueError If `bins` is not monotonic. TypeError If the type of the input is complex. See Also -------- bincount, histogram, unique, searchsorted Notes ----- If values in `x` are such that they fall outside the bin range, attempting to index `bins` with the indices that `digitize` returns will result in an IndexError. .. versionadded:: 1.10.0 `np.digitize` is implemented in terms of `np.searchsorted`. This means that a binary search is used to bin the values, which scales much better for larger number of bins than the previous linear search. It also removes the requirement for the input array to be 1-dimensional. Examples -------- >>> x = np.array([0.2, 6.4, 3.0, 1.6]) >>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0]) >>> inds = np.digitize(x, bins) >>> inds array([1, 4, 3, 2]) >>> for n in range(x.size): ... print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]]) ... 0.0 <= 0.2 < 1.0 4.0 <= 6.4 < 10.0 2.5 <= 3.0 < 4.0 1.0 <= 1.6 < 2.5 >>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.]) >>> bins = np.array([0, 5, 10, 15, 20]) >>> np.digitize(x,bins,right=True) array([1, 2, 3, 4, 4]) >>> np.digitize(x,bins,right=False) array([1, 3, 3, 4, 5]) """) add_newdoc('numpy.core.multiarray', 'bincount', """ bincount(x, weights=None, minlength=0) Count number of occurrences of each value in array of non-negative ints. The number of bins (of size 1) is one larger than the largest value in `x`. If `minlength` is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents of `x`). Each bin gives the number of occurrences of its index value in `x`. If `weights` is specified the input array is weighted by it, i.e. if a value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead of ``out[n] += 1``. Parameters ---------- x : array_like, 1 dimension, nonnegative ints Input array. weights : array_like, optional Weights, array of the same shape as `x`. minlength : int, optional A minimum number of bins for the output array. .. versionadded:: 1.6.0 Returns ------- out : ndarray of ints The result of binning the input array. The length of `out` is equal to ``np.amax(x)+1``. Raises ------ ValueError If the input is not 1-dimensional, or contains elements with negative values, or if `minlength` is negative. TypeError If the type of the input is float or complex. See Also -------- histogram, digitize, unique Examples -------- >>> np.bincount(np.arange(5)) array([1, 1, 1, 1, 1]) >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) array([1, 3, 1, 1, 0, 0, 0, 1]) >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23]) >>> np.bincount(x).size == np.amax(x)+1 True The input array needs to be of integer dtype, otherwise a TypeError is raised: >>> np.bincount(np.arange(5, dtype=np.float)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: array cannot be safely cast to required type A possible use of ``bincount`` is to perform sums over variable-size chunks of an array, using the ``weights`` keyword. >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights >>> x = np.array([0, 1, 1, 2, 2, 2]) >>> np.bincount(x, weights=w) array([ 0.3, 0.7, 1.1]) """) add_newdoc('numpy.core.multiarray', 'ravel_multi_index', """ ravel_multi_index(multi_index, dims, mode='raise', order='C') Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index. Parameters ---------- multi_index : tuple of array_like A tuple of integer arrays, one array for each dimension. dims : tuple of ints The shape of array into which the indices from ``multi_index`` apply. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index. * 'raise' -- raise an error (default) * 'wrap' -- wrap around * 'clip' -- clip to the range In 'clip' mode, a negative index which would normally wrap will clip to 0 instead. order : {'C', 'F'}, optional Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order. Returns ------- raveled_indices : ndarray An array of indices into the flattened version of an array of dimensions ``dims``. See Also -------- unravel_index Notes ----- .. versionadded:: 1.6.0 Examples -------- >>> arr = np.array([[3,6,6],[4,5,1]]) >>> np.ravel_multi_index(arr, (7,6)) array([22, 41, 37]) >>> np.ravel_multi_index(arr, (7,6), order='F') array([31, 41, 13]) >>> np.ravel_multi_index(arr, (4,6), mode='clip') array([22, 23, 19]) >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap')) array([12, 13, 13]) >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9)) 1621 """) add_newdoc('numpy.core.multiarray', 'unravel_index', """ unravel_index(indices, dims, order='C') Converts a flat index or array of flat indices into a tuple of coordinate arrays. Parameters ---------- indices : array_like An integer array whose elements are indices into the flattened version of an array of dimensions ``dims``. Before version 1.6.0, this function accepted just one index value. dims : tuple of ints The shape of the array to use for unraveling ``indices``. order : {'C', 'F'}, optional Determines whether the indices should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order. .. versionadded:: 1.6.0 Returns ------- unraveled_coords : tuple of ndarray Each array in the tuple has the same shape as the ``indices`` array. See Also -------- ravel_multi_index Examples -------- >>> np.unravel_index([22, 41, 37], (7,6)) (array([3, 6, 6]), array([4, 5, 1])) >>> np.unravel_index([31, 41, 13], (7,6), order='F') (array([3, 6, 6]), array([4, 5, 1])) >>> np.unravel_index(1621, (6,7,8,9)) (3, 1, 4, 1) """) add_newdoc('numpy.core.multiarray', 'add_docstring', """ add_docstring(obj, docstring) Add a docstring to a built-in obj if possible. If the obj already has a docstring raise a RuntimeError If this routine does not know how to add a docstring to the object raise a TypeError """) add_newdoc('numpy.core.umath', '_add_newdoc_ufunc', """ add_ufunc_docstring(ufunc, new_docstring) Replace the docstring for a ufunc with new_docstring. This method will only work if the current docstring for the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.) Parameters ---------- ufunc : numpy.ufunc A ufunc whose current doc is NULL. new_docstring : string The new docstring for the ufunc. Notes ----- This method allocates memory for new_docstring on the heap. Technically this creates a mempory leak, since this memory will not be reclaimed until the end of the program even if the ufunc itself is removed. However this will only be a problem if the user is repeatedly creating ufuncs with no documentation, adding documentation via add_newdoc_ufunc, and then throwing away the ufunc. """) add_newdoc('numpy.core.multiarray', 'packbits', """ packbits(myarray, axis=None) Packs the elements of a binary-valued array into bits in a uint8 array. The result is padded to full bytes by inserting zero bits at the end. Parameters ---------- myarray : array_like An array of integers or booleans whose elements should be packed to bits. axis : int, optional The dimension over which bit-packing is done. ``None`` implies packing the flattened array. Returns ------- packed : ndarray Array of type uint8 whose elements represent bits corresponding to the logical (0 or nonzero) value of the input elements. The shape of `packed` has the same number of dimensions as the input (unless `axis` is None, in which case the output is 1-D). See Also -------- unpackbits: Unpacks elements of a uint8 array into a binary-valued output array. Examples -------- >>> a = np.array([[[1,0,1], ... [0,1,0]], ... [[1,1,0], ... [0,0,1]]]) >>> b = np.packbits(a, axis=-1) >>> b array([[[160],[64]],[[192],[32]]], dtype=uint8) Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000, and 32 = 0010 0000. """) add_newdoc('numpy.core.multiarray', 'unpackbits', """ unpackbits(myarray, axis=None) Unpacks elements of a uint8 array into a binary-valued output array. Each element of `myarray` represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if `axis` is None) or the same shape as the input array with unpacking done along the axis specified. Parameters ---------- myarray : ndarray, uint8 type Input array. axis : int, optional Unpacks along this axis. Returns ------- unpacked : ndarray, uint8 type The elements are binary-valued (0 or 1). See Also -------- packbits : Packs the elements of a binary-valued array into bits in a uint8 array. Examples -------- >>> a = np.array([[2], [7], [23]], dtype=np.uint8) >>> a array([[ 2], [ 7], [23]], dtype=uint8) >>> b = np.unpackbits(a, axis=1) >>> b array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8) """) ############################################################################## # # Documentation for ufunc attributes and methods # ############################################################################## ############################################################################## # # ufunc object # ############################################################################## add_newdoc('numpy.core', 'ufunc', """ Functions that operate element by element on whole arrays. To see the documentation for a specific ufunc, use `info`. For example, ``np.info(np.sin)``. Because ufuncs are written in C (for speed) and linked into Python with NumPy's ufunc facility, Python's help() function finds this page whenever help() is called on a ufunc. A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`. Calling ufuncs: =============== op(*x[, out], where=True, **kwargs) Apply `op` to the arguments `*x` elementwise, broadcasting the arguments. The broadcasting rules are: * Dimensions of length 1 may be prepended to either array. * Arrays may be repeated along dimensions of length 1. Parameters ---------- *x : array_like Input arrays. out : ndarray, None, or tuple of ndarray and None, optional Alternate array object(s) in which to put the result; if provided, it must have a shape that the inputs broadcast to. A tuple of arrays (possible only as a keyword argument) must have length equal to the number of outputs; use `None` for outputs to be allocated by the ufunc. where : array_like, optional Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone. **kwargs For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`. Returns ------- r : ndarray or tuple of ndarray `r` will have the shape that the arrays in `x` broadcast to; if `out` is provided, `r` will be equal to `out`. If the function has more than one output, then the result will be a tuple of arrays. """) ############################################################################## # # ufunc attributes # ############################################################################## add_newdoc('numpy.core', 'ufunc', ('identity', """ The identity value. Data attribute containing the identity element for the ufunc, if it has one. If it does not, the attribute value is None. Examples -------- >>> np.add.identity 0 >>> np.multiply.identity 1 >>> np.power.identity 1 >>> print(np.exp.identity) None """)) add_newdoc('numpy.core', 'ufunc', ('nargs', """ The number of arguments. Data attribute containing the number of arguments the ufunc takes, including optional ones. Notes ----- Typically this value will be one more than what you might expect because all ufuncs take the optional "out" argument. Examples -------- >>> np.add.nargs 3 >>> np.multiply.nargs 3 >>> np.power.nargs 3 >>> np.exp.nargs 2 """)) add_newdoc('numpy.core', 'ufunc', ('nin', """ The number of inputs. Data attribute containing the number of arguments the ufunc treats as input. Examples -------- >>> np.add.nin 2 >>> np.multiply.nin 2 >>> np.power.nin 2 >>> np.exp.nin 1 """)) add_newdoc('numpy.core', 'ufunc', ('nout', """ The number of outputs. Data attribute containing the number of arguments the ufunc treats as output. Notes ----- Since all ufuncs can take output arguments, this will always be (at least) 1. Examples -------- >>> np.add.nout 1 >>> np.multiply.nout 1 >>> np.power.nout 1 >>> np.exp.nout 1 """)) add_newdoc('numpy.core', 'ufunc', ('ntypes', """ The number of types. The number of numerical NumPy types - of which there are 18 total - on which the ufunc can operate. See Also -------- numpy.ufunc.types Examples -------- >>> np.add.ntypes 18 >>> np.multiply.ntypes 18 >>> np.power.ntypes 17 >>> np.exp.ntypes 7 >>> np.remainder.ntypes 14 """)) add_newdoc('numpy.core', 'ufunc', ('types', """ Returns a list with types grouped input->output. Data attribute listing the data-type "Domain-Range" groupings the ufunc can deliver. The data-types are given using the character codes. See Also -------- numpy.ufunc.ntypes Examples -------- >>> np.add.types ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] >>> np.multiply.types ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] >>> np.power.types ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] >>> np.exp.types ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O'] >>> np.remainder.types ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O'] """)) ############################################################################## # # ufunc methods # ############################################################################## add_newdoc('numpy.core', 'ufunc', ('reduce', """ reduce(a, axis=0, dtype=None, out=None, keepdims=False) Reduces `a`'s dimension by one, by applying ufunc along one axis. Let :math:`a.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then :math:`ufunc.reduce(a, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` = the result of iterating `j` over :math:`range(N_i)`, cumulatively applying ufunc to each :math:`a[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`. For a one-dimensional array, reduce produces results equivalent to: :: r = op.identity # op = ufunc for i in range(len(A)): r = op(r, A[i]) return r For example, add.reduce() is equivalent to sum(). Parameters ---------- a : array_like The array to act on. axis : None or int or tuple of ints, optional Axis or axes along which a reduction is performed. The default (`axis` = 0) is perform a reduction over the first dimension of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.7.0 If this is `None`, a reduction is performed over all the axes. If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before. For operations which are either not commutative or not associative, doing a reduction over multiple axes is not well-defined. The ufuncs do not currently raise an exception in this case, but will likely do so in the future. dtype : data-type code, optional The type used to represent the intermediate results. Defaults to the data-type of the output array if this is provided, or the data-type of the input array if no output array is provided. out : ndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If not provided or `None`, a freshly-allocated array is returned. For consistency with :ref:`ufunc.__call__`, if given as a keyword, this may be wrapped in a 1-element tuple. .. versionchanged:: 1.13.0 Tuples are allowed for keyword argument. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. .. versionadded:: 1.7.0 Returns ------- r : ndarray The reduced array. If `out` was supplied, `r` is a reference to it. Examples -------- >>> np.multiply.reduce([2,3,5]) 30 A multi-dimensional array example: >>> X = np.arange(8).reshape((2,2,2)) >>> X array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> np.add.reduce(X, 0) array([[ 4, 6], [ 8, 10]]) >>> np.add.reduce(X) # confirm: default axis value is 0 array([[ 4, 6], [ 8, 10]]) >>> np.add.reduce(X, 1) array([[ 2, 4], [10, 12]]) >>> np.add.reduce(X, 2) array([[ 1, 5], [ 9, 13]]) """)) add_newdoc('numpy.core', 'ufunc', ('accumulate', """ accumulate(array, axis=0, dtype=None, out=None, keepdims=None) Accumulate the result of applying the operator to all elements. For a one-dimensional array, accumulate produces results equivalent to:: r = np.empty(len(A)) t = op.identity # op = the ufunc being applied to A's elements for i in range(len(A)): t = op(t, A[i]) r[i] = t return r For example, add.accumulate() is equivalent to np.cumsum(). For a multi-dimensional array, accumulate is applied along only one axis (axis zero by default; see Examples below) so repeated use is necessary if one wants to accumulate over multiple axes. Parameters ---------- array : array_like The array to act on. axis : int, optional The axis along which to apply the accumulation; default is zero. dtype : data-type code, optional The data-type used to represent the intermediate results. Defaults to the data-type of the output array if such is provided, or the the data-type of the input array if no output array is provided. out : ndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If not provided or `None`, a freshly-allocated array is returned. For consistency with :ref:`ufunc.__call__`, if given as a keyword, this may be wrapped in a 1-element tuple. .. versionchanged:: 1.13.0 Tuples are allowed for keyword argument. keepdims : bool Has no effect. Deprecated, and will be removed in future. Returns ------- r : ndarray The accumulated values. If `out` was supplied, `r` is a reference to `out`. Examples -------- 1-D array examples: >>> np.add.accumulate([2, 3, 5]) array([ 2, 5, 10]) >>> np.multiply.accumulate([2, 3, 5]) array([ 2, 6, 30]) 2-D array examples: >>> I = np.eye(2) >>> I array([[ 1., 0.], [ 0., 1.]]) Accumulate along axis 0 (rows), down columns: >>> np.add.accumulate(I, 0) array([[ 1., 0.], [ 1., 1.]]) >>> np.add.accumulate(I) # no axis specified = axis zero array([[ 1., 0.], [ 1., 1.]]) Accumulate along axis 1 (columns), through rows: >>> np.add.accumulate(I, 1) array([[ 1., 1.], [ 0., 1.]]) """)) add_newdoc('numpy.core', 'ufunc', ('reduceat', """ reduceat(a, indices, axis=0, dtype=None, out=None) Performs a (local) reduce with specified slices over a single axis. For i in ``range(len(indices))``, `reduceat` computes ``ufunc.reduce(a[indices[i]:indices[i+1]])``, which becomes the i-th generalized "row" parallel to `axis` in the final result (i.e., in a 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if `axis = 1`, it becomes the i-th column). There are three exceptions to this: * when ``i = len(indices) - 1`` (so for the last index), ``indices[i+1] = a.shape[axis]``. * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is simply ``a[indices[i]]``. * if ``indices[i] >= len(a)`` or ``indices[i] < 0``, an error is raised. The shape of the output depends on the size of `indices`, and may be larger than `a` (this happens if ``len(indices) > a.shape[axis]``). Parameters ---------- a : array_like The array to act on. indices : array_like Paired indices, comma separated (not colon), specifying slices to reduce. axis : int, optional The axis along which to apply the reduceat. dtype : data-type code, optional The type used to represent the intermediate results. Defaults to the data type of the output array if this is provided, or the data type of the input array if no output array is provided. out : ndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If not provided or `None`, a freshly-allocated array is returned. For consistency with :ref:`ufunc.__call__`, if given as a keyword, this may be wrapped in a 1-element tuple. .. versionchanged:: 1.13.0 Tuples are allowed for keyword argument. Returns ------- r : ndarray The reduced values. If `out` was supplied, `r` is a reference to `out`. Notes ----- A descriptive example: If `a` is 1-D, the function `ufunc.accumulate(a)` is the same as ``ufunc.reduceat(a, indices)[::2]`` where `indices` is ``range(len(array) - 1)`` with a zero placed in every other element: ``indices = zeros(2 * len(a) - 1)``, ``indices[1::2] = range(1, len(a))``. Don't be fooled by this attribute's name: `reduceat(a)` is not necessarily smaller than `a`. Examples -------- To take the running sum of four successive values: >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2] array([ 6, 10, 14, 18]) A 2-D example: >>> x = np.linspace(0, 15, 16).reshape(4,4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 12., 13., 14., 15.]]) :: # reduce such that the result has the following five rows: # [row1 + row2 + row3] # [row4] # [row2] # [row3] # [row1 + row2 + row3 + row4] >>> np.add.reduceat(x, [0, 3, 1, 2, 0]) array([[ 12., 15., 18., 21.], [ 12., 13., 14., 15.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 24., 28., 32., 36.]]) :: # reduce such that result has the following two columns: # [col1 * col2 * col3, col4] >>> np.multiply.reduceat(x, [0, 3], 1) array([[ 0., 3.], [ 120., 7.], [ 720., 11.], [ 2184., 15.]]) """)) add_newdoc('numpy.core', 'ufunc', ('outer', """ outer(A, B, **kwargs) Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`. Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of ``op.outer(A, B)`` is an array of dimension M + N such that: .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] = op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}]) For `A` and `B` one-dimensional, this is equivalent to:: r = empty(len(A),len(B)) for i in range(len(A)): for j in range(len(B)): r[i,j] = op(A[i], B[j]) # op = ufunc in question Parameters ---------- A : array_like First array B : array_like Second array kwargs : any Arguments to pass on to the ufunc. Typically `dtype` or `out`. Returns ------- r : ndarray Output array See Also -------- numpy.outer Examples -------- >>> np.multiply.outer([1, 2, 3], [4, 5, 6]) array([[ 4, 5, 6], [ 8, 10, 12], [12, 15, 18]]) A multi-dimensional example: >>> A = np.array([[1, 2, 3], [4, 5, 6]]) >>> A.shape (2, 3) >>> B = np.array([[1, 2, 3, 4]]) >>> B.shape (1, 4) >>> C = np.multiply.outer(A, B) >>> C.shape; C (2, 3, 1, 4) array([[[[ 1, 2, 3, 4]], [[ 2, 4, 6, 8]], [[ 3, 6, 9, 12]]], [[[ 4, 8, 12, 16]], [[ 5, 10, 15, 20]], [[ 6, 12, 18, 24]]]]) """)) add_newdoc('numpy.core', 'ufunc', ('at', """ at(a, indices, b=None) Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'. For addition ufunc, this method is equivalent to `a[indices] += b`, except that results are accumulated for elements that are indexed more than once. For example, `a[[0,0]] += 1` will only increment the first element once because of buffering, whereas `add.at(a, [0,0], 1)` will increment the first element twice. .. versionadded:: 1.8.0 Parameters ---------- a : array_like The array to perform in place operation on. indices : array_like or tuple Array like index object or slice object for indexing into first operand. If first operand has multiple dimensions, indices can be a tuple of array like index objects or slice objects. b : array_like Second operand for ufuncs requiring two operands. Operand must be broadcastable over first operand after indexing or slicing. Examples -------- Set items 0 and 1 to their negative values: >>> a = np.array([1, 2, 3, 4]) >>> np.negative.at(a, [0, 1]) >>> print(a) array([-1, -2, 3, 4]) :: Increment items 0 and 1, and increment item 2 twice: >>> a = np.array([1, 2, 3, 4]) >>> np.add.at(a, [0, 1, 2, 2], 1) >>> print(a) array([2, 3, 5, 4]) :: Add items 0 and 1 in first array to second array, and store results in first array: >>> a = np.array([1, 2, 3, 4]) >>> b = np.array([1, 2]) >>> np.add.at(a, [0, 1], b) >>> print(a) array([2, 4, 3, 4]) """)) ############################################################################## # # Documentation for dtype attributes and methods # ############################################################################## ############################################################################## # # dtype object # ############################################################################## add_newdoc('numpy.core.multiarray', 'dtype', """ dtype(obj, align=False, copy=False) Create a data type object. A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be constructed from different combinations of fundamental numeric types. Parameters ---------- obj Object to be converted to a data type object. align : bool, optional Add padding to the fields to match what a C compiler would output for a similar C-struct. Can be ``True`` only if `obj` is a dictionary or a comma-separated string. If a struct dtype is being created, this also sets a sticky alignment flag ``isalignedstruct``. copy : bool, optional Make a new copy of the data-type object. If ``False``, the result may just be a reference to a built-in data-type object. See also -------- result_type Examples -------- Using array-scalar type: >>> np.dtype(np.int16) dtype('int16') Structured type, one field name 'f1', containing int16: >>> np.dtype([('f1', np.int16)]) dtype([('f1', '<i2')]) Structured type, one field named 'f1', in itself containing a structured type with one field: >>> np.dtype([('f1', [('f1', np.int16)])]) dtype([('f1', [('f1', '<i2')])]) Structured type, two fields: the first field contains an unsigned int, the second an int32: >>> np.dtype([('f1', np.uint), ('f2', np.int32)]) dtype([('f1', '<u4'), ('f2', '<i4')]) Using array-protocol type strings: >>> np.dtype([('a','f8'),('b','S10')]) dtype([('a', '<f8'), ('b', '|S10')]) Using comma-separated field formats. The shape is (2,3): >>> np.dtype("i4, (2,3)f8") dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))]) Using tuples. ``int`` is a fixed type, 3 the field's shape. ``void`` is a flexible type, here of size 10: >>> np.dtype([('hello',(np.int,3)),('world',np.void,10)]) dtype([('hello', '<i4', 3), ('world', '|V10')]) Subdivide ``int16`` into 2 ``int8``'s, called x and y. 0 and 1 are the offsets in bytes: >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)})) dtype(('<i2', [('x', '|i1'), ('y', '|i1')])) Using dictionaries. Two fields named 'gender' and 'age': >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]}) dtype([('gender', '|S1'), ('age', '|u1')]) Offsets in bytes, here 0 and 25: >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)}) dtype([('surname', '|S25'), ('age', '|u1')]) """) ############################################################################## # # dtype attributes # ############################################################################## add_newdoc('numpy.core.multiarray', 'dtype', ('alignment', """ The required alignment (bytes) of this data-type according to the compiler. More information is available in the C-API section of the manual. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('byteorder', """ A character indicating the byte-order of this data-type object. One of: === ============== '=' native '<' little-endian '>' big-endian '|' not applicable === ============== All built-in data-type objects have byteorder either '=' or '|'. Examples -------- >>> dt = np.dtype('i2') >>> dt.byteorder '=' >>> # endian is not relevant for 8 bit numbers >>> np.dtype('i1').byteorder '|' >>> # or ASCII strings >>> np.dtype('S2').byteorder '|' >>> # Even if specific code is given, and it is native >>> # '=' is the byteorder >>> import sys >>> sys_is_le = sys.byteorder == 'little' >>> native_code = sys_is_le and '<' or '>' >>> swapped_code = sys_is_le and '>' or '<' >>> dt = np.dtype(native_code + 'i2') >>> dt.byteorder '=' >>> # Swapped code shows up as itself >>> dt = np.dtype(swapped_code + 'i2') >>> dt.byteorder == swapped_code True """)) add_newdoc('numpy.core.multiarray', 'dtype', ('char', """A unique character code for each of the 21 different built-in types.""")) add_newdoc('numpy.core.multiarray', 'dtype', ('descr', """ PEP3118 interface description of the data-type. The format is that required by the 'descr' key in the PEP3118 `__array_interface__` attribute. Warning: This attribute exists specifically for PEP3118 compliance, and is not a datatype description compatible with `np.dtype`. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('fields', """ Dictionary of named fields defined for this data type, or ``None``. The dictionary is indexed by keys that are the names of the fields. Each entry in the dictionary is a tuple fully describing the field:: (dtype, offset[, title]) If present, the optional title can be any object (if it is a string or unicode then it will also be a key in the fields dictionary, otherwise it's meta-data). Notice also that the first two elements of the tuple can be passed directly as arguments to the ``ndarray.getfield`` and ``ndarray.setfield`` methods. See Also -------- ndarray.getfield, ndarray.setfield Examples -------- >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> print(dt.fields) {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)} """)) add_newdoc('numpy.core.multiarray', 'dtype', ('flags', """ Bit-flags describing how this data type is to be interpreted. Bit-masks are in `numpy.core.multiarray` as the constants `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`, `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation of these flags is in C-API documentation; they are largely useful for user-defined data-types. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('hasobject', """ Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes. Recall that what is actually in the ndarray memory representing the Python object is the memory address of that object (a pointer). Special handling may be required, and this attribute is useful for distinguishing data types that may contain arbitrary Python objects and data-types that won't. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('isbuiltin', """ Integer indicating how this dtype relates to the built-in dtypes. Read-only. = ======================================================================== 0 if this is a structured array type, with fields 1 if this is a dtype compiled into numpy (such as ints, floats etc) 2 if the dtype is for a user-defined numpy type A user-defined type uses the numpy C-API machinery to extend numpy to handle a new array type. See :ref:`user.user-defined-data-types` in the NumPy manual. = ======================================================================== Examples -------- >>> dt = np.dtype('i2') >>> dt.isbuiltin 1 >>> dt = np.dtype('f8') >>> dt.isbuiltin 1 >>> dt = np.dtype([('field1', 'f8')]) >>> dt.isbuiltin 0 """)) add_newdoc('numpy.core.multiarray', 'dtype', ('isnative', """ Boolean indicating whether the byte order of this dtype is native to the platform. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('isalignedstruct', """ Boolean indicating whether the dtype is a struct which maintains field alignment. This flag is sticky, so when combining multiple structs together, it is preserved and produces new dtypes which are also aligned. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('itemsize', """ The element size of this data-type object. For 18 of the 21 types this number is fixed by the data-type. For the flexible data-types, this number can be anything. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('kind', """ A character code (one of 'biufcmMOSUV') identifying the general kind of data. = ====================== b boolean i signed integer u unsigned integer f floating-point c complex floating-point m timedelta M datetime O object S (byte-)string U Unicode V void = ====================== """)) add_newdoc('numpy.core.multiarray', 'dtype', ('name', """ A bit-width name for this data-type. Un-sized flexible data-type objects do not have this attribute. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('names', """ Ordered list of field names, or ``None`` if there are no fields. The names are ordered according to increasing byte offset. This can be used, for example, to walk through all of the named fields in offset order. Examples -------- >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt.names ('name', 'grades') """)) add_newdoc('numpy.core.multiarray', 'dtype', ('num', """ A unique number for each of the 21 different built-in types. These are roughly ordered from least-to-most precision. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('shape', """ Shape tuple of the sub-array if this data type describes a sub-array, and ``()`` otherwise. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('ndim', """ Number of dimensions of the sub-array if this data type describes a sub-array, and ``0`` otherwise. .. versionadded:: 1.13.0 """)) add_newdoc('numpy.core.multiarray', 'dtype', ('str', """The array-protocol typestring of this data-type object.""")) add_newdoc('numpy.core.multiarray', 'dtype', ('subdtype', """ Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and None otherwise. The *shape* is the fixed shape of the sub-array described by this data type, and *item_dtype* the data type of the array. If a field whose dtype object has this attribute is retrieved, then the extra dimensions implied by *shape* are tacked on to the end of the retrieved array. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('type', """The type object used to instantiate a scalar of this data-type.""")) ############################################################################## # # dtype methods # ############################################################################## add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder', """ newbyteorder(new_order='S') Return a new dtype with a different byte order. Changes are also made in all fields and sub-arrays of the data type. Parameters ---------- new_order : string, optional Byte order to force; a value from the byte order specifications below. The default value ('S') results in swapping the current byte order. `new_order` codes can be any of: * 'S' - swap dtype from current to opposite endian * {'<', 'L'} - little endian * {'>', 'B'} - big endian * {'=', 'N'} - native order * {'|', 'I'} - ignore (no change to byte order) The code does a case-insensitive check on the first letter of `new_order` for these alternatives. For example, any of '>' or 'B' or 'b' or 'brian' are valid to specify big-endian. Returns ------- new_dtype : dtype New dtype object with the given change to the byte order. Notes ----- Changes are also made in all fields and sub-arrays of the data type. Examples -------- >>> import sys >>> sys_is_le = sys.byteorder == 'little' >>> native_code = sys_is_le and '<' or '>' >>> swapped_code = sys_is_le and '>' or '<' >>> native_dt = np.dtype(native_code+'i2') >>> swapped_dt = np.dtype(swapped_code+'i2') >>> native_dt.newbyteorder('S') == swapped_dt True >>> native_dt.newbyteorder() == swapped_dt True >>> native_dt == swapped_dt.newbyteorder('S') True >>> native_dt == swapped_dt.newbyteorder('=') True >>> native_dt == swapped_dt.newbyteorder('N') True >>> native_dt == native_dt.newbyteorder('|') True >>> np.dtype('<i2') == native_dt.newbyteorder('<') True >>> np.dtype('<i2') == native_dt.newbyteorder('L') True >>> np.dtype('>i2') == native_dt.newbyteorder('>') True >>> np.dtype('>i2') == native_dt.newbyteorder('B') True """)) ############################################################################## # # Datetime-related Methods # ############################################################################## add_newdoc('numpy.core.multiarray', 'busdaycalendar', """ busdaycalendar(weekmask='1111100', holidays=None) A business day calendar object that efficiently stores information defining valid days for the busday family of functions. The default valid days are Monday through Friday ("business days"). A busdaycalendar object can be specified with any set of weekly valid days, plus an optional "holiday" dates that always will be invalid. Once a busdaycalendar object is created, the weekmask and holidays cannot be modified. .. versionadded:: 1.7.0 Parameters ---------- weekmask : str or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidays : array_like of datetime64[D], optional An array of dates to consider as invalid dates, no matter which weekday they fall upon. Holiday dates may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. Returns ------- out : busdaycalendar A business day calendar object containing the specified weekmask and holidays values. See Also -------- is_busday : Returns a boolean array indicating valid days. busday_offset : Applies an offset counted in valid days. busday_count : Counts how many valid days are in a half-open date range. Attributes ---------- Note: once a busdaycalendar object is created, you cannot modify the weekmask or holidays. The attributes return copies of internal data. weekmask : (copy) seven-element array of bool holidays : (copy) sorted array of datetime64[D] Examples -------- >>> # Some important days in July ... bdd = np.busdaycalendar( ... holidays=['2011-07-01', '2011-07-04', '2011-07-17']) >>> # Default is Monday to Friday weekdays ... bdd.weekmask array([ True, True, True, True, True, False, False], dtype='bool') >>> # Any holidays already on the weekend are removed ... bdd.holidays array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]') """) add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('weekmask', """A copy of the seven-element boolean mask indicating valid days.""")) add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('holidays', """A copy of the holiday array indicating additional invalid days.""")) add_newdoc('numpy.core.multiarray', 'is_busday', """ is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None) Calculates which of the given dates are valid days, and which are not. .. versionadded:: 1.7.0 Parameters ---------- dates : array_like of datetime64[D] The array of dates to process. weekmask : str or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidays : array_like of datetime64[D], optional An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. busdaycal : busdaycalendar, optional A `busdaycalendar` object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided. out : array of bool, optional If provided, this array is filled with the result. Returns ------- out : array of bool An array with the same shape as ``dates``, containing True for each valid day, and False for each invalid day. See Also -------- busdaycalendar: An object that specifies a custom set of valid days. busday_offset : Applies an offset counted in valid days. busday_count : Counts how many valid days are in a half-open date range. Examples -------- >>> # The weekdays are Friday, Saturday, and Monday ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'], ... holidays=['2011-07-01', '2011-07-04', '2011-07-17']) array([False, False, True], dtype='bool') """) add_newdoc('numpy.core.multiarray', 'busday_offset', """ busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None) First adjusts the date to fall on a valid day according to the ``roll`` rule, then applies offsets to the given dates counted in valid days. .. versionadded:: 1.7.0 Parameters ---------- dates : array_like of datetime64[D] The array of dates to process. offsets : array_like of int The array of offsets, which is broadcast with ``dates``. roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', 'modifiedfollowing', 'modifiedpreceding'}, optional How to treat dates that do not fall on a valid day. The default is 'raise'. * 'raise' means to raise an exception for an invalid day. * 'nat' means to return a NaT (not-a-time) for an invalid day. * 'forward' and 'following' mean to take the first valid day later in time. * 'backward' and 'preceding' mean to take the first valid day earlier in time. * 'modifiedfollowing' means to take the first valid day later in time unless it is across a Month boundary, in which case to take the first valid day earlier in time. * 'modifiedpreceding' means to take the first valid day earlier in time unless it is across a Month boundary, in which case to take the first valid day later in time. weekmask : str or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidays : array_like of datetime64[D], optional An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. busdaycal : busdaycalendar, optional A `busdaycalendar` object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided. out : array of datetime64[D], optional If provided, this array is filled with the result. Returns ------- out : array of datetime64[D] An array with a shape from broadcasting ``dates`` and ``offsets`` together, containing the dates with offsets applied. See Also -------- busdaycalendar: An object that specifies a custom set of valid days. is_busday : Returns a boolean array indicating valid days. busday_count : Counts how many valid days are in a half-open date range. Examples -------- >>> # First business day in October 2011 (not accounting for holidays) ... np.busday_offset('2011-10', 0, roll='forward') numpy.datetime64('2011-10-03','D') >>> # Last business day in February 2012 (not accounting for holidays) ... np.busday_offset('2012-03', -1, roll='forward') numpy.datetime64('2012-02-29','D') >>> # Third Wednesday in January 2011 ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed') numpy.datetime64('2011-01-19','D') >>> # 2012 Mother's Day in Canada and the U.S. ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun') numpy.datetime64('2012-05-13','D') >>> # First business day on or after a date ... np.busday_offset('2011-03-20', 0, roll='forward') numpy.datetime64('2011-03-21','D') >>> np.busday_offset('2011-03-22', 0, roll='forward') numpy.datetime64('2011-03-22','D') >>> # First business day after a date ... np.busday_offset('2011-03-20', 1, roll='backward') numpy.datetime64('2011-03-21','D') >>> np.busday_offset('2011-03-22', 1, roll='backward') numpy.datetime64('2011-03-23','D') """) add_newdoc('numpy.core.multiarray', 'busday_count', """ busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None) Counts the number of valid days between `begindates` and `enddates`, not including the day of `enddates`. If ``enddates`` specifies a date value that is earlier than the corresponding ``begindates`` date value, the count will be negative. .. versionadded:: 1.7.0 Parameters ---------- begindates : array_like of datetime64[D] The array of the first dates for counting. enddates : array_like of datetime64[D] The array of the end dates for counting, which are excluded from the count themselves. weekmask : str or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidays : array_like of datetime64[D], optional An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. busdaycal : busdaycalendar, optional A `busdaycalendar` object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided. out : array of int, optional If provided, this array is filled with the result. Returns ------- out : array of int An array with a shape from broadcasting ``begindates`` and ``enddates`` together, containing the number of valid days between the begin and end dates. See Also -------- busdaycalendar: An object that specifies a custom set of valid days. is_busday : Returns a boolean array indicating valid days. busday_offset : Applies an offset counted in valid days. Examples -------- >>> # Number of weekdays in January 2011 ... np.busday_count('2011-01', '2011-02') 21 >>> # Number of weekdays in 2011 ... np.busday_count('2011', '2012') 260 >>> # Number of Saturdays in 2011 ... np.busday_count('2011', '2012', weekmask='Sat') 53 """) add_newdoc('numpy.core.multiarray', 'normalize_axis_index', """ normalize_axis_index(axis, ndim, msg_prefix=None) Normalizes an axis index, `axis`, such that is a valid positive index into the shape of array with `ndim` dimensions. Raises an AxisError with an appropriate message if this is not possible. Used internally by all axis-checking logic. .. versionadded:: 1.13.0 Parameters ---------- axis : int The un-normalized index of the axis. Can be negative ndim : int The number of dimensions of the array that `axis` should be normalized against msg_prefix : str A prefix to put before the message, typically the name of the argument Returns ------- normalized_axis : int The normalized axis index, such that `0 <= normalized_axis < ndim` Raises ------ AxisError If the axis index is invalid, when `-ndim <= axis < ndim` is false. Examples -------- >>> normalize_axis_index(0, ndim=3) 0 >>> normalize_axis_index(1, ndim=3) 1 >>> normalize_axis_index(-1, ndim=3) 2 >>> normalize_axis_index(3, ndim=3) Traceback (most recent call last): ... AxisError: axis 3 is out of bounds for array of dimension 3 >>> normalize_axis_index(-4, ndim=3, msg_prefix='axes_arg') Traceback (most recent call last): ... AxisError: axes_arg: axis -4 is out of bounds for array of dimension 3 """) ############################################################################## # # nd_grid instances # ############################################################################## add_newdoc('numpy.lib.index_tricks', 'mgrid', """ `nd_grid` instance which returns a dense multi-dimensional "meshgrid". An instance of `numpy.lib.index_tricks.nd_grid` which returns an dense (or fleshed out) mesh-grid when indexed, so that each returned argument has the same shape. The dimensions and number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex number, then the stop is not inclusive. However, if the step length is a **complex number** (e.g. 5j), then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value **is inclusive**. Returns ---------- mesh-grid `ndarrays` all of the same dimensions See Also -------- numpy.lib.index_tricks.nd_grid : class of `ogrid` and `mgrid` objects ogrid : like mgrid but returns open (not fleshed out) mesh grids r_ : array concatenator Examples -------- >>> np.mgrid[0:5,0:5] array([[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]], [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]]) >>> np.mgrid[-1:1:5j] array([-1. , -0.5, 0. , 0.5, 1. ]) """) add_newdoc('numpy.lib.index_tricks', 'ogrid', """ `nd_grid` instance which returns an open multi-dimensional "meshgrid". An instance of `numpy.lib.index_tricks.nd_grid` which returns an open (i.e. not fleshed out) mesh-grid when indexed, so that only one dimension of each returned array is greater than 1. The dimension and number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex number, then the stop is not inclusive. However, if the step length is a **complex number** (e.g. 5j), then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value **is inclusive**. Returns ---------- mesh-grid `ndarrays` with only one dimension :math:`\\neq 1` See Also -------- np.lib.index_tricks.nd_grid : class of `ogrid` and `mgrid` objects mgrid : like `ogrid` but returns dense (or fleshed out) mesh grids r_ : array concatenator Examples -------- >>> from numpy import ogrid >>> ogrid[-1:1:5j] array([-1. , -0.5, 0. , 0.5, 1. ]) >>> ogrid[0:5,0:5] [array([[0], [1], [2], [3], [4]]), array([[0, 1, 2, 3, 4]])] """) ############################################################################## # # Documentation for `generic` attributes and methods # ############################################################################## add_newdoc('numpy.core.numerictypes', 'generic', """ Base class for numpy scalar types. Class from which most (all?) numpy scalar types are derived. For consistency, exposes the same API as `ndarray`, despite many consequent attributes being either "get-only," or completely irrelevant. This is the class from which it is strongly suggested users should derive custom scalar types. """) # Attributes add_newdoc('numpy.core.numerictypes', 'generic', ('T', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('base', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('data', """Pointer to start of data.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('dtype', """Get array data-descriptor.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('flags', """The integer value of flags.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('flat', """A 1-D view of the scalar.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('imag', """The imaginary part of the scalar.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('itemsize', """The length of one element in bytes.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('nbytes', """The length of the scalar in bytes.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('ndim', """The number of array dimensions.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('real', """The real part of the scalar.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('shape', """Tuple of array dimensions.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('size', """The number of elements in the gentype.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('strides', """Tuple of bytes steps in each dimension.""")) # Methods add_newdoc('numpy.core.numerictypes', 'generic', ('all', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('any', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('argmax', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('argmin', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('argsort', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('astype', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('byteswap', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('choose', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('clip', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('compress', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('conjugate', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('copy', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('cumprod', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('cumsum', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('diagonal', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('dump', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('dumps', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('fill', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('flatten', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('getfield', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('item', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('itemset', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('max', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('mean', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('min', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('newbyteorder', """ newbyteorder(new_order='S') Return a new `dtype` with a different byte order. Changes are also made in all fields and sub-arrays of the data type. The `new_order` code can be any from the following: * 'S' - swap dtype from current to opposite endian * {'<', 'L'} - little endian * {'>', 'B'} - big endian * {'=', 'N'} - native order * {'|', 'I'} - ignore (no change to byte order) Parameters ---------- new_order : str, optional Byte order to force; a value from the byte order specifications above. The default value ('S') results in swapping the current byte order. The code does a case-insensitive check on the first letter of `new_order` for the alternatives above. For example, any of 'B' or 'b' or 'biggish' are valid to specify big-endian. Returns ------- new_dtype : dtype New `dtype` object with the given change to the byte order. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('nonzero', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('prod', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('ptp', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('put', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('ravel', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('repeat', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('reshape', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('resize', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('round', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('searchsorted', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('setfield', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('setflags', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('sort', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('squeeze', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('std', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('sum', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('swapaxes', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('take', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('tofile', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('tolist', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('tostring', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('trace', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('transpose', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('var', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('view', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) ############################################################################## # # Documentation for other scalar classes # ############################################################################## add_newdoc('numpy.core.numerictypes', 'bool_', """NumPy's Boolean type. Character code: ``?``. Alias: bool8""") add_newdoc('numpy.core.numerictypes', 'complex64', """ Complex number type composed of two 32 bit floats. Character code: 'F'. """) add_newdoc('numpy.core.numerictypes', 'complex128', """ Complex number type composed of two 64 bit floats. Character code: 'D'. Python complex compatible. """) add_newdoc('numpy.core.numerictypes', 'complex256', """ Complex number type composed of two 128-bit floats. Character code: 'G'. """) add_newdoc('numpy.core.numerictypes', 'float32', """ 32-bit floating-point number. Character code 'f'. C float compatible. """) add_newdoc('numpy.core.numerictypes', 'float64', """ 64-bit floating-point number. Character code 'd'. Python float compatible. """) add_newdoc('numpy.core.numerictypes', 'float96', """ """) add_newdoc('numpy.core.numerictypes', 'float128', """ 128-bit floating-point number. Character code: 'g'. C long float compatible. """) add_newdoc('numpy.core.numerictypes', 'int8', """8-bit integer. Character code ``b``. C char compatible.""") add_newdoc('numpy.core.numerictypes', 'int16', """16-bit integer. Character code ``h``. C short compatible.""") add_newdoc('numpy.core.numerictypes', 'int32', """32-bit integer. Character code 'i'. C int compatible.""") add_newdoc('numpy.core.numerictypes', 'int64', """64-bit integer. Character code 'l'. Python int compatible.""") add_newdoc('numpy.core.numerictypes', 'object_', """Any Python object. Character code: 'O'.""")
gpl-3.0
angr/angr
angr/analyses/identifier/functions/strcmp.py
3
3509
import random from ..func import Func, TestData def rand_str(length, byte_list=None): if byte_list is None: return "".join(chr(random.randint(0, 255)) for _ in range(length)) return "".join(random.choice(byte_list) for _ in range(length)) class strcmp(Func): non_null = [chr(i) for i in range(1, 256)] def __init__(self): super(strcmp, self).__init__() #pylint disable=useless-super-delegation def get_name(self): return "strcmp" def num_args(self): return 2 def args(self): #pylint disable=no-self-use return ["buf1", "buf2"] def gen_input_output_pair(self): l = 5 s = rand_str(l, strcmp.non_null) #pylint disable=unused-variable return None def can_call_other_funcs(self): return False def pre_test(self, func, runner): r = self._strcmp_pretest(func, runner) if not isinstance(r, bool): v1, v2, v3, v4 = r return v1 == 0 and v2 != 0 and v3 != 0 and v4 != 0 return r @staticmethod def _strcmp_pretest(func, runner): # todo we don't test which order it returns the signs in bufa = "asdf\x00" bufb = "asdf\x00" test_input = [bufa, bufb] test_output = [bufa, bufb] max_steps = 10 return_val = None test = TestData(test_input, test_output, return_val, max_steps) s = runner.get_out_state(func, test) if s is None or s.solver.eval(s.regs.eax) != 0: return False bufa = "asde\x00" bufb = "asde\x00" test_input = [bufa, bufb] test_output = [bufa, bufb] max_steps = 10 return_val = None test = TestData(test_input, test_output, return_val, max_steps) s = runner.get_out_state(func, test) if s is None or s.solver.eval(s.regs.eax) != 0: return False # should return true for strcmp, false for memcpy bufa = "asdfa\x00sfdadfsa" bufb = "asdfa\x00sadfsadf" test_input = [bufa, bufb] test_output = [bufa, bufb] test = TestData(test_input, test_output, return_val, max_steps) s = runner.get_out_state(func, test) if s is None: return False outval1 = s.solver.eval(s.regs.eax) # should fail bufa = "asdfc\x00as" bufb = "asdfb\x0011232" test_input = [bufa, bufb] test_output = [bufa, bufb] test = TestData(test_input, test_output, return_val, max_steps) s = runner.get_out_state(func, test) if s is None: return False outval2 = s.solver.eval(s.regs.eax) # should prevent us from misidentifying strcasecmp bufa = "ASDFC\x00" bufb = "asdfc\x00" test_input = [bufa, bufb] test_output = [bufa, bufb] test = TestData(test_input, test_output, return_val, max_steps) s = runner.get_out_state(func, test) if s is None: return False outval3 = s.solver.eval(s.regs.eax) # should distinguish between strcmp and strncmp bufa = "abc555" bufb = "abc666" test_input = [bufa, bufb, 3] test_output = [bufa, bufb, 3] test = TestData(test_input, test_output, return_val, max_steps) s = runner.get_out_state(func, test) if s is None: return False outval4 = s.solver.eval(s.regs.eax) return outval1, outval2, outval3, outval4
bsd-2-clause
rgeleta/odoo
addons/portal_project/project.py
285
1809
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013-TODAY OpenERP S.A (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv from openerp.tools.translate import _ class portal_project(osv.Model): """ Update of mail_mail class, to add the signin URL to notifications. """ _inherit = 'project.project' def _get_visibility_selection(self, cr, uid, context=None): """ Override to add portal option. """ selection = super(portal_project, self)._get_visibility_selection(cr, uid, context=context) idx = [item[0] for item in selection].index('public') selection.insert((idx + 1), ('portal', _('Customer related project: visible through portal'))) return selection # return [('public', 'All Users'), # ('portal', 'Portal Users and Employees'), # ('employees', 'Employees Only'), # ('followers', 'Followers Only')]
agpl-3.0
nicobustillos/odoo
addons/base_report_designer/openerp_sxw2rml/__init__.py
423
1091
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp_sxw2rml import sxw2rml # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
simongoffin/website_version
openerp/service/report.py
49
5025
# -*- coding: utf-8 -*- import base64 import logging import sys import threading import openerp import openerp.report from openerp import tools import security _logger = logging.getLogger(__name__) # TODO: set a maximum report number per user to avoid DOS attacks # # Report state: # False -> True self_reports = {} self_id = 0 self_id_protect = threading.Semaphore() def dispatch(method, params): (db, uid, passwd ) = params[0:3] threading.current_thread().uid = uid params = params[3:] if method not in ['report', 'report_get', 'render_report']: raise KeyError("Method not supported %s" % method) security.check(db,uid,passwd) openerp.modules.registry.RegistryManager.check_registry_signaling(db) fn = globals()['exp_' + method] res = fn(db, uid, *params) openerp.modules.registry.RegistryManager.signal_caches_change(db) return res def exp_render_report(db, uid, object, ids, datas=None, context=None): if not datas: datas={} if not context: context={} self_id_protect.acquire() global self_id self_id += 1 id = self_id self_id_protect.release() self_reports[id] = {'uid': uid, 'result': False, 'state': False, 'exception': None} cr = openerp.registry(db).cursor() try: result, format = openerp.report.render_report(cr, uid, ids, object, datas, context) if not result: tb = sys.exc_info() self_reports[id]['exception'] = openerp.exceptions.DeferredException('RML is not available at specified location or not enough data to print!', tb) self_reports[id]['result'] = result self_reports[id]['format'] = format self_reports[id]['state'] = True except Exception, exception: _logger.exception('Exception: %s\n', exception) if hasattr(exception, 'name') and hasattr(exception, 'value'): self_reports[id]['exception'] = openerp.exceptions.DeferredException(tools.ustr(exception.name), tools.ustr(exception.value)) else: tb = sys.exc_info() self_reports[id]['exception'] = openerp.exceptions.DeferredException(tools.exception_to_unicode(exception), tb) self_reports[id]['state'] = True cr.commit() cr.close() return _check_report(id) def exp_report(db, uid, object, ids, datas=None, context=None): if not datas: datas={} if not context: context={} self_id_protect.acquire() global self_id self_id += 1 id = self_id self_id_protect.release() self_reports[id] = {'uid': uid, 'result': False, 'state': False, 'exception': None} def go(id, uid, ids, datas, context): cr = openerp.registry(db).cursor() try: result, format = openerp.report.render_report(cr, uid, ids, object, datas, context) if not result: tb = sys.exc_info() self_reports[id]['exception'] = openerp.exceptions.DeferredException('RML is not available at specified location or not enough data to print!', tb) self_reports[id]['result'] = result self_reports[id]['format'] = format self_reports[id]['state'] = True except Exception, exception: _logger.exception('Exception: %s\n', exception) if hasattr(exception, 'name') and hasattr(exception, 'value'): self_reports[id]['exception'] = openerp.exceptions.DeferredException(tools.ustr(exception.name), tools.ustr(exception.value)) else: tb = sys.exc_info() self_reports[id]['exception'] = openerp.exceptions.DeferredException(tools.exception_to_unicode(exception), tb) self_reports[id]['state'] = True cr.commit() cr.close() return True threading.Thread(target=go, args=(id, uid, ids, datas, context)).start() return id def _check_report(report_id): result = self_reports[report_id] exc = result['exception'] if exc: raise openerp.osv.orm.except_orm(exc.message, exc.traceback) res = {'state': result['state']} if res['state']: if tools.config['reportgz']: import zlib res2 = zlib.compress(result['result']) res['code'] = 'zlib' else: #CHECKME: why is this needed??? if isinstance(result['result'], unicode): res2 = result['result'].encode('latin1', 'replace') else: res2 = result['result'] if res2: res['result'] = base64.encodestring(res2) res['format'] = result['format'] del self_reports[report_id] return res def exp_report_get(db, uid, report_id): if report_id in self_reports: if self_reports[report_id]['uid'] == uid: return _check_report(report_id) else: raise Exception, 'AccessDenied' else: raise Exception, 'ReportNotFound' # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
openprocurement/openprocurement.auction.insider
openprocurement/auction/insider/tests/unit/conftest.py
1
6502
# -*- coding: utf-8 -*- import datetime import logging import os import pytest import yaml import couchdb import json from dateutil.tz import tzlocal from flask import redirect from mock import MagicMock from pytz import timezone as tz from StringIO import StringIO from mock import patch from openprocurement.auction.insider.auction import Auction, SCHEDULER from openprocurement.auction.insider.server import app as server_app from openprocurement.auction.insider.forms import BidsForm, form_handler from openprocurement.auction.insider.mixins import LOGGER from openprocurement.auction.insider.constants import ( PRESEALEDBID, SEALEDBID, PREBESTBID ) from openprocurement.auction.insider.tests.data.data import ( tender_data, bidders ) def update_auctionPeriod(data): new_start_time = (datetime.datetime.now(tzlocal()) + datetime.timedelta(seconds=120)).isoformat() if 'lots' in data['data']: for lot in data['data']['lots']: lot['auctionPeriod']['startDate'] = new_start_time data['data']['auctionPeriod']['startDate'] = new_start_time PWD = os.path.dirname(os.path.realpath(__file__)) worker_defaults_file_path = os.path.join( os.getcwd(), "openprocurement/auction/insider/tests/data/auction_worker_insider.yaml") with open(worker_defaults_file_path) as stream: worker_defaults = yaml.load(stream) @pytest.yield_fixture(scope="function") def auction(): update_auctionPeriod(tender_data) yield Auction( tender_id=tender_data['data']['tenderID'], worker_defaults=yaml.load(open(worker_defaults_file_path)), auction_data=tender_data ) @pytest.fixture(scope='function') def db(request): server = couchdb.Server("http://" + worker_defaults['COUCH_DATABASE'].split('/')[2]) name = worker_defaults['COUCH_DATABASE'].split('/')[3] def delete(): del server[name] if name in server: delete() server.create(name) request.addfinalizer(delete) class LogInterceptor(object): def __init__(self, logger): self.log_capture_string = StringIO() self.test_handler = logging.StreamHandler(self.log_capture_string) self.test_handler.setLevel(logging.INFO) logger.addHandler(self.test_handler) @pytest.fixture(scope='function') def logger(): return LogInterceptor(LOGGER) @pytest.fixture(scope='function') def scheduler(): return SCHEDULER @pytest.fixture(scope='function') def bids_form(auction, db): form = BidsForm() auction.prepare_auction_document() form.document = auction.auction_document return form @pytest.yield_fixture(scope='function') def app(db): update_auctionPeriod(tender_data) logger = MagicMock() logger.name = 'some-logger' app_auction = Auction( tender_id=tender_data['data']['tenderID'], worker_defaults=yaml.load(open(worker_defaults_file_path)), auction_data=tender_data ) app_auction.prepare_auction_document() app_auction.schedule_auction() app_auction.start_auction() server_app.config.update(app_auction.worker_defaults) server_app.logger_name = logger.name server_app._logger = logger server_app.config['auction'] = app_auction server_app.config['timezone'] = tz('Europe/Kiev') server_app.config['SESSION_COOKIE_PATH'] = '/{}/{}'.format( 'auctions', app_auction.auction_doc_id) server_app.config['SESSION_COOKIE_NAME'] = 'auction_session' server_app.oauth = MagicMock() server_app.bids_form = BidsForm server_app.form_handler = MagicMock() server_app.form_handler.return_value = {'data': 'ok'} server_app.remote_oauth = MagicMock() authorized_response = { u'access_token': u'aMALGpjnB1iyBwXJM6betfgT4usHqw', u'token_type': u'Bearer', u'expires_in': 86400, u'refresh_token': u'uoRKeSJl9UFjuMwOw6PikXuUVp7MjX', u'scope': u'email' } server_app.remote_oauth.authorized_response.side_effect = [ None, authorized_response, authorized_response] server_app.remote_oauth.authorize.return_value = \ redirect('https://my.test.url') for bidder in bidders.values(): server_app.logins_cache[bidder['remote_oauth']] = { u'bidder_id': bidder['bidder_id'], u'expires': (datetime.datetime.now(tzlocal()) + datetime.timedelta(0, 600)).isoformat() } server_app.auction_bidders = { u'f7c8cd1d56624477af8dc3aa9c4b3ea3': { 'clients': {}, 'channels': {} }} yield server_app.test_client() @pytest.yield_fixture(scope='function') def auction_app(app): for bidder in bidders.values(): if bidder['bidder_id'] == '2' * 32 or bidder['bidder_id'] == '1' * 32: continue app.application.config['auction'].bidders_data.append( {'id': bidder['bidder_id']}) app.application.config['auction'].mapping[bidder['bidder_id']] = \ len(app.application.config['auction'].mapping) + 1 app.application.form_handler = form_handler yield app @pytest.yield_fixture(scope='function') def sealedbid_app(auction_app): headers = {'Content-Type': 'application/json'} session = { 'remote_oauth': None, 'client_id': 'b3a000cdd006b4176cc9fafb46be0273' } stage = \ auction_app.application.config['auction'].auction_document['stages'][1] for i in xrange(0, 6): auction_app.application.config['auction'].next_stage(stage) data = { 'bidder_id': bidders['dutch_bidder']['bidder_id'], 'bid': 33250 } session['remote_oauth'] = bidders['dutch_bidder']['remote_oauth'] with patch('openprocurement.auction.insider.server.session', session), \ patch('openprocurement.auction.insider.forms.session', session): auction_app.post('/postbid', data=json.dumps(data), headers=headers) yield auction_app def pytest_addoption(parser): parser.addoption("--worker", action="store_true", help="runs worker test", dest='worker') def pytest_configure(config): # register an additional marker config.addinivalue_line("markers", "worker: mark test to run only if worker option is passed (--worker)") def pytest_runtest_setup(item): worker_marker = item.get_marker("worker") if worker_marker is not None: if not item.config.getoption("worker", False): pytest.skip("test requires worker option (--worker)")
apache-2.0
Workday/OpenFrame
ppapi/native_client/tools/browser_tester/browsertester/browserlauncher.py
81
11818
#!/usr/bin/python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os.path import re import shutil import sys import tempfile import time import urlparse import browserprocess class LaunchFailure(Exception): pass def GetPlatform(): if sys.platform == 'darwin': platform = 'mac' elif sys.platform.startswith('linux'): platform = 'linux' elif sys.platform in ('cygwin', 'win32'): platform = 'windows' else: raise LaunchFailure('Unknown platform: %s' % sys.platform) return platform PLATFORM = GetPlatform() def SelectRunCommand(): # The subprocess module added support for .kill in Python 2.6 assert (sys.version_info[0] >= 3 or (sys.version_info[0] == 2 and sys.version_info[1] >= 6)) if PLATFORM == 'linux': return browserprocess.RunCommandInProcessGroup else: return browserprocess.RunCommandWithSubprocess RunCommand = SelectRunCommand() def RemoveDirectory(path): retry = 5 sleep_time = 0.25 while True: try: shutil.rmtree(path) except Exception: # Windows processes sometime hang onto files too long if retry > 0: retry -= 1 time.sleep(sleep_time) sleep_time *= 2 else: # No luck - don't mask the error raise else: # succeeded break # In Windows, subprocess seems to have an issue with file names that # contain spaces. def EscapeSpaces(path): if PLATFORM == 'windows' and ' ' in path: return '"%s"' % path return path def MakeEnv(options): env = dict(os.environ) # Enable PPAPI Dev interfaces for testing. env['NACL_ENABLE_PPAPI_DEV'] = str(options.enable_ppapi_dev) if options.debug: env['NACL_PLUGIN_DEBUG'] = '1' # env['NACL_SRPC_DEBUG'] = '1' return env class BrowserLauncher(object): WAIT_TIME = 20 WAIT_STEPS = 80 SLEEP_TIME = float(WAIT_TIME) / WAIT_STEPS def __init__(self, options): self.options = options self.profile = None self.binary = None self.tool_log_dir = None def KnownPath(self): raise NotImplementedError def BinaryName(self): raise NotImplementedError def CreateProfile(self): raise NotImplementedError def MakeCmd(self, url, host, port): raise NotImplementedError def CreateToolLogDir(self): self.tool_log_dir = tempfile.mkdtemp(prefix='vglogs_') return self.tool_log_dir def FindBinary(self): if self.options.browser_path: return self.options.browser_path else: path = self.KnownPath() if path is None or not os.path.exists(path): raise LaunchFailure('Cannot find the browser directory') binary = os.path.join(path, self.BinaryName()) if not os.path.exists(binary): raise LaunchFailure('Cannot find the browser binary') return binary def WaitForProcessDeath(self): self.browser_process.Wait(self.WAIT_STEPS, self.SLEEP_TIME) def Cleanup(self): self.browser_process.Kill() RemoveDirectory(self.profile) if self.tool_log_dir is not None: RemoveDirectory(self.tool_log_dir) def MakeProfileDirectory(self): self.profile = tempfile.mkdtemp(prefix='browserprofile_') return self.profile def SetStandardStream(self, env, var_name, redirect_file, is_output): if redirect_file is None: return file_prefix = 'file:' dev_prefix = 'dev:' debug_warning = 'DEBUG_ONLY:' # logic must match src/trusted/service_runtime/nacl_resource.* # resource specification notation. file: is the default # interpretation, so we must have an exhaustive list of # alternative schemes accepted. if we remove the file-is-default # interpretation, replace with # is_file = redirect_file.startswith(file_prefix) # and remove the list of non-file schemes. is_file = (not (redirect_file.startswith(dev_prefix) or redirect_file.startswith(debug_warning + dev_prefix))) if is_file: if redirect_file.startswith(file_prefix): bare_file = redirect_file[len(file_prefix)] else: bare_file = redirect_file # why always abspath? does chrome chdir or might it in the # future? this means we do not test/use the relative path case. redirect_file = file_prefix + os.path.abspath(bare_file) else: bare_file = None # ensure error if used without checking is_file env[var_name] = redirect_file if is_output: # sel_ldr appends program output to the file so we need to clear it # in order to get the stable result. if is_file: if os.path.exists(bare_file): os.remove(bare_file) parent_dir = os.path.dirname(bare_file) # parent directory may not exist. if not os.path.exists(parent_dir): os.makedirs(parent_dir) def Launch(self, cmd, env): browser_path = cmd[0] if not os.path.exists(browser_path): raise LaunchFailure('Browser does not exist %r'% browser_path) if not os.access(browser_path, os.X_OK): raise LaunchFailure('Browser cannot be executed %r (Is this binary on an ' 'NFS volume?)' % browser_path) if self.options.sel_ldr: env['NACL_SEL_LDR'] = self.options.sel_ldr if self.options.sel_ldr_bootstrap: env['NACL_SEL_LDR_BOOTSTRAP'] = self.options.sel_ldr_bootstrap if self.options.irt_library: env['NACL_IRT_LIBRARY'] = self.options.irt_library self.SetStandardStream(env, 'NACL_EXE_STDIN', self.options.nacl_exe_stdin, False) self.SetStandardStream(env, 'NACL_EXE_STDOUT', self.options.nacl_exe_stdout, True) self.SetStandardStream(env, 'NACL_EXE_STDERR', self.options.nacl_exe_stderr, True) print 'ENV:', ' '.join(['='.join(pair) for pair in env.iteritems()]) print 'LAUNCHING: %s' % ' '.join(cmd) sys.stdout.flush() self.browser_process = RunCommand(cmd, env=env) def IsRunning(self): return self.browser_process.IsRunning() def GetReturnCode(self): return self.browser_process.GetReturnCode() def Run(self, url, host, port): self.binary = EscapeSpaces(self.FindBinary()) self.profile = self.CreateProfile() if self.options.tool is not None: self.tool_log_dir = self.CreateToolLogDir() cmd = self.MakeCmd(url, host, port) self.Launch(cmd, MakeEnv(self.options)) def EnsureDirectory(path): if not os.path.exists(path): os.makedirs(path) def EnsureDirectoryForFile(path): EnsureDirectory(os.path.dirname(path)) class ChromeLauncher(BrowserLauncher): def KnownPath(self): if PLATFORM == 'linux': # TODO(ncbray): look in path? return '/opt/google/chrome' elif PLATFORM == 'mac': return '/Applications/Google Chrome.app/Contents/MacOS' else: homedir = os.path.expanduser('~') path = os.path.join(homedir, r'AppData\Local\Google\Chrome\Application') return path def BinaryName(self): if PLATFORM == 'mac': return 'Google Chrome' elif PLATFORM == 'windows': return 'chrome.exe' else: return 'chrome' def MakeEmptyJSONFile(self, path): EnsureDirectoryForFile(path) f = open(path, 'w') f.write('{}') f.close() def CreateProfile(self): profile = self.MakeProfileDirectory() # Squelch warnings by creating bogus files. self.MakeEmptyJSONFile(os.path.join(profile, 'Default', 'Preferences')) self.MakeEmptyJSONFile(os.path.join(profile, 'Local State')) return profile def NetLogName(self): return os.path.join(self.profile, 'netlog.json') def MakeCmd(self, url, host, port): cmd = [self.binary, # --enable-logging enables stderr output from Chromium subprocesses # on Windows (see # https://code.google.com/p/chromium/issues/detail?id=171836) '--enable-logging', '--disable-web-resources', '--disable-preconnect', # This is speculative, sync should not occur with a clean profile. '--disable-sync', # This prevents Chrome from making "hidden" network requests at # startup. These requests could be a source of non-determinism, # and they also add noise to the netlogs. '--dns-prefetch-disable', '--no-first-run', '--no-default-browser-check', '--log-level=1', '--safebrowsing-disable-auto-update', '--disable-default-apps', # Suppress metrics reporting. This prevents misconfigured bots, # people testing at their desktop, etc from poisoning the UMA data. '--metrics-recording-only', # Chrome explicitly blacklists some ports as "unsafe" because # certain protocols use them. Chrome gives an error like this: # Error 312 (net::ERR_UNSAFE_PORT): Unknown error # Unfortunately, the browser tester can randomly choose a # blacklisted port. To work around this, the tester whitelists # whatever port it is using. '--explicitly-allowed-ports=%d' % port, '--user-data-dir=%s' % self.profile] # Log network requests to assist debugging. cmd.append('--log-net-log=%s' % self.NetLogName()) if PLATFORM == 'linux': # Explicitly run with mesa on linux. The test infrastructure doesn't have # sufficient native GL contextes to run these tests. cmd.append('--use-gl=osmesa') if self.options.ppapi_plugin is None: cmd.append('--enable-nacl') disable_sandbox = False # Chrome process can't access file within sandbox disable_sandbox |= self.options.nacl_exe_stdin is not None disable_sandbox |= self.options.nacl_exe_stdout is not None disable_sandbox |= self.options.nacl_exe_stderr is not None if disable_sandbox: cmd.append('--no-sandbox') else: cmd.append('--register-pepper-plugins=%s;%s' % (self.options.ppapi_plugin, self.options.ppapi_plugin_mimetype)) cmd.append('--no-sandbox') if self.options.browser_extensions: cmd.append('--load-extension=%s' % ','.join(self.options.browser_extensions)) cmd.append('--enable-experimental-extension-apis') if self.options.enable_crash_reporter: cmd.append('--enable-crash-reporter-for-testing') if self.options.tool == 'memcheck': cmd = ['src/third_party/valgrind/memcheck.sh', '-v', '--xml=yes', '--leak-check=no', '--gen-suppressions=all', '--num-callers=30', '--trace-children=yes', '--nacl-file=%s' % (self.options.files[0],), '--suppressions=' + '../tools/valgrind/memcheck/suppressions.txt', '--xml-file=%s/xml.%%p' % (self.tool_log_dir,), '--log-file=%s/log.%%p' % (self.tool_log_dir,)] + cmd elif self.options.tool == 'tsan': cmd = ['src/third_party/valgrind/tsan.sh', '-v', '--num-callers=30', '--trace-children=yes', '--nacl-file=%s' % (self.options.files[0],), '--ignore=../tools/valgrind/tsan/ignores.txt', '--suppressions=../tools/valgrind/tsan/suppressions.txt', '--log-file=%s/log.%%p' % (self.tool_log_dir,)] + cmd elif self.options.tool != None: raise LaunchFailure('Invalid tool name "%s"' % (self.options.tool,)) if self.options.enable_sockets: cmd.append('--allow-nacl-socket-api=%s' % host) cmd.extend(self.options.browser_flags) cmd.append(url) return cmd
bsd-3-clause
alexis-82/suiteAV
init/lang/en/lib/ansi.py
527
1039
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. ''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code ''' CSI = '\033[' def code_to_chars(code): return CSI + str(code) + 'm' class AnsiCodes(object): def __init__(self, codes): for name in dir(codes): if not name.startswith('_'): value = getattr(codes, name) setattr(self, name, code_to_chars(value)) class AnsiFore: BLACK = 30 RED = 31 GREEN = 32 YELLOW = 33 BLUE = 34 MAGENTA = 35 CYAN = 36 WHITE = 37 RESET = 39 class AnsiBack: BLACK = 40 RED = 41 GREEN = 42 YELLOW = 43 BLUE = 44 MAGENTA = 45 CYAN = 46 WHITE = 47 RESET = 49 class AnsiStyle: BRIGHT = 1 DIM = 2 NORMAL = 22 RESET_ALL = 0 Fore = AnsiCodes( AnsiFore ) Back = AnsiCodes( AnsiBack ) Style = AnsiCodes( AnsiStyle )
gpl-2.0
JianyuWang/neutron
neutron/tests/unit/notifiers/test_nova.py
18
14302
# Copyright 2014 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from novaclient import exceptions as nova_exceptions from oslo_utils import uuidutils from sqlalchemy.orm import attributes as sql_attr from oslo_config import cfg from neutron.common import constants from neutron.db import models_v2 from neutron.notifiers import nova from neutron.tests import base class TestNovaNotify(base.BaseTestCase): def setUp(self, plugin=None): super(TestNovaNotify, self).setUp() class FakePlugin(object): def get_port(self, context, port_id): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' return {'device_id': device_id, 'device_owner': 'compute:None'} self.nova_notifier = nova.Notifier() self.nova_notifier._plugin_ref = FakePlugin() def test_notify_port_status_all_values(self): states = [constants.PORT_STATUS_ACTIVE, constants.PORT_STATUS_DOWN, constants.PORT_STATUS_ERROR, constants.PORT_STATUS_BUILD, sql_attr.NO_VALUE] device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' # test all combinations for previous_port_status in states: for current_port_status in states: port = models_v2.Port(id='port-uuid', device_id=device_id, device_owner="compute:", status=current_port_status) self._record_port_status_changed_helper(current_port_status, previous_port_status, port) def test_port_without_uuid_device_id_no_notify(self): port = models_v2.Port(id='port-uuid', device_id='compute_probe:', device_owner='compute:', status=constants.PORT_STATUS_ACTIVE) self._record_port_status_changed_helper(constants.PORT_STATUS_ACTIVE, sql_attr.NO_VALUE, port) def test_port_without_device_owner_no_notify(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' port = models_v2.Port(id='port-uuid', device_id=device_id, status=constants.PORT_STATUS_ACTIVE) self._record_port_status_changed_helper(constants.PORT_STATUS_ACTIVE, sql_attr.NO_VALUE, port) def test_port_without_device_id_no_notify(self): port = models_v2.Port(id='port-uuid', device_owner="network:dhcp", status=constants.PORT_STATUS_ACTIVE) self._record_port_status_changed_helper(constants.PORT_STATUS_ACTIVE, sql_attr.NO_VALUE, port) def test_port_without_id_no_notify(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' port = models_v2.Port(device_id=device_id, device_owner="compute:", status=constants.PORT_STATUS_ACTIVE) self._record_port_status_changed_helper(constants.PORT_STATUS_ACTIVE, sql_attr.NO_VALUE, port) def test_non_compute_instances_no_notify(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' port = models_v2.Port(id='port-uuid', device_id=device_id, device_owner="network:dhcp", status=constants.PORT_STATUS_ACTIVE) self._record_port_status_changed_helper(constants.PORT_STATUS_ACTIVE, sql_attr.NO_VALUE, port) def _record_port_status_changed_helper(self, current_port_status, previous_port_status, port): if not (port.device_id and port.id and port.device_owner and port.device_owner.startswith('compute:') and uuidutils.is_uuid_like(port.device_id)): return if (previous_port_status == constants.PORT_STATUS_ACTIVE and current_port_status == constants.PORT_STATUS_DOWN): event_name = nova.VIF_UNPLUGGED elif (previous_port_status in [sql_attr.NO_VALUE, constants.PORT_STATUS_DOWN, constants.PORT_STATUS_BUILD] and current_port_status in [constants.PORT_STATUS_ACTIVE, constants.PORT_STATUS_ERROR]): event_name = nova.VIF_PLUGGED else: return status = nova.NEUTRON_NOVA_EVENT_STATUS_MAP.get(current_port_status) self.nova_notifier.record_port_status_changed(port, current_port_status, previous_port_status, None) event = {'server_uuid': port.device_id, 'status': status, 'name': event_name, 'tag': 'port-uuid'} self.assertEqual(event, port._notify_event) def test_update_fixed_ip_changed(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' returned_obj = {'port': {'device_owner': u'compute:dfd', 'id': u'bee50827-bcee-4cc8-91c1-a27b0ce54222', 'device_id': device_id}} expected_event = {'server_uuid': device_id, 'name': 'network-changed'} event = self.nova_notifier.create_port_changed_event('update_port', {}, returned_obj) self.assertEqual(event, expected_event) def test_create_floatingip_notify(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' returned_obj = {'floatingip': {'port_id': u'bee50827-bcee-4cc8-91c1-a27b0ce54222'}} expected_event = {'server_uuid': device_id, 'name': 'network-changed'} event = self.nova_notifier.create_port_changed_event( 'create_floatingip', {}, returned_obj) self.assertEqual(event, expected_event) def test_create_floatingip_no_port_id_no_notify(self): returned_obj = {'floatingip': {'port_id': None}} event = self.nova_notifier.create_port_changed_event( 'create_floatingip', {}, returned_obj) self.assertFalse(event, None) def test_delete_floatingip_notify(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' returned_obj = {'floatingip': {'port_id': u'bee50827-bcee-4cc8-91c1-a27b0ce54222'}} expected_event = {'server_uuid': device_id, 'name': 'network-changed'} event = self.nova_notifier.create_port_changed_event( 'delete_floatingip', {}, returned_obj) self.assertEqual(expected_event, event) def test_delete_floatingip_no_port_id_no_notify(self): returned_obj = {'floatingip': {'port_id': None}} event = self.nova_notifier.create_port_changed_event( 'delete_floatingip', {}, returned_obj) self.assertEqual(event, None) def test_associate_floatingip_notify(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' returned_obj = {'floatingip': {'port_id': u'5a39def4-3d3f-473d-9ff4-8e90064b9cc1'}} original_obj = {'port_id': None} expected_event = {'server_uuid': device_id, 'name': 'network-changed'} event = self.nova_notifier.create_port_changed_event( 'update_floatingip', original_obj, returned_obj) self.assertEqual(expected_event, event) def test_disassociate_floatingip_notify(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' returned_obj = {'floatingip': {'port_id': None}} original_obj = {'port_id': '5a39def4-3d3f-473d-9ff4-8e90064b9cc1'} expected_event = {'server_uuid': device_id, 'name': 'network-changed'} event = self.nova_notifier.create_port_changed_event( 'update_floatingip', original_obj, returned_obj) self.assertEqual(expected_event, event) def test_no_notification_notify_nova_on_port_data_changes_false(self): cfg.CONF.set_override('notify_nova_on_port_data_changes', False) with mock.patch.object(self.nova_notifier, 'send_events') as send_events: self.nova_notifier.send_network_change('update_floatingip', {}, {}) self.assertFalse(send_events.called, False) def test_nova_send_events_returns_bad_list(self): with mock.patch.object( self.nova_notifier.nclient.server_external_events, 'create') as nclient_create: nclient_create.return_value = 'i am a string!' self.nova_notifier.send_events([]) def test_nova_send_event_rasies_404(self): with mock.patch.object( self.nova_notifier.nclient.server_external_events, 'create') as nclient_create: nclient_create.side_effect = nova_exceptions.NotFound self.nova_notifier.send_events([]) def test_nova_send_events_raises(self): with mock.patch.object( self.nova_notifier.nclient.server_external_events, 'create') as nclient_create: nclient_create.side_effect = Exception self.nova_notifier.send_events([]) def test_nova_send_events_returns_non_200(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' with mock.patch.object( self.nova_notifier.nclient.server_external_events, 'create') as nclient_create: nclient_create.return_value = [{'code': 404, 'name': 'network-changed', 'server_uuid': device_id}] self.nova_notifier.send_events( [{'name': 'network-changed', 'server_uuid': device_id}]) def test_nova_send_events_return_200(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' with mock.patch.object( self.nova_notifier.nclient.server_external_events, 'create') as nclient_create: nclient_create.return_value = [{'code': 200, 'name': 'network-changed', 'server_uuid': device_id}] self.nova_notifier.send_events( [{'name': 'network-changed', 'server_uuid': device_id}]) def test_nova_send_events_multiple(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' with mock.patch.object( self.nova_notifier.nclient.server_external_events, 'create') as nclient_create: nclient_create.return_value = [{'code': 200, 'name': 'network-changed', 'server_uuid': device_id}, {'code': 200, 'name': 'network-changed', 'server_uuid': device_id}] self.nova_notifier.send_events([ {'name': 'network-changed', 'server_uuid': device_id}, {'name': 'network-changed', 'server_uuid': device_id}]) def test_reassociate_floatingip_without_disassociate_event(self): returned_obj = {'floatingip': {'port_id': 'f5348a16-609a-4971-b0f0-4b8def5235fb'}} original_obj = {'port_id': '5a39def4-3d3f-473d-9ff4-8e90064b9cc1'} self.nova_notifier._waiting_to_send = True self.nova_notifier.send_network_change( 'update_floatingip', original_obj, returned_obj) self.assertEqual( 2, len(self.nova_notifier.batch_notifier.pending_events)) returned_obj_non = {'floatingip': {'port_id': None}} event_dis = self.nova_notifier.create_port_changed_event( 'update_floatingip', original_obj, returned_obj_non) event_assoc = self.nova_notifier.create_port_changed_event( 'update_floatingip', original_obj, returned_obj) self.assertEqual( self.nova_notifier.batch_notifier.pending_events[0], event_dis) self.assertEqual( self.nova_notifier.batch_notifier.pending_events[1], event_assoc) def test_delete_port_notify(self): device_id = '32102d7b-1cf4-404d-b50a-97aae1f55f87' port_id = 'bee50827-bcee-4cc8-91c1-a27b0ce54222' returned_obj = {'port': {'device_owner': 'compute:dfd', 'id': port_id, 'device_id': device_id}} expected_event = {'server_uuid': device_id, 'name': nova.VIF_DELETED, 'tag': port_id} event = self.nova_notifier.create_port_changed_event('delete_port', {}, returned_obj) self.assertEqual(expected_event, event)
apache-2.0
Plain-Andy-legacy/android_external_chromium_org
chrome/common/extensions/docs/server2/test_data/api_data_source/canned_master_fs.py
78
5828
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json CANNED_MASTER_FS_DATA = { 'api': { '_api_features.json': json.dumps({ 'add_rules_tester': { 'dependencies': ['permission:add_rules_tester'] }, 'ref_test': { 'dependencies': ['permission:ref_test'] }, 'tester': { 'dependencies': ['permission:tester', 'manifest:tester'], 'contexts': ['content_script'] }, 'tester.test1': {'contexts': ['content_script']}, 'tester.test2': {} }), '_manifest_features.json': json.dumps({'tester': {}, 'ref_test': {}}), '_permission_features.json': json.dumps({ 'tester': {}, 'ref_test': {}, 'add_rules_tester': {} }), 'add_rules_tester.json': json.dumps([{ 'namespace': 'add_rules_tester', 'description': ('A test api with a couple of events which support or ' 'do not support rules.'), 'types': [], 'functions': [], 'events': [ { 'name': 'rules', 'options': { 'supportsRules': True, 'conditions': [], 'actions': [] } }, { 'name': 'noRules', 'type': 'function', 'description': 'Listeners can be registered with this event.', 'parameters': [] } ] }]), 'events.json': json.dumps([{ 'namespace': 'events', 'description': 'These are events.', 'types': [ { 'id': 'Event', 'type': 'object', 'description': 'An Event object.', 'functions': [ { 'name': 'addListener', 'type': 'function', 'description': 'Adds a listener.' } ], } ] }]), 'tester.json': json.dumps([{ 'namespace': 'tester', 'description': 'a test api', 'types': [ { 'id': 'TypeA', 'type': 'object', 'description': 'A cool thing.', 'properties': { 'a': {'nodoc': True, 'type': 'string', 'minimum': 0}, 'b': {'type': 'array', 'optional': True, 'items': {'$ref': 'TypeA'}, 'description': 'List of TypeA.'} } } ], 'functions': [ { 'name': 'get', 'type': 'function', 'description': 'Gets stuff.', 'parameters': [ { 'name': 'a', 'description': 'a param', 'choices': [ {'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}, 'minItems': 1} ] }, { 'type': 'function', 'name': 'callback', 'parameters': [ {'name': 'results', 'type': 'array', 'items': {'$ref': 'TypeA'}} ] } ] } ], 'events': [ { 'name': 'EventA', 'type': 'function', 'description': 'A cool event.', 'parameters': [ {'type': 'string', 'name': 'id'}, { '$ref': 'TypeA', 'name': 'bookmark' } ] } ] }]), 'ref_test.json': json.dumps([{ 'namespace': 'ref_test', 'description': 'An API for testing ref\'s', 'types': [ { 'id': 'type1', 'type': 'string', 'description': '$ref:type2' }, { 'id': 'type2', 'type': 'string', 'description': 'A $ref:type3, or $ref:type2' }, { 'id': 'type3', 'type': 'string', 'description': '$ref:other.type2 != $ref:ref_test.type2' } ], 'events': [ { 'name': 'event1', 'type': 'function', 'description': 'We like $ref:type1', 'parameters': [ { 'name': 'param1', 'type': 'string' } ] } ], 'properties': { 'prop1': { '$ref': 'type3' } }, 'functions': [ { 'name': 'func1', 'type': 'function', 'parameters': [ { 'name': 'param1', 'type': 'string' } ] } ] }]) }, 'docs': { 'templates': { 'intros': { 'test.html': '<h1>hi</h1>you<h2>first</h2><h3>inner</h3><h2>second</h2>' }, 'json': { 'api_availabilities.json': json.dumps({ 'master_api': { 'channel': 'master' }, 'dev_api': { 'channel': 'dev' }, 'beta_api': { 'channel': 'beta' }, 'stable_api': { 'channel': 'stable', 'version': 20 } }), 'intro_tables.json': json.dumps({ 'tester': { 'Permissions': [ { 'class': 'override', 'text': '"tester"' }, { 'text': 'is an API for testing things.' } ], 'Learn More': [ { 'link': 'https://tester.test.com/welcome.html', 'text': 'Welcome!' } ] } }), 'manifest.json': '{}', 'permissions.json': '{}' }, 'private': { 'intro_tables': { 'master_message.html': 'available on master', 'stable_message.html': 'Since {{content.version}}.', 'content_scripts.html': 'Content Scripts' } } } } }
bsd-3-clause
rspavel/spack
var/spack/repos/builtin/packages/r-kegggraph/package.py
5
1444
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RKegggraph(RPackage): """KEGGgraph: A graph approach to KEGG PATHWAY in R and Bioconductor. KEGGGraph is an interface between KEGG pathway and graph object as well as a collection of tools to analyze, dissect and visualize these graphs. It parses the regularly updated KGML (KEGG XML) files into graph models maintaining all essential pathway attributes. The package offers functionalities including parsing, graph operation, visualization and etc.""" homepage = "https://bioconductor.org/packages/KEGGgraph" git = "https://git.bioconductor.org/packages/KEGGgraph.git" version('1.44.0', commit='2c24e8ec53fe34c72ea65f34e3c09905ab2e5c62') version('1.42.0', commit='7d907e22a3ad7b4829a7cbaba5a8f8dc8013a609') version('1.40.0', commit='6351a1637276f71697b01a994ebda0d3d1cf6d7a') version('1.38.0', commit='72f102e2611e3966362cfaa43646a6e66dd2ba27') version('1.38.1', commit='dd31665beb36d5aad8ed09ed56c603633b6b2292') depends_on('r@2.10.0:', type=('build', 'run')) depends_on('r-xml@2.3-0:', type=('build', 'run')) depends_on('r-graph', type=('build', 'run')) depends_on('r-rcurl', when='@1.44.0:', type=('build', 'run'))
lgpl-2.1
timtim17/IntroToGameProg
Experiments/Splash Screen.py
1
3389
# Austin Jenchi # 2/5/2015 # 8th Period # Splash Screen import pygame from pygame import QUIT from pygame import KEYDOWN from Tkinter import Tk as getScreen pygame.init() # COLORS BG_COLOR = [255, 152, 0] FG_COLOR = [0, 0, 0] # IMAGES CHROME = pygame.image.load("chrome.png") chromeAngle = 0 chromeAngleInterval = 0.01 # FONTS SYSFONT = pygame.font.Font(None, 48) # WINDOW DONE = False FULLSCREEN = False CLOCK = pygame.time.Clock() SIZE = (700, 500) SCREEN = pygame.display.set_mode(SIZE, pygame.RESIZABLE) pygame.display.set_caption("Splash Screen") STAGE = 0 monitor = getScreen() counter = 0 # http://www.pygame.org/wiki/RotateCenter?parent=CookBook def rot_center(image, angle): """rotate an image while keeping its center and size""" orig_rect = image.get_rect() rot_image = pygame.transform.rotate(image, angle) rot_rect = orig_rect.copy() rot_rect.center = rot_image.get_rect().center rot_image = rot_image.subsurface(rot_rect).copy() return rot_image while not DONE: SCREEN.fill(BG_COLOR) if STAGE == 0 or STAGE == 1: text = SYSFONT.render("Aa Games", True, FG_COLOR) SCREEN.blit(text, [SCREEN.get_width() / 2 - text.get_width() // 2, SCREEN.get_height() / 2 - text.get_height() // 2]) elif STAGE == 2: SCREEN.blit(rot_center(CHROME, chromeAngle), [SCREEN.get_width() / 2 - CHROME.get_width() // 2, SCREEN.get_height() / 2 - CHROME.get_height() // 2]) chromeAngle += chromeAngleInterval if chromeAngleInterval <= 50: chromeAngleInterval += 0.1 pygame.display.flip() if STAGE == 0: counter += 1 if counter > 100: STAGE = 1 elif STAGE == 1: if BG_COLOR[0] < 224: BG_COLOR[0] += 1 elif BG_COLOR[0] > 224: BG_COLOR[0] -= 1 if BG_COLOR[1] < 224: BG_COLOR[1] += 1 elif BG_COLOR[1] > 224: BG_COLOR[1] -= 1 if BG_COLOR[2] < 224: BG_COLOR[2] += 1 elif BG_COLOR[2] > 224: BG_COLOR[2] -= 1 if FG_COLOR[0] < 224: FG_COLOR[0] += 1 elif FG_COLOR[0] > 224: FG_COLOR[0] -= 1 if FG_COLOR[1] < 224: FG_COLOR[1] += 1 elif FG_COLOR[1] > 224: FG_COLOR[1] -= 1 if FG_COLOR[2] < 224: FG_COLOR[2] += 1 elif FG_COLOR[2] > 224: FG_COLOR[2] -= 1 if BG_COLOR[0] == 224 and BG_COLOR[1] == 224 and BG_COLOR[2] == 224 and FG_COLOR[0] == 224 and FG_COLOR[1] == 224 and FG_COLOR[2] == 224: STAGE = 2 for event in pygame.event.get(): type = event.type if type == QUIT: DONE = True elif type == KEYDOWN: if event.key == 292: # F11 if not FULLSCREEN: screen = pygame.display.set_mode((monitor.winfo_screenwidth(), monitor.winfo_screenheight()), pygame.FULLSCREEN) FULLSCREEN = True else: SCREEN = pygame.display.set_mode(SIZE, pygame.RESIZABLE) FULLSCREEN = False elif event.key == 27: # Esc SCREEN = pygame.display.set_mode(SIZE, pygame.RESIZABLE) FULLSCREEN = False CLOCK.tick(60) pygame.quit()
gpl-2.0
c-amr/camr
stanfordnlp/pexpect/FSM.py
73
13419
#!/usr/bin/env python '''This module implements a Finite State Machine (FSM). In addition to state this FSM also maintains a user defined "memory". So this FSM can be used as a Push-down Automata (PDA) since a PDA is a FSM + memory. The following describes how the FSM works, but you will probably also need to see the example function to understand how the FSM is used in practice. You define an FSM by building tables of transitions. For a given input symbol the process() method uses these tables to decide what action to call and what the next state will be. The FSM has a table of transitions that associate: (input_symbol, current_state) --> (action, next_state) Where "action" is a function you define. The symbols and states can be any objects. You use the add_transition() and add_transition_list() methods to add to the transition table. The FSM also has a table of transitions that associate: (current_state) --> (action, next_state) You use the add_transition_any() method to add to this transition table. The FSM also has one default transition that is not associated with any specific input_symbol or state. You use the set_default_transition() method to set the default transition. When an action function is called it is passed a reference to the FSM. The action function may then access attributes of the FSM such as input_symbol, current_state, or "memory". The "memory" attribute can be any object that you want to pass along to the action functions. It is not used by the FSM itself. For parsing you would typically pass a list to be used as a stack. The processing sequence is as follows. The process() method is given an input_symbol to process. The FSM will search the table of transitions that associate: (input_symbol, current_state) --> (action, next_state) If the pair (input_symbol, current_state) is found then process() will call the associated action function and then set the current state to the next_state. If the FSM cannot find a match for (input_symbol, current_state) it will then search the table of transitions that associate: (current_state) --> (action, next_state) If the current_state is found then the process() method will call the associated action function and then set the current state to the next_state. Notice that this table lacks an input_symbol. It lets you define transitions for a current_state and ANY input_symbol. Hence, it is called the "any" table. Remember, it is always checked after first searching the table for a specific (input_symbol, current_state). For the case where the FSM did not match either of the previous two cases the FSM will try to use the default transition. If the default transition is defined then the process() method will call the associated action function and then set the current state to the next_state. This lets you define a default transition as a catch-all case. You can think of it as an exception handler. There can be only one default transition. Finally, if none of the previous cases are defined for an input_symbol and current_state then the FSM will raise an exception. This may be desirable, but you can always prevent this just by defining a default transition. Noah Spurrier 20020822 PEXPECT LICENSE This license is approved by the OSI and FSF as GPL-compatible. http://opensource.org/licenses/isc-license.txt Copyright (c) 2012, Noah Spurrier <noah@noah.org> PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ''' class ExceptionFSM(Exception): '''This is the FSM Exception class.''' def __init__(self, value): self.value = value def __str__(self): return 'ExceptionFSM: ' + str(self.value) class FSM: '''This is a Finite State Machine (FSM). ''' def __init__(self, initial_state, memory=None): '''This creates the FSM. You set the initial state here. The "memory" attribute is any object that you want to pass along to the action functions. It is not used by the FSM. For parsing you would typically pass a list to be used as a stack. ''' # Map (input_symbol, current_state) --> (action, next_state). self.state_transitions = {} # Map (current_state) --> (action, next_state). self.state_transitions_any = {} self.default_transition = None self.input_symbol = None self.initial_state = initial_state self.current_state = self.initial_state self.next_state = None self.action = None self.memory = memory def reset (self): '''This sets the current_state to the initial_state and sets input_symbol to None. The initial state was set by the constructor __init__(). ''' self.current_state = self.initial_state self.input_symbol = None def add_transition (self, input_symbol, state, action=None, next_state=None): '''This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. You can also set transitions for a list of symbols by using add_transition_list(). ''' if next_state is None: next_state = state self.state_transitions[(input_symbol, state)] = (action, next_state) def add_transition_list (self, list_input_symbols, state, action=None, next_state=None): '''This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state for input_symbol in list_input_symbols: self.add_transition (input_symbol, state, action, next_state) def add_transition_any (self, state, action=None, next_state=None): '''This adds a transition that associates: (current_state) --> (action, next_state) That is, any input symbol will match the current state. The process() method checks the "any" state associations after it first checks for an exact match of (input_symbol, current_state). The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state self.state_transitions_any [state] = (action, next_state) def set_default_transition (self, action, next_state): '''This sets the default transition. This defines an action and next_state if the FSM cannot find the input symbol and the current state in the transition list and if the FSM cannot find the current_state in the transition_any list. This is useful as a final fall-through state for catching errors and undefined states. The default transition can be removed by setting the attribute default_transition to None. ''' self.default_transition = (action, next_state) def get_transition (self, input_symbol, state): '''This returns (action, next state) given an input_symbol and state. This does not modify the FSM state, so calling this method has no side effects. Normally you do not call this method directly. It is called by process(). The sequence of steps to check for a defined transition goes from the most specific to the least specific. 1. Check state_transitions[] that match exactly the tuple, (input_symbol, state) 2. Check state_transitions_any[] that match (state) In other words, match a specific state and ANY input_symbol. 3. Check if the default_transition is defined. This catches any input_symbol and any state. This is a handler for errors, undefined states, or defaults. 4. No transition was defined. If we get here then raise an exception. ''' if (input_symbol, state) in self.state_transitions: return self.state_transitions[(input_symbol, state)] elif state in self.state_transitions_any: return self.state_transitions_any[state] elif self.default_transition is not None: return self.default_transition else: raise ExceptionFSM ('Transition is undefined: (%s, %s).' % (str(input_symbol), str(state)) ) def process (self, input_symbol): '''This is the main method that you call to process input. This may cause the FSM to change state and call an action. This method calls get_transition() to find the action and next_state associated with the input_symbol and current_state. If the action is None then the action is not called and only the current state is changed. This method processes one complete input symbol. You can process a list of symbols (or a string) by calling process_list(). ''' self.input_symbol = input_symbol (self.action, self.next_state) = self.get_transition (self.input_symbol, self.current_state) if self.action is not None: self.action (self) self.current_state = self.next_state self.next_state = None def process_list (self, input_symbols): '''This takes a list and sends each element to process(). The list may be a string or any iterable object. ''' for s in input_symbols: self.process (s) ############################################################################## # The following is an example that demonstrates the use of the FSM class to # process an RPN expression. Run this module from the command line. You will # get a prompt > for input. Enter an RPN Expression. Numbers may be integers. # Operators are * / + - Use the = sign to evaluate and print the expression. # For example: # # 167 3 2 2 * * * 1 - = # # will print: # # 2003 ############################################################################## import sys import string PY3 = (sys.version_info[0] >= 3) # # These define the actions. # Note that "memory" is a list being used as a stack. # def BeginBuildNumber (fsm): fsm.memory.append (fsm.input_symbol) def BuildNumber (fsm): s = fsm.memory.pop () s = s + fsm.input_symbol fsm.memory.append (s) def EndBuildNumber (fsm): s = fsm.memory.pop () fsm.memory.append (int(s)) def DoOperator (fsm): ar = fsm.memory.pop() al = fsm.memory.pop() if fsm.input_symbol == '+': fsm.memory.append (al + ar) elif fsm.input_symbol == '-': fsm.memory.append (al - ar) elif fsm.input_symbol == '*': fsm.memory.append (al * ar) elif fsm.input_symbol == '/': fsm.memory.append (al / ar) def DoEqual (fsm): print(str(fsm.memory.pop())) def Error (fsm): print('That does not compute.') print(str(fsm.input_symbol)) def main(): '''This is where the example starts and the FSM state transitions are defined. Note that states are strings (such as 'INIT'). This is not necessary, but it makes the example easier to read. ''' f = FSM ('INIT', []) f.set_default_transition (Error, 'INIT') f.add_transition_any ('INIT', None, 'INIT') f.add_transition ('=', 'INIT', DoEqual, 'INIT') f.add_transition_list (string.digits, 'INIT', BeginBuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.digits, 'BUILDING_NUMBER', BuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.whitespace, 'BUILDING_NUMBER', EndBuildNumber, 'INIT') f.add_transition_list ('+-*/', 'INIT', DoOperator, 'INIT') print() print('Enter an RPN Expression.') print('Numbers may be integers. Operators are * / + -') print('Use the = sign to evaluate and print the expression.') print('For example: ') print(' 167 3 2 2 * * * 1 - =') inputstr = (input if PY3 else raw_input)('> ') # analysis:ignore f.process_list(inputstr) if __name__ == '__main__': main()
gpl-2.0
congthuc/androguard-2.0-custom
androguard/decompiler/dad/ast.py
20
23793
# This file is part of Androguard. # # Copyright (C) 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''This file is a simplified version of writer.py that outputs an AST instead of source code.''' import struct from androguard.decompiler.dad import basic_blocks, instruction, opcode_ins def array_access(arr, ind): return ['ArrayAccess', [arr, ind]] def array_creation(tn, params, dim): return ['ArrayCreation', [tn] + params, dim] def array_initializer(params, tn=None): return ['ArrayInitializer', params, tn] def assignment(lhs, rhs, op=''): return ['Assignment', [lhs, rhs], op] def binary_infix(op, left, right): return ['BinaryInfix', [left, right], op] def cast(tn, arg): return ['Cast', [tn, arg]] def field_access(triple, left): return ['FieldAccess', [left], triple] def literal(result, tt): return ['Literal', result, tt] def local(name): return ['Local', name] def method_invocation(triple, name, base, params): if base is None: return ['MethodInvocation', params, triple, name, False] return ['MethodInvocation', [base]+params, triple, name, True] def parenthesis(expr): return ['Parenthesis', [expr]] def typen(baset, dim): return ['TypeName', (baset, dim)] def unary_prefix(op, left): return ['Unary', [left], op, False] def unary_postfix(left, op): return ['Unary', [left], op, True] def var_decl(typen, var): return [typen, var] def dummy(*args): return ['Dummy', args] ################################################################################ def expression_stmt(expr): return ['ExpressionStatement', expr] def local_decl_stmt(expr, decl): return ['LocalDeclarationStatement', expr, decl] def return_stmt(expr): return ['ReturnStatement', expr] def throw_stmt(expr): return ['ThrowStatement', expr] def jump_stmt(keyword): return ['JumpStatement', keyword, None] def loop_stmt(isdo, cond_expr, body): type_ = 'DoStatement' if isdo else 'WhileStatement' return [type_, None, cond_expr, body] def try_stmt(tryb, pairs): return ['TryStatement', None, tryb, pairs] def if_stmt(cond_expr, scopes): return ['IfStatement', None, cond_expr, scopes] def switch_stmt(cond_expr, ksv_pairs): return ['SwitchStatement', None, cond_expr, ksv_pairs] # Create empty statement block (statements to be appended later) # Note, the code below assumes this can be modified in place def statement_block(): return ['BlockStatement', None, []] # Add a statement to the end of a statement block def _append(sb, stmt): assert(sb[0] == 'BlockStatement') if stmt is not None: sb[2].append(stmt) ################################################################################ TYPE_DESCRIPTOR = { 'V': 'void', 'Z': 'boolean', 'B': 'byte', 'S': 'short', 'C': 'char', 'I': 'int', 'J': 'long', 'F': 'float', 'D': 'double', } def parse_descriptor(desc): dim = 0 while desc and desc[0] == '[': desc = desc[1:] dim += 1 if desc in TYPE_DESCRIPTOR: return typen('.'+TYPE_DESCRIPTOR[desc], dim) if desc and desc[0] == 'L' and desc[-1] == ';': return typen(desc[1:-1], dim) # invalid descriptor (probably None) return dummy(str(desc)) # Note: the literal_foo functions (and dummy) are also imported by decompile.py def literal_string(s): escapes = { '\0':'\\0', '\t':'\\t', '\r':'\\r', '\n':'\\n', '"':'\\"', '\\':'\\\\' } buf = ['"'] for c in s.decode('utf8'): if c in escapes: buf.append(escapes[c]) elif ' ' <= c < '\x7f': buf.append(c) else: buf.append('\u{:04x}'.format(ord(c))) buf.append('"') return literal(''.join(buf), ('java/lang/String', 0)) def literal_class(desc): return literal(parse_descriptor(desc), ('java/lang/Class', 0)) def literal_bool(b): return literal(str(b).lower(), ('.boolean', 0)) def literal_int(b): return literal(str(b), ('.int', 0)) def literal_hex_int(b): return literal(hex(b), ('.int', 0)) def literal_long(b): return literal(str(b)+'L', ('.long', 0)) def literal_float(f): return literal(str(f)+'f', ('.float', 0)) def literal_double(f): return literal(str(f), ('.double', 0)) def literal_null(): return literal('null', ('.null', 0)) def visit_decl(var, init_expr=None): t = parse_descriptor(var.get_type()) v = local('v{}'.format(var.name)) return local_decl_stmt(init_expr, var_decl(t, v)) def visit_arr_data(value): data = value.get_data() tab = [] elem_size = value.element_width if elem_size == 4: for i in range(0, value.size * 4, 4): tab.append(struct.unpack('<i', data[i:i + 4])[0]) else: # FIXME: other cases for i in range(value.size): tab.append(struct.unpack('<b', data[i])[0]) return array_initializer(map(literal_int, tab)) def write_inplace_if_possible(lhs, rhs): if isinstance(rhs, instruction.BinaryExpression) and lhs == rhs.var_map[rhs.arg1]: exp_rhs = rhs.var_map[rhs.arg2] # post increment/decrement if rhs.op in '+-' and isinstance(exp_rhs, instruction.Constant) and exp_rhs.get_int_value() == 1: return unary_postfix(visit_expr(lhs), rhs.op * 2) # compound assignment return assignment(visit_expr(lhs), visit_expr(exp_rhs), op=rhs.op) return assignment(visit_expr(lhs), visit_expr(rhs)) def visit_expr(op): if isinstance(op, instruction.ArrayLengthExpression): expr = visit_expr(op.var_map[op.array]) return field_access([None, 'length', None], expr) if isinstance(op, instruction.ArrayLoadExpression): array_expr = visit_expr(op.var_map[op.array]) index_expr = visit_expr(op.var_map[op.idx]) return array_access(array_expr, index_expr) if isinstance(op, instruction.ArrayStoreInstruction): array_expr = visit_expr(op.var_map[op.array]) index_expr = visit_expr(op.var_map[op.index]) rhs = visit_expr(op.var_map[op.rhs]) return assignment(array_access(array_expr, index_expr), rhs) if isinstance(op, instruction.AssignExpression): lhs = op.var_map.get(op.lhs) rhs = op.rhs if lhs is None: return visit_expr(rhs) return write_inplace_if_possible(lhs, rhs) if isinstance(op, instruction.BaseClass): if op.clsdesc is None: assert(op.cls == "super") return local(op.cls) return parse_descriptor(op.clsdesc) if isinstance(op, instruction.BinaryExpression): lhs = op.var_map.get(op.arg1) rhs = op.var_map.get(op.arg2) expr = binary_infix(op.op, visit_expr(lhs), visit_expr(rhs)) if not isinstance(op, instruction.BinaryCompExpression): expr = parenthesis(expr) return expr if isinstance(op, instruction.CheckCastExpression): lhs = op.var_map.get(op.arg) return parenthesis(cast(parse_descriptor(op.clsdesc), visit_expr(lhs))) if isinstance(op, instruction.ConditionalExpression): lhs = op.var_map.get(op.arg1) rhs = op.var_map.get(op.arg2) return binary_infix(op.op, visit_expr(lhs), visit_expr(rhs)) if isinstance(op, instruction.ConditionalZExpression): arg = op.var_map[op.arg] if isinstance(arg, instruction.BinaryCompExpression): arg.op = op.op return visit_expr(arg) expr = visit_expr(arg) atype = arg.get_type() if atype == 'Z': if op.op == opcode_ins.Op.EQUAL: expr = unary_prefix('!', expr) elif atype in 'VBSCIJFD': expr = binary_infix(op.op, expr, literal_int(0)) else: expr = binary_infix(op.op, expr, literal_null()) return expr if isinstance(op, instruction.Constant): if op.type == 'Ljava/lang/String;': return literal_string(op.cst) elif op.type == 'Z': return literal_bool(op.cst == 0) elif op.type in 'ISCB': return literal_int(op.cst2) elif op.type in 'J': return literal_long(op.cst2) elif op.type in 'F': return literal_float(op.cst) elif op.type in 'D': return literal_double(op.cst) elif op.type == 'Ljava/lang/Class;': return literal_class(op.clsdesc) return dummy('???') if isinstance(op, instruction.FillArrayExpression): array_expr = visit_expr(op.var_map[op.reg]) rhs = visit_arr_data(op.value) return assignment(array_expr, rhs) if isinstance(op, instruction.FilledArrayExpression): tn = parse_descriptor(op.type) params = [visit_expr(op.var_map[x]) for x in op.args] return array_initializer(params, tn) if isinstance(op, instruction.InstanceExpression): triple = op.clsdesc[1:-1], op.name, op.ftype expr = visit_expr(op.var_map[op.arg]) return field_access(triple, expr) if isinstance(op, instruction.InstanceInstruction): triple = op.clsdesc[1:-1], op.name, op.atype lhs = field_access(triple, visit_expr(op.var_map[op.lhs])) rhs = visit_expr(op.var_map[op.rhs]) return assignment(lhs, rhs) if isinstance(op, instruction.InvokeInstruction): base = op.var_map[op.base] params = [op.var_map[arg] for arg in op.args] params = map(visit_expr, params) if op.name == '<init>': if isinstance(base, instruction.ThisParam): return method_invocation(op.triple, 'this', None, params) elif isinstance(base, instruction.NewInstance): return ['ClassInstanceCreation', params, parse_descriptor(base.type)] else: assert(isinstance(base, instruction.Variable)) # fallthrough to create dummy <init> call return method_invocation(op.triple, op.name, visit_expr(base), params) # for unmatched monitor instructions, just create dummy expressions if isinstance(op, instruction.MonitorEnterExpression): return dummy("monitor enter(", visit_expr(op.var_map[op.ref]), ")") if isinstance(op, instruction.MonitorExitExpression): return dummy("monitor exit(", visit_expr(op.var_map[op.ref]), ")") if isinstance(op, instruction.MoveExpression): lhs = op.var_map.get(op.lhs) rhs = op.var_map.get(op.rhs) return write_inplace_if_possible(lhs, rhs) if isinstance(op, instruction.MoveResultExpression): lhs = op.var_map.get(op.lhs) rhs = op.var_map.get(op.rhs) return assignment(visit_expr(lhs), visit_expr(rhs)) if isinstance(op, instruction.NewArrayExpression): tn = parse_descriptor(op.type[1:]) expr = visit_expr(op.var_map[op.size]) return array_creation(tn, [expr], 1) # create dummy expression for unmatched newinstance if isinstance(op, instruction.NewInstance): return dummy("new ", parse_descriptor(op.type)) if isinstance(op, instruction.Param): if isinstance(op, instruction.ThisParam): return local('this') return local('p{}'.format(op.v)) if isinstance(op, instruction.StaticExpression): triple = op.clsdesc[1:-1], op.name, op.ftype return field_access(triple, parse_descriptor(op.clsdesc)) if isinstance(op, instruction.StaticInstruction): triple = op.clsdesc[1:-1], op.name, op.ftype lhs = field_access(triple, parse_descriptor(op.clsdesc)) rhs = visit_expr(op.var_map[op.rhs]) return assignment(lhs, rhs) if isinstance(op, instruction.SwitchExpression): return visit_expr(op.var_map[op.src]) if isinstance(op, instruction.UnaryExpression): lhs = op.var_map.get(op.arg) if isinstance(op, instruction.CastExpression): expr = cast(parse_descriptor(op.clsdesc), visit_expr(lhs)) else: expr = unary_prefix(op.op, visit_expr(lhs)) return parenthesis(expr) if isinstance(op, instruction.Variable): # assert(op.declared) return local('v{}'.format(op.name)) return dummy('???') def visit_ins(op, isCtor=False): if isinstance(op, instruction.ReturnInstruction): expr = None if op.arg is None else visit_expr(op.var_map[op.arg]) return return_stmt(expr) elif isinstance(op, instruction.ThrowExpression): return throw_stmt(visit_expr(op.var_map[op.ref])) elif isinstance(op, instruction.NopExpression): return None # Local var decl statements if isinstance(op, (instruction.AssignExpression, instruction.MoveExpression, instruction.MoveResultExpression)): lhs = op.var_map.get(op.lhs) rhs = op.rhs if isinstance(op, instruction.AssignExpression) else op.var_map.get(op.rhs) if isinstance(lhs, instruction.Variable) and not lhs.declared: lhs.declared = True expr = visit_expr(rhs) return visit_decl(lhs, expr) # skip this() at top of constructors if isCtor and isinstance(op, instruction.AssignExpression): op2 = op.rhs if op.lhs is None and isinstance(op2, instruction.InvokeInstruction): if op2.name == '<init>' and len(op2.args) == 0: if isinstance(op2.var_map[op2.base], instruction.ThisParam): return None # MoveExpression is skipped when lhs = rhs if isinstance(op, instruction.MoveExpression): if op.var_map.get(op.lhs) is op.var_map.get(op.rhs): return None return expression_stmt(visit_expr(op)) class JSONWriter(object): def __init__(self, graph, method): self.graph = graph self.method = method self.visited_nodes = set() self.loop_follow = [None] self.if_follow = [None] self.switch_follow = [None] self.latch_node = [None] self.try_follow = [None] self.next_case = None self.need_break = True self.constructor = False self.context = [] # This class is created as a context manager so that it can be used like # with self as foo: # ... # which pushes a statement block on to the context stack and assigns it to foo # within the with block, all added instructions will be added to foo def __enter__(self): self.context.append(statement_block()) return self.context[-1] def __exit__(self, *args): self.context.pop() return False # Add a statement to the current context def add(self, val): _append(self.context[-1], val) def visit_ins(self, op): self.add(visit_ins(op, isCtor=self.constructor)) # Note: this is a mutating operation def get_ast(self): m = self.method flags = m.access if 'constructor' in flags: flags.remove('constructor') self.constructor = True params = m.lparams[:] if 'static' not in m.access: params = params[1:] # DAD doesn't create any params for abstract methods if len(params) != len(m.params_type): assert('abstract' in flags or 'native' in flags) assert(not params) params = range(len(m.params_type)) paramdecls = [] for ptype, name in zip(m.params_type, params): t = parse_descriptor(ptype) v = local('p{}'.format(name)) paramdecls.append(var_decl(t, v)) if self.graph is None: body = None else: with self as body: self.visit_node(self.graph.entry) return { 'triple': m.triple, 'flags': flags, 'ret': parse_descriptor(m.type), 'params': paramdecls, 'comments': [], 'body': body, } def _visit_condition(self, cond): if cond.isnot: cond.cond1.neg() left = parenthesis(self.get_cond(cond.cond1)) right = parenthesis(self.get_cond(cond.cond2)) op = '&&' if cond.isand else '||' res = binary_infix(op, left, right) return res def get_cond(self, node): if isinstance(node, basic_blocks.ShortCircuitBlock): return self._visit_condition(node.cond) elif isinstance(node, basic_blocks.LoopBlock): return self.get_cond(node.cond) else: assert(type(node) == basic_blocks.CondBlock) assert(len(node.ins) == 1) return visit_expr(node.ins[-1]) def visit_node(self, node): if node in (self.if_follow[-1], self.switch_follow[-1], self.loop_follow[-1], self.latch_node[-1], self.try_follow[-1]): return if not node.type.is_return and node in self.visited_nodes: return self.visited_nodes.add(node) for var in node.var_to_declare: if not var.declared: self.add(visit_decl(var)) var.declared = True node.visit(self) def visit_loop_node(self, loop): isDo = cond_expr = body = None follow = loop.follow['loop'] if loop.looptype.is_pretest: if loop.true is follow: loop.neg() loop.true, loop.false = loop.false, loop.true isDo = False cond_expr = self.get_cond(loop) elif loop.looptype.is_posttest: isDo = True self.latch_node.append(loop.latch) elif loop.looptype.is_endless: isDo = False cond_expr = literal_bool(True) with self as body: self.loop_follow.append(follow) if loop.looptype.is_pretest: self.visit_node(loop.true) else: self.visit_node(loop.cond) self.loop_follow.pop() if loop.looptype.is_pretest: pass elif loop.looptype.is_posttest: self.latch_node.pop() cond_expr = self.get_cond(loop.latch) else: self.visit_node(loop.latch) assert(cond_expr is not None and isDo is not None) self.add(loop_stmt(isDo, cond_expr, body)) if follow is not None: self.visit_node(follow) def visit_cond_node(self, cond): cond_expr = None scopes = [] follow = cond.follow['if'] if cond.false is cond.true: self.add(expression_stmt(self.get_cond(cond))) self.visit_node(cond.true) return if cond.false is self.loop_follow[-1]: cond.neg() cond.true, cond.false = cond.false, cond.true if self.loop_follow[-1] in (cond.true, cond.false): cond_expr = self.get_cond(cond) with self as scope: self.add(jump_stmt('break')) scopes.append(scope) with self as scope: self.visit_node(cond.false) scopes.append(scope) self.add(if_stmt(cond_expr, scopes)) elif follow is not None: if cond.true in (follow, self.next_case) or\ cond.num > cond.true.num: # or cond.true.num > cond.false.num: cond.neg() cond.true, cond.false = cond.false, cond.true self.if_follow.append(follow) if cond.true: # in self.visited_nodes: cond_expr = self.get_cond(cond) with self as scope: self.visit_node(cond.true) scopes.append(scope) is_else = not (follow in (cond.true, cond.false)) if is_else and not cond.false in self.visited_nodes: with self as scope: self.visit_node(cond.false) scopes.append(scope) self.if_follow.pop() self.add(if_stmt(cond_expr, scopes)) self.visit_node(follow) else: cond_expr = self.get_cond(cond) with self as scope: self.visit_node(cond.true) scopes.append(scope) with self as scope: self.visit_node(cond.false) scopes.append(scope) self.add(if_stmt(cond_expr, scopes)) def visit_switch_node(self, switch): lins = switch.get_ins() for ins in lins[:-1]: self.visit_ins(ins) switch_ins = switch.get_ins()[-1] cond_expr = visit_expr(switch_ins) ksv_pairs = [] follow = switch.follow['switch'] cases = switch.cases self.switch_follow.append(follow) default = switch.default for i, node in enumerate(cases): if node in self.visited_nodes: continue cur_ks = switch.node_to_case[node][:] if i + 1 < len(cases): self.next_case = cases[i + 1] else: self.next_case = None if node is default: cur_ks.append(None) default = None with self as body: self.visit_node(node) if self.need_break: self.add(jump_stmt('break')) else: self.need_break = True ksv_pairs.append((cur_ks, body)) if default not in (None, follow): with self as body: self.visit_node(default) ksv_pairs.append(([None], body)) self.add(switch_stmt(cond_expr, ksv_pairs)) self.switch_follow.pop() self.visit_node(follow) def visit_statement_node(self, stmt): sucs = self.graph.sucs(stmt) for ins in stmt.get_ins(): self.visit_ins(ins) if len(sucs) == 1: if sucs[0] is self.loop_follow[-1]: self.add(jump_stmt('break')) elif sucs[0] is self.next_case: self.need_break = False else: self.visit_node(sucs[0]) def visit_try_node(self, try_node): with self as tryb: self.try_follow.append(try_node.follow) self.visit_node(try_node.try_start) pairs = [] for catch_node in try_node.catch: if catch_node.exception_ins: ins = catch_node.exception_ins assert(isinstance(ins, instruction.MoveExceptionExpression)) var = ins.var_map[ins.ref] var.declared = True ctype = var.get_type() name = 'v{}'.format(var.name) else: ctype = catch_node.catch_type name = '_' catch_decl = var_decl(parse_descriptor(ctype), local(name)) with self as body: self.visit_node(catch_node.catch_start) pairs.append((catch_decl, body)) self.add(try_stmt(tryb, pairs)) self.visit_node(self.try_follow.pop()) def visit_return_node(self, ret): self.need_break = False for ins in ret.get_ins(): self.visit_ins(ins) def visit_throw_node(self, throw): for ins in throw.get_ins(): self.visit_ins(ins)
apache-2.0
ychen820/microblog
y/google-cloud-sdk/.install/.backup/platform/gsutil/gslib/command_argument.py
31
3698
# -*- coding: utf-8 -*- # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains classes related to argparse-based argument parsing.""" from tab_complete import CompleterType class CommandArgument(object): """Argparse style argument.""" def __init__(self, *args, **kwargs): """Constructs an argparse argument with the given data. See add_argument in argparse for description of the options. The only deviation from the argparse arguments is the 'completer' parameter. If 'completer' is present, it's used as the argcomplete completer for the argument. Args: *args: Position args to pass to argparse add_argument **kwargs: Named args to pass to argparse add_argument """ completer = None if 'completer' in kwargs: completer = kwargs['completer'] del kwargs['completer'] self.args = args self.kwargs = kwargs self.completer = completer @staticmethod def MakeZeroOrMoreCloudURLsArgument(): """Constructs an argument that takes 0 or more Cloud URLs as parameters.""" return CommandArgument( 'file', nargs='*', completer=CompleterType.CLOUD_OBJECT) @staticmethod def MakeZeroOrMoreCloudBucketURLsArgument(): """Constructs an argument that takes 0+ Cloud bucket URLs as parameters.""" return CommandArgument( 'file', nargs='*', completer=CompleterType.CLOUD_BUCKET) @staticmethod def MakeNCloudBucketURLsArgument(n): """Constructs an argument that takes N Cloud bucket URLs as parameters.""" return CommandArgument( 'file', nargs=n, completer=CompleterType.CLOUD_BUCKET) @staticmethod def MakeNCloudURLsArgument(n): """Constructs an argument that takes N Cloud URLs as parameters.""" return CommandArgument( 'file', nargs=n, completer=CompleterType.CLOUD_OBJECT) @staticmethod def MakeZeroOrMoreCloudOrFileURLsArgument(): """Constructs an argument that takes 0 or more Cloud or File URLs.""" return CommandArgument( 'file', nargs='*', completer=CompleterType.CLOUD_OR_LOCAL_OBJECT) @staticmethod def MakeNCloudOrFileURLsArgument(n): """Constructs an argument that takes N Cloud or File URLs as parameters.""" return CommandArgument( 'file', nargs=n, completer=CompleterType.CLOUD_OR_LOCAL_OBJECT) @staticmethod def MakeZeroOrMoreFileURLsArgument(): """Constructs an argument that takes 0 or more File URLs as parameters.""" return CommandArgument( 'file', nargs='*', completer=CompleterType.LOCAL_OBJECT) @staticmethod def MakeNFileURLsArgument(n): """Constructs an argument that takes N File URLs as parameters.""" return CommandArgument( 'file', nargs=n, completer=CompleterType.LOCAL_OBJECT) @staticmethod def MakeFileURLOrCannedACLArgument(): """Constructs an argument that takes a File URL or a canned ACL.""" return CommandArgument( 'file', nargs=1, completer=CompleterType.LOCAL_OBJECT_OR_CANNED_ACL) @staticmethod def MakeFreeTextArgument(): """Constructs an argument that takes arbitrary text.""" return CommandArgument('text', completer=CompleterType.NO_OP)
bsd-3-clause
jinnykoo/wuyisj
src/oscar/apps/dashboard/promotions/forms.py
6
2749
from django import forms from django.conf import settings from django.forms.models import inlineformset_factory from django.utils.translation import ugettext_lazy as _ from oscar.apps.promotions.conf import PROMOTION_CLASSES from oscar.forms.fields import ExtendedURLField from oscar.core.loading import get_classes, get_class HandPickedProductList, RawHTML, SingleProduct, PagePromotion, OrderedProduct \ = get_classes('promotions.models', ['HandPickedProductList', 'RawHTML', 'SingleProduct', 'PagePromotion', 'OrderedProduct']) ProductSelect = get_class('dashboard.catalogue.widgets', 'ProductSelect') class PromotionTypeSelectForm(forms.Form): choices = [] for klass in PROMOTION_CLASSES: choices.append((klass.classname(), klass._meta.verbose_name)) promotion_type = forms.ChoiceField(choices=tuple(choices), label=_("Promotion type")) class RawHTMLForm(forms.ModelForm): class Meta: model = RawHTML exclude = ('display_type',) def __init__(self, *args, **kwargs): super(RawHTMLForm, self).__init__(*args, **kwargs) self.fields['body'].widget.attrs['class'] = "no-widget-init" class SingleProductForm(forms.ModelForm): class Meta: model = SingleProduct fields = ['name', 'product', 'description'] widgets = {'product': ProductSelect} class HandPickedProductListForm(forms.ModelForm): class Meta: model = HandPickedProductList exclude = ('products',) class OrderedProductForm(forms.ModelForm): class Meta: model = OrderedProduct fields = ['list', 'product', 'display_order'] widgets = { 'product': ProductSelect, } OrderedProductFormSet = inlineformset_factory( HandPickedProductList, OrderedProduct, form=OrderedProductForm, extra=2) class PagePromotionForm(forms.ModelForm): page_url = ExtendedURLField(label=_("URL"), verify_exists=True) position = forms.CharField( widget=forms.Select(choices=settings.OSCAR_PROMOTION_POSITIONS), label=_("Position"), help_text=_("Where in the page this content block will appear")) class Meta: model = PagePromotion exclude = ('display_order', 'clicks', 'content_type', 'object_id') def clean_page_url(self): page_url = self.cleaned_data.get('page_url') if not page_url: return page_url if page_url.startswith('http'): raise forms.ValidationError( _("Content blocks can only be linked to internal URLs")) if page_url.startswith('/') and not page_url.endswith('/'): page_url += '/' return page_url
bsd-3-clause
rbaindourov/v8-inspector
Source/chrome/tools/cr/cr/commands/install.py
113
1206
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A module for the install command.""" import cr class InstallCommand(cr.Command): """The implementation of the install command. This first uses Builder.Build to bring the target up to date, and then installs it using Installer.Reinstall. The builder installs its command line arguments, and you can use those to select which builder is used. Selecting the skip builder (using --builder=skip) bypasses the build stage. """ def __init__(self): super(InstallCommand, self).__init__() self.help = 'Install a binary' def AddArguments(self, subparsers): parser = super(InstallCommand, self).AddArguments(subparsers) cr.Builder.AddArguments(self, parser) cr.Installer.AddArguments(self, parser) cr.Target.AddArguments(self, parser, allow_multiple=True) self.ConsumeArgs(parser, 'the installer') return parser def Run(self): targets = cr.Target.GetTargets() if not cr.Installer.Skipping(): cr.Builder.Build(targets, []) cr.Installer.Reinstall(targets, cr.context.remains)
bsd-3-clause
13-1-kae/solar_project
solar_objects.py
9
1827
# coding: utf-8 # license: GPLv3 class Star: """Тип данных, описывающий звезду. Содержит массу, координаты, скорость звезды, а также визуальный радиус звезды в пикселах и её цвет. """ type = "star" """Признак объекта звезды""" m = 0 """Масса звезды""" x = 0 """Координата по оси **x**""" y = 0 """Координата по оси **y**""" Vx = 0 """Скорость по оси **x**""" Vy = 0 """Скорость по оси **y**""" Fx = 0 """Сила по оси **x**""" Fy = 0 """Сила по оси **y**""" R = 5 """Радиус звезды""" color = "red" """Цвет звезды""" image = None """Изображение звезды""" class Planet: """Тип данных, описывающий планету. Содержит массу, координаты, скорость планеты, а также визуальный радиус планеты в пикселах и её цвет """ type = "planet" """Признак объекта планеты""" m = 0 """Масса планеты""" x = 0 """Координата по оси **x**""" y = 0 """Координата по оси **y**""" Vx = 0 """Скорость по оси **x**""" Vy = 0 """Скорость по оси **y**""" Fx = 0 """Сила по оси **x**""" Fy = 0 """Сила по оси **y**""" R = 5 """Радиус планеты""" color = "green" """Цвет планеты""" image = None """Изображение планеты"""
gpl-3.0
carvalhomb/tsmells
guess/guess-src/Lib/xml/sax/drivers2/drv_xmlproc.py
2
12993
""" A SAX 2.0 driver for xmlproc. $Id: drv_xmlproc.py,v 1.1 2005/10/05 20:19:38 eytanadar Exp $ """ import types, string from xml.parsers.xmlproc import xmlproc, xmlval, xmlapp from xml.sax import saxlib from xml.sax.xmlreader import AttributesImpl, AttributesNSImpl from xml.sax.saxutils import ContentGenerator, prepare_input_source # Todo # - EntityResolver # - as much as possible of LexicalHandler # - entity expansion features # - core properties # - extra properties/features # - element stack # - entity stack # - current error code # - byte offset # - DTD object # - catalog path # - use catalogs # - regression test # - methods from Python SAX extensions? # - remove FIXMEs class XmlprocDriver(saxlib.XMLReader): # ===== SAX 2.0 INTERFACES # --- XMLReader methods def __init__(self): saxlib.XMLReader.__init__(self) self.__parsing = 0 self.__validate = 0 self.__namespaces = 1 self.__locator = 0 self._lex_handler = saxlib.LexicalHandler() self._decl_handler = saxlib.DeclHandler() def parse(self, source): try: self.__parsing = 1 # interpret source source = prepare_input_source(source) # create parser if self.__validate: parser = xmlval.XMLValidator() else: parser = xmlproc.XMLProcessor() # set handlers if self._cont_handler != None or self._lex_handler != None: if self._cont_handler == None: self._cont_handler = saxlib.ContentHandler() if self._lex_handler == None: self._lex_handler = saxlib.LexicalHandler() if self.__namespaces: filter = NamespaceFilter(parser, self._cont_handler, self._lex_handler, self) parser.set_application(filter) else: parser.set_application(self) if self._err_handler != None: parser.set_error_handler(self) if self._decl_handler != None or self._dtd_handler != None: parser.set_dtd_listener(self) # FIXME: set other handlers bufsize=16384 self._parser = parser # make it available for callbacks #parser.parse_resource(source.getSystemId()) # FIXME: rest! parser.set_sysid(source.getSystemId()) parser.read_from(source.getByteStream(), bufsize) source.getByteStream().close() parser.flush() parser.parseEnd() finally: self._parser = None self.__parsing = 0 def setLocale(self, locale): pass def getFeature(self, name): if name == saxlib.feature_string_interning or \ name == saxlib.feature_external_ges or \ name == saxlib.feature_external_pes: return 1 elif name == saxlib.feature_validation: return self.__validate elif name == saxlib.feature_namespaces: return self.__namespaces else: raise saxlib.SAXNotRecognizedException("Feature '%s' not recognized" % name) def setFeature(self, name, state): if self.__parsing: raise saxlib.SAXNotSupportedException("Cannot set feature '%s' during parsing" % name) if name == saxlib.feature_string_interning: pass elif name == saxlib.feature_validation: self.__validate = state elif name == saxlib.feature_namespaces: self.__namespaces = state elif name == saxlib.feature_external_ges or \ name == saxlib.feature_external_pes: if not state: raise saxlib.SAXNotSupportedException("This feature cannot be turned off with xmlproc.") else: raise saxlib.SAXNotRecognizedException("Feature '%s' not recognized" % name) def getProperty(self, name): if name == saxlib.property_lexical_handler: return self._lex_handler elif name == saxlib.property_declaration_handler: return self._decl_handler raise saxlib.SAXNotRecognizedException("Property '%s' not recognized" % name) def setProperty(self, name, value): if name == saxlib.property_lexical_handler: self._lex_handler = value elif name == saxlib.property_declaration_handler: self._decl_handler = value else: raise saxlib.SAXNotRecognizedException("Property '%s' not recognized" % name) # --- Locator methods def getColumnNumber(self): return self._parser.get_column() def getLineNumber(self): return self._parser.get_line() def getPublicId(self): return None # FIXME: Try to find this. Perhaps from InputSource? def getSystemId(self): return self._parser.get_current_sysid() # FIXME? # ===== XMLPROC INTERFACES # --- Application methods def set_locator(self, locator): self._locator = locator def doc_start(self): self._cont_handler.startDocument() def doc_end(self): self._cont_handler.endDocument() def handle_comment(self, data): self._lex_handler.comment(data) def handle_start_tag(self, name, attrs): self._cont_handler.startElement(name, AttributesImpl(attrs)) def handle_end_tag(self,name): self._cont_handler.endElement(name) def handle_data(self, data, start, end): self._cont_handler.characters(data[start:end]) def handle_ignorable_data(self, data, start, end): self._cont_handler.ignorableWhitespace(data[start:end]) def handle_pi(self, target, data): self._cont_handler.processingInstruction(target, data) def handle_doctype(self, root, pubId, sysId): self._lex_handler.startDTD(root, pubId, sysId) def set_entity_info(self, xmlver, enc, sddecl): pass # --- ErrorHandler methods # set_locator implemented as Application method above def get_locator(self): return self._locator def warning(self, msg): self._err_handler.warning(saxlib.SAXParseException(msg, None, self)) def error(self, msg): self._err_handler.error(saxlib.SAXParseException(msg, None, self)) def fatal(self, msg): self._err_handler.fatalError(saxlib.SAXParseException(msg, None, self)) # --- DTDConsumer methods def dtd_start(self): pass # this is done by handle_doctype def dtd_end(self): self._lex_handler.endDTD() def handle_comment(self, contents): self._lex_handler.comment(contents) def handle_pi(self, target, rem): self._cont_handler.processingInstruction(target, rem) def new_general_entity(self, name, val): self._decl_handler.internalEntityDecl(name, val) def new_external_entity(self, ent_name, pub_id, sys_id, ndata): if not ndata: self._decl_handler.externalEntityDecl(ent_name, pub_id, sys_id) else: self._dtd_handler.unparsedEntityDecl(ent_name, pub_id, sys_id, ndata) def new_parameter_entity(self, name, val): self._decl_handler.internalEntityDecl("%" + name, val) def new_external_pe(self, name, pubid, sysid): self._decl_handler.externalEntityDecl("%" + name, pubid, sysid) def new_notation(self, name, pubid, sysid): self._dtd_handler.notationDecl(name, pubid, sysid) def new_element_type(self, elem_name, elem_cont): if elem_cont == None: elem_cont = "ANY" elif elem_cont == ("", [], ""): elem_cont = "EMPTY" self._decl_handler.elementDecl(elem_name, elem_cont) def new_attribute(self, elem, attr, type, a_decl, a_def): self._decl_handler.attributeDecl(elem, attr, type, a_decl, a_def) # --- NamespaceFilter class NamespaceFilter: """An xmlproc application that processes qualified names and reports them as (URI, local-part). It reports errors through the error reporting mechanisms of the parser.""" def __init__(self, parser, content, lexical, driver): self._cont_handler = content self._lex_handler = lexical self.driver = driver self.ns_map = {} # Current prefix -> URI map self.ns_map["xml"] = "http://www.w3.org/XML/1998/namespace" self.ns_stack = [] # Pushed for each element, used to maint ns_map self.rep_ns_attrs = 0 # Report xmlns-attributes? self.parser = parser def set_locator(self, locator): self.driver.set_locator(locator) def doc_start(self): self._cont_handler.startDocument() def doc_end(self): self._cont_handler.endDocument() def handle_comment(self, data): self._lex_handler.comment(data) def handle_start_tag(self,name,attrs): old_ns={} # Reset ns_map to these values when we leave this element del_ns=[] # Delete these prefixes from ns_map when we leave element # attrs=attrs.copy() Will have to do this if more filters are made # Find declarations, update self.ns_map and self.ns_stack for (a,v) in attrs.items(): if a[:6]=="xmlns:": prefix=a[6:] if string.find(prefix,":")!=-1: self.parser.report_error(1900) #if v=="": # self.parser.report_error(1901) elif a=="xmlns": prefix="" else: continue if self.ns_map.has_key(prefix): old_ns[prefix]=self.ns_map[prefix] if v: self.ns_map[prefix]=v else: del self.ns_map[prefix] if not self.rep_ns_attrs: del attrs[a] self.ns_stack.append((old_ns,del_ns)) # Process elem and attr names cooked_name = self.__process_name(name) ns = cooked_name[0] rawnames = {} for (a,v) in attrs.items(): del attrs[a] aname = self.__process_name(a, is_attr=1) if attrs.has_key(aname): self.parser.report_error(1903) attrs[aname] = v rawnames[aname] = a # Report event self._cont_handler.startElementNS(cooked_name, name, AttributesNSImpl(attrs, rawnames)) def handle_end_tag(self, rawname): name = self.__process_name(rawname) # Clean up self.ns_map and self.ns_stack (old_ns,del_ns)=self.ns_stack[-1] del self.ns_stack[-1] self.ns_map.update(old_ns) for prefix in del_ns: del self.ns_map[prefix] self._cont_handler.endElementNS(name, rawname) def handle_data(self, data, start, end): self._cont_handler.characters(data[start:end]) def handle_ignorable_data(self, data, start, end): self._cont_handler.ignorableWhitespace(data[start:end]) def handle_pi(self, target, data): self._cont_handler.processingInstruction(target, data) def handle_doctype(self, root, pubId, sysId): self._lex_handler.startDTD(root, pubId, sysId) def set_entity_info(self, xmlver, enc, sddecl): pass # --- Internal methods def __process_name(self, name, default_to=None, is_attr=0): n=string.split(name,":") if len(n)>2: self.parser.report_error(1900) return (None, name) elif len(n)==2: if n[0]=="xmlns": return (None, name) try: return (self.ns_map[n[0]], n[1]) except KeyError: self.parser.report_error(1902) return (None, name) elif is_attr: return (None, name) elif default_to != None: return (default_to, name) elif self.ns_map.has_key("") and name != "xmlns": return (self.ns_map[""],name) else: return (None, name) def create_parser(): return XmlprocDriver()
gpl-2.0
golismero/golismero-devel
thirdparty_libs/django/utils/formats.py
104
7799
import decimal import datetime from django.conf import settings from django.utils import dateformat, numberformat, datetime_safe from django.utils.importlib import import_module from django.utils.encoding import force_str from django.utils.functional import lazy from django.utils.safestring import mark_safe from django.utils import six from django.utils.translation import get_language, to_locale, check_for_language # format_cache is a mapping from (format_type, lang) to the format string. # By using the cache, it is possible to avoid running get_format_modules # repeatedly. _format_cache = {} _format_modules_cache = {} ISO_INPUT_FORMATS = { 'DATE_INPUT_FORMATS': ('%Y-%m-%d',), 'TIME_INPUT_FORMATS': ('%H:%M:%S', '%H:%M'), 'DATETIME_INPUT_FORMATS': ( '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d' ), } def reset_format_cache(): """Clear any cached formats. This method is provided primarily for testing purposes, so that the effects of cached formats can be removed. """ global _format_cache, _format_modules_cache _format_cache = {} _format_modules_cache = {} def iter_format_modules(lang): """ Does the heavy lifting of finding format modules. """ if check_for_language(lang): format_locations = ['django.conf.locale.%s'] if settings.FORMAT_MODULE_PATH: format_locations.append(settings.FORMAT_MODULE_PATH + '.%s') format_locations.reverse() locale = to_locale(lang) locales = [locale] if '_' in locale: locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: try: yield import_module('.formats', location % loc) except ImportError: pass def get_format_modules(lang=None, reverse=False): """ Returns a list of the format modules found """ if lang is None: lang = get_language() modules = _format_modules_cache.setdefault(lang, list(iter_format_modules(lang))) if reverse: return list(reversed(modules)) return modules def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if use_l10n or (use_l10n is None and settings.USE_L10N): if lang is None: lang = get_language() cache_key = (format_type, lang) try: cached = _format_cache[cache_key] if cached is not None: return cached else: # Return the general setting by default return getattr(settings, format_type) except KeyError: for module in get_format_modules(lang): try: val = getattr(module, format_type) for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): if iso_input not in val: if isinstance(val, tuple): val = list(val) val.append(iso_input) _format_cache[cache_key] = val return val except AttributeError: pass _format_cache[cache_key] = None return getattr(settings, format_type) get_format_lazy = lazy(get_format, six.text_type, list, tuple) def date_format(value, format=None, use_l10n=None): """ Formats a datetime.date or datetime.datetime object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n)) def time_format(value, format=None, use_l10n=None): """ Formats a datetime.time object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n)) def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Formats a numeric value using localization settings If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n or (use_l10n is None and settings.USE_L10N): lang = get_language() else: lang = None return numberformat.format( value, get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n), decimal_pos, get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n), get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n), force_grouping=force_grouping ) def localize(value, use_l10n=None): """ Checks if value is a localizable type (date, number...) and returns it formatted as a string using current locale format. If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ if isinstance(value, bool): return mark_safe(six.text_type(value)) elif isinstance(value, (decimal.Decimal, float) + six.integer_types): return number_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.datetime): return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n) elif isinstance(value, datetime.date): return date_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.time): return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n) else: return value def localize_input(value, default=None): """ Checks if an input value is a localizable type and returns it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, (decimal.Decimal, float) + six.integer_types): return number_format(value) elif isinstance(value, datetime.datetime): value = datetime_safe.new_datetime(value) format = force_str(default or get_format('DATETIME_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.date): value = datetime_safe.new_date(value) format = force_str(default or get_format('DATE_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.time): format = force_str(default or get_format('TIME_INPUT_FORMATS')[0]) return value.strftime(format) return value def sanitize_separators(value): """ Sanitizes a value according to the current decimal and thousand separator setting. Used with form field input. """ if settings.USE_L10N: decimal_separator = get_format('DECIMAL_SEPARATOR') if isinstance(value, six.string_types): parts = [] if decimal_separator in value: value, decimals = value.split(decimal_separator, 1) parts.append(decimals) if settings.USE_THOUSAND_SEPARATOR: parts.append(value.replace(get_format('THOUSAND_SEPARATOR'), '')) else: parts.append(value) value = '.'.join(reversed(parts)) return value
gpl-2.0
dongjoon-hyun/tensorflow
tensorflow/contrib/specs/python/specs_test.py
23
8218
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Testing specs specifications.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.specs import python from tensorflow.contrib.specs.python import summaries from tensorflow.python.framework import constant_op from tensorflow.python.ops import init_ops from tensorflow.python.ops import variables import tensorflow.python.ops.math_ops # pylint: disable=unused-import from tensorflow.python.platform import test specs = python def _rand(*size): return np.random.uniform(size=size).astype("f") class SpecsTest(test.TestCase): def testSimpleConv(self): with self.cached_session(): inputs = constant_op.constant(_rand(1, 18, 19, 5)) spec = "net = Cr(64, [5, 5])" outputs = specs.create_net(spec, inputs) self.assertEqual(outputs.get_shape().as_list(), [1, 18, 19, 64]) variables.global_variables_initializer().run() result = outputs.eval() self.assertEqual(tuple(result.shape), (1, 18, 19, 64)) self.assertEqual( summaries.tf_spec_structure(spec, inputs), "_ variablev2 conv variablev2 biasadd relu") def testUnary(self): # This is just a quick and dirty check that these ops exist # and work as unary ops. with self.cached_session(): inputs = constant_op.constant(_rand(17, 55)) spec = "net = Do(0.5) | Bn | Unit(1) | Relu | Sig | Tanh | Smax" outputs = specs.create_net(spec, inputs) self.assertEqual(outputs.get_shape().as_list(), [17, 55]) variables.global_variables_initializer().run() result = outputs.eval() self.assertEqual(tuple(result.shape), (17, 55)) def testAdd(self): with self.cached_session(): inputs = constant_op.constant(_rand(17, 55)) spec = "net = Fs(10) + Fr(10)" outputs = specs.create_net(spec, inputs) self.assertEqual(outputs.get_shape().as_list(), [17, 10]) variables.global_variables_initializer().run() result = outputs.eval() self.assertEqual(tuple(result.shape), (17, 10)) self.assertEqual( summaries.tf_spec_structure(spec, inputs), "_ variablev2 dot variablev2 biasadd sig " "<> variablev2 dot variablev2 biasadd relu add") def testMpPower(self): with self.cached_session(): inputs = constant_op.constant(_rand(1, 64, 64, 5)) spec = "M2 = Mp([2, 2]); net = M2**3" outputs = specs.create_net(spec, inputs) self.assertEqual(outputs.get_shape().as_list(), [1, 8, 8, 5]) variables.global_variables_initializer().run() result = outputs.eval() self.assertEqual(tuple(result.shape), (1, 8, 8, 5)) self.assertEqual( summaries.tf_spec_structure(spec, inputs), "_ maxpool maxpool maxpool") def testAbbrevPower(self): with self.cached_session(): inputs = constant_op.constant(_rand(1, 64, 64, 5)) spec = "C3 = Cr([3, 3]); M2 = Mp([2, 2]); net = (C3(5) | M2)**3" outputs = specs.create_net(spec, inputs) self.assertEqual(outputs.get_shape().as_list(), [1, 8, 8, 5]) variables.global_variables_initializer().run() result = outputs.eval() self.assertEqual(tuple(result.shape), (1, 8, 8, 5)) self.assertEqual( summaries.tf_spec_structure(spec, inputs), "_ variablev2 conv variablev2 biasadd relu maxpool" " variablev2 conv variablev2" " biasadd relu maxpool variablev2 conv variablev2" " biasadd relu maxpool") def testAbbrevPower2(self): with self.cached_session(): inputs = constant_op.constant(_rand(1, 64, 64, 5)) spec = "C3 = Cr(_1=[3, 3]); M2 = Mp([2, 2]);" spec += "net = (C3(_0=5) | M2)**3" outputs = specs.create_net(spec, inputs) self.assertEqual(outputs.get_shape().as_list(), [1, 8, 8, 5]) variables.global_variables_initializer().run() result = outputs.eval() self.assertEqual(tuple(result.shape), (1, 8, 8, 5)) self.assertEqual( summaries.tf_spec_structure(spec, inputs), "_ variablev2 conv variablev2 biasadd relu maxpool" " variablev2 conv variablev2 biasadd relu" " maxpool variablev2 conv variablev2 biasadd relu" " maxpool") def testConc(self): with self.cached_session(): inputs = constant_op.constant(_rand(10, 20)) spec = "net = Conc(1, Fs(20), Fs(10))" outputs = specs.create_net(spec, inputs) self.assertEqual(outputs.get_shape().as_list(), [10, 30]) variables.global_variables_initializer().run() result = outputs.eval() self.assertEqual(tuple(result.shape), (10, 30)) self.assertEqual( summaries.tf_spec_structure(spec, inputs), "_ variablev2 dot variablev2 biasadd sig " "<> variablev2 dot variablev2 biasadd sig _ concatv2") def testImport(self): with self.cached_session(): inputs = constant_op.constant(_rand(10, 20)) spec = ("S = Import('from tensorflow.python.ops" + " import math_ops; f = math_ops.sigmoid')") spec += "; net = S | S" outputs = specs.create_net(spec, inputs) self.assertEqual(outputs.get_shape().as_list(), [10, 20]) variables.global_variables_initializer().run() result = outputs.eval() self.assertEqual(tuple(result.shape), (10, 20)) self.assertEqual(summaries.tf_spec_structure(spec, inputs), "_ sig sig") def testKeywordRestriction(self): with self.cached_session(): inputs = constant_op.constant(_rand(10, 20)) spec = "import re; net = Conc(1, Fs(20), Fs(10))" self.assertRaises(ValueError, lambda: specs.create_net(spec, inputs)) def testParams(self): params = "x = 3; y = Ui(-10, 10); z = Lf(1, 100); q = Nt(0.0, 1.0)" bindings = specs.eval_params(params, {}) self.assertTrue("x" in bindings) self.assertEqual(bindings["x"], 3) self.assertTrue("y" in bindings) self.assertTrue("z" in bindings) self.assertTrue("q" in bindings) # XXX: the cleverness of this code is over 9000 # TODO: original author please fix def DISABLED_testSpecsOps(self): # pylint: disable=undefined-variable with self.assertRaises(NameError): _ = Cr with specs.ops: self.assertIsNotNone(Cr) self.assertTrue(callable(Cr(64, [3, 3]))) with self.assertRaises(NameError): _ = Cr # XXX: the cleverness of this code is over 9000 # TODO: original author please fix def DISABLED_testVar(self): with self.cached_session() as sess: with specs.ops: # pylint: disable=undefined-variable v = Var("test_var", shape=[2, 2], initializer=init_ops.constant_initializer(42.0)) inputs = constant_op.constant(_rand(10, 100)) outputs = v.funcall(inputs) self.assertEqual(len(variables.global_variables()), 1) sess.run([outputs.initializer]) outputs_value = outputs.eval() self.assertEqual(outputs_value.shape, (2, 2)) self.assertEqual(outputs_value[1, 1], 42.0) # XXX: the cleverness of this code is over 9000 # TODO: original author please fix def DISABLED_testShared(self): with self.cached_session(): with specs.ops: # pylint: disable=undefined-variable f = Shared(Fr(100)) g = f | f | f | f inputs = constant_op.constant(_rand(10, 100)) _ = g.funcall(inputs) self.assertEqual(len(variables.global_variables()), 2) if __name__ == "__main__": test.main()
apache-2.0
lmazuel/azure-sdk-for-python
azure-mgmt-recoveryservices/azure/mgmt/recoveryservices/models/vault_usage.py
2
1943
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class VaultUsage(Model): """Usages of a vault. :param unit: Unit of the usage. Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond' :type unit: str or :class:`UsagesUnit <azure.mgmt.recoveryservices.models.UsagesUnit>` :param quota_period: Quota period of usage. :type quota_period: str :param next_reset_time: Next reset time of usage. :type next_reset_time: datetime :param current_value: Current value of usage. :type current_value: long :param limit: Limit of usage. :type limit: long :param name: Name of usage. :type name: :class:`NameInfo <azure.mgmt.recoveryservices.models.NameInfo>` """ _attribute_map = { 'unit': {'key': 'unit', 'type': 'str'}, 'quota_period': {'key': 'quotaPeriod', 'type': 'str'}, 'next_reset_time': {'key': 'nextResetTime', 'type': 'iso-8601'}, 'current_value': {'key': 'currentValue', 'type': 'long'}, 'limit': {'key': 'limit', 'type': 'long'}, 'name': {'key': 'name', 'type': 'NameInfo'}, } def __init__(self, unit=None, quota_period=None, next_reset_time=None, current_value=None, limit=None, name=None): self.unit = unit self.quota_period = quota_period self.next_reset_time = next_reset_time self.current_value = current_value self.limit = limit self.name = name
mit
Jorge-Rodriguez/ansible
test/units/module_utils/basic/test_safe_eval.py
134
2333
# -*- coding: utf-8 -*- # (c) 2015-2017, Toshio Kuratomi <tkuratomi@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division) __metaclass__ = type from itertools import chain import pytest # Strings that should be converted into a typed value VALID_STRINGS = ( ("'a'", 'a'), ("'1'", '1'), ("1", 1), ("True", True), ("False", False), ("{}", {}), ) # Passing things that aren't strings should just return the object NONSTRINGS = ( ({'a': 1}, {'a': 1}), ) # These strings are not basic types. For security, these should not be # executed. We return the same string and get an exception for some INVALID_STRINGS = ( ("a=1", "a=1", SyntaxError), ("a.foo()", "a.foo()", None), ("import foo", "import foo", None), ("__import__('foo')", "__import__('foo')", ValueError), ) @pytest.mark.parametrize('code, expected, stdin', ((c, e, {}) for c, e in chain(VALID_STRINGS, NONSTRINGS)), indirect=['stdin']) def test_simple_types(am, code, expected): # test some basic usage for various types assert am.safe_eval(code) == expected @pytest.mark.parametrize('code, expected, stdin', ((c, e, {}) for c, e in chain(VALID_STRINGS, NONSTRINGS)), indirect=['stdin']) def test_simple_types_with_exceptions(am, code, expected): # Test simple types with exceptions requested assert am.safe_eval(code, include_exceptions=True), (expected, None) @pytest.mark.parametrize('code, expected, stdin', ((c, e, {}) for c, e, dummy in INVALID_STRINGS), indirect=['stdin']) def test_invalid_strings(am, code, expected): assert am.safe_eval(code) == expected @pytest.mark.parametrize('code, expected, exception, stdin', ((c, e, ex, {}) for c, e, ex in INVALID_STRINGS), indirect=['stdin']) def test_invalid_strings_with_exceptions(am, code, expected, exception): res = am.safe_eval(code, include_exceptions=True) assert res[0] == expected if exception is None: assert res[1] == exception else: assert type(res[1]) == exception
gpl-3.0
chacoroot/planetary
addons/auth_oauth/res_users.py
157
4897
import logging import werkzeug.urls import urlparse import urllib2 import simplejson import openerp from openerp.addons.auth_signup.res_users import SignupError from openerp.osv import osv, fields from openerp import SUPERUSER_ID _logger = logging.getLogger(__name__) class res_users(osv.Model): _inherit = 'res.users' _columns = { 'oauth_provider_id': fields.many2one('auth.oauth.provider', 'OAuth Provider'), 'oauth_uid': fields.char('OAuth User ID', help="Oauth Provider user_id", copy=False), 'oauth_access_token': fields.char('OAuth Access Token', readonly=True, copy=False), } _sql_constraints = [ ('uniq_users_oauth_provider_oauth_uid', 'unique(oauth_provider_id, oauth_uid)', 'OAuth UID must be unique per provider'), ] def _auth_oauth_rpc(self, cr, uid, endpoint, access_token, context=None): params = werkzeug.url_encode({'access_token': access_token}) if urlparse.urlparse(endpoint)[4]: url = endpoint + '&' + params else: url = endpoint + '?' + params f = urllib2.urlopen(url) response = f.read() return simplejson.loads(response) def _auth_oauth_validate(self, cr, uid, provider, access_token, context=None): """ return the validation data corresponding to the access token """ p = self.pool.get('auth.oauth.provider').browse(cr, uid, provider, context=context) validation = self._auth_oauth_rpc(cr, uid, p.validation_endpoint, access_token) if validation.get("error"): raise Exception(validation['error']) if p.data_endpoint: data = self._auth_oauth_rpc(cr, uid, p.data_endpoint, access_token) validation.update(data) return validation def _auth_oauth_signin(self, cr, uid, provider, validation, params, context=None): """ retrieve and sign in the user corresponding to provider and validated access token :param provider: oauth provider id (int) :param validation: result of validation of access token (dict) :param params: oauth parameters (dict) :return: user login (str) :raise: openerp.exceptions.AccessDenied if signin failed This method can be overridden to add alternative signin methods. """ try: oauth_uid = validation['user_id'] user_ids = self.search(cr, uid, [("oauth_uid", "=", oauth_uid), ('oauth_provider_id', '=', provider)]) if not user_ids: raise openerp.exceptions.AccessDenied() assert len(user_ids) == 1 user = self.browse(cr, uid, user_ids[0], context=context) user.write({'oauth_access_token': params['access_token']}) return user.login except openerp.exceptions.AccessDenied, access_denied_exception: if context and context.get('no_user_creation'): return None state = simplejson.loads(params['state']) token = state.get('t') oauth_uid = validation['user_id'] email = validation.get('email', 'provider_%s_user_%s' % (provider, oauth_uid)) name = validation.get('name', email) values = { 'name': name, 'login': email, 'email': email, 'oauth_provider_id': provider, 'oauth_uid': oauth_uid, 'oauth_access_token': params['access_token'], 'active': True, } try: _, login, _ = self.signup(cr, uid, values, token, context=context) return login except SignupError: raise access_denied_exception def auth_oauth(self, cr, uid, provider, params, context=None): # Advice by Google (to avoid Confused Deputy Problem) # if validation.audience != OUR_CLIENT_ID: # abort() # else: # continue with the process access_token = params.get('access_token') validation = self._auth_oauth_validate(cr, uid, provider, access_token) # required check if not validation.get('user_id'): raise openerp.exceptions.AccessDenied() # retrieve and sign in user login = self._auth_oauth_signin(cr, uid, provider, validation, params, context=context) if not login: raise openerp.exceptions.AccessDenied() # return user credentials return (cr.dbname, login, access_token) def check_credentials(self, cr, uid, password): try: return super(res_users, self).check_credentials(cr, uid, password) except openerp.exceptions.AccessDenied: res = self.search(cr, SUPERUSER_ID, [('id', '=', uid), ('oauth_access_token', '=', password)]) if not res: raise #
agpl-3.0
adlius/osf.io
osf/models/banner.py
16
1944
from django.db import models from datetime import datetime from osf.utils.storage import BannerImageStorage from osf.exceptions import ValidationValueError from osf.utils.fields import NonNaiveDateTimeField def validate_banner_dates(banner_id, start_date, end_date): if start_date > end_date: raise ValidationValueError('Start date must be before end date.') overlapping = ScheduledBanner.objects.filter( (models.Q(start_date__gte=start_date) & models.Q(start_date__lte=end_date)) | (models.Q(end_date__gte=start_date) & models.Q(end_date__lte=end_date)) | (models.Q(start_date__lte=start_date) & models.Q(end_date__gte=end_date)) ).exclude(id=banner_id).exists() if overlapping: raise ValidationValueError('Banners dates cannot be overlapping.') class ScheduledBanner(models.Model): class Meta: # Custom permissions for use in the OSF Admin App permissions = ( ('view_scheduledbanner', 'Can view scheduled banner details'), ) name = models.CharField(unique=True, max_length=256) start_date = NonNaiveDateTimeField() end_date = NonNaiveDateTimeField() color = models.CharField(max_length=7) license = models.CharField(blank=True, null=True, max_length=256) link = models.URLField(blank=True, default='https://www.crowdrise.com/centerforopenscience') default_photo = models.FileField(storage=BannerImageStorage()) default_alt_text = models.TextField() mobile_photo = models.FileField(storage=BannerImageStorage()) mobile_alt_text = models.TextField(blank=True, null=True) def save(self, *args, **kwargs): self.start_date = datetime.combine(self.start_date, datetime.min.time()) self.end_date = datetime.combine(self.end_date, datetime.max.time()) validate_banner_dates(self.id, self.start_date, self.end_date) super(ScheduledBanner, self).save(*args, **kwargs)
apache-2.0
rjeschmi/easybuild-framework
test/framework/easyconfigparser.py
5
7251
# # # Copyright 2013-2015 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (http://www.herculesstichting.be/in_English) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation v2. # # EasyBuild is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with EasyBuild. If not, see <http://www.gnu.org/licenses/>. # # """ Unit tests for easyconfig/parser.py @author: Stijn De Weirdt (Ghent University) """ import os from test.framework.utilities import EnhancedTestCase from unittest import TestLoader, main from vsc.utils.fancylogger import setLogLevelDebug, logToScreen import easybuild.tools.build_log from easybuild.framework.easyconfig.format.format import Dependency from easybuild.framework.easyconfig.format.version import EasyVersion from easybuild.framework.easyconfig.parser import EasyConfigParser from easybuild.tools.build_log import EasyBuildError from easybuild.tools.filetools import read_file TESTDIRBASE = os.path.join(os.path.dirname(__file__), 'easyconfigs') class EasyConfigParserTest(EnhancedTestCase): """Test the parser""" def test_v10(self): ecp = EasyConfigParser(os.path.join(TESTDIRBASE, 'v1.0', 'GCC-4.6.3.eb')) self.assertEqual(ecp._formatter.VERSION, EasyVersion('1.0')) ec = ecp.get_config_dict() self.assertEqual(ec['toolchain'], {'name': 'dummy', 'version': 'dummy'}) self.assertEqual(ec['name'], 'GCC') self.assertEqual(ec['version'], '4.6.3') def test_v20(self): """Test parsing of easyconfig in format v2.""" # hard enable experimental orig_experimental = easybuild.tools.build_log.EXPERIMENTAL easybuild.tools.build_log.EXPERIMENTAL = True fn = os.path.join(TESTDIRBASE, 'v2.0', 'GCC.eb') ecp = EasyConfigParser(fn) formatter = ecp._formatter self.assertEqual(formatter.VERSION, EasyVersion('2.0')) self.assertTrue('name' in formatter.pyheader_localvars) self.assertFalse('version' in formatter.pyheader_localvars) self.assertFalse('toolchain' in formatter.pyheader_localvars) # this should be ok: ie the default values ec = ecp.get_config_dict() self.assertEqual(ec['toolchain'], {'name': 'dummy', 'version': 'dummy'}) self.assertEqual(ec['name'], 'GCC') self.assertEqual(ec['version'], '4.6.2') # restore easybuild.tools.build_log.EXPERIMENTAL = orig_experimental def test_v20_extra(self): """Test parsing of easyconfig in format v2.""" # hard enable experimental orig_experimental = easybuild.tools.build_log.EXPERIMENTAL easybuild.tools.build_log.EXPERIMENTAL = True fn = os.path.join(TESTDIRBASE, 'v2.0', 'doesnotexist.eb') ecp = EasyConfigParser(fn) formatter = ecp._formatter self.assertEqual(formatter.VERSION, EasyVersion('2.0')) self.assertTrue('name' in formatter.pyheader_localvars) self.assertFalse('version' in formatter.pyheader_localvars) self.assertFalse('toolchain' in formatter.pyheader_localvars) # restore easybuild.tools.build_log.EXPERIMENTAL = orig_experimental def test_v20_deps(self): """Test parsing of easyconfig in format v2 that includes dependencies.""" # hard enable experimental orig_experimental = easybuild.tools.build_log.EXPERIMENTAL easybuild.tools.build_log.EXPERIMENTAL = True fn = os.path.join(TESTDIRBASE, 'v2.0', 'libpng.eb') ecp = EasyConfigParser(fn) ec = ecp.get_config_dict() self.assertEqual(ec['name'], 'libpng') # first version/toolchain listed is default self.assertEqual(ec['version'], '1.5.10') self.assertEqual(ec['toolchain'], {'name': 'goolf', 'version': '1.4.10'}) # dependencies should be parsed correctly deps = ec['dependencies'] self.assertTrue(isinstance(deps[0], Dependency)) self.assertEqual(deps[0].name(), 'zlib') self.assertEqual(deps[0].version(), '1.2.5') fn = os.path.join(TESTDIRBASE, 'v2.0', 'goolf.eb') ecp = EasyConfigParser(fn) ec = ecp.get_config_dict() self.assertEqual(ec['name'], 'goolf') self.assertEqual(ec['version'], '1.4.10') self.assertEqual(ec['toolchain'], {'name': 'dummy', 'version': 'dummy'}) # dependencies should be parsed correctly deps = [ # name, version, versionsuffix, toolchain ('GCC', '4.7.2', None, None), ('OpenMPI', '1.6.4', None, {'name': 'GCC', 'version': '4.7.2'}), ('OpenBLAS', '0.2.6', '-LAPACK-3.4.2', {'name': 'gompi', 'version': '1.4.10'}), ('FFTW', '3.3.3', None, {'name': 'gompi', 'version': '1.4.10'}), ('ScaLAPACK', '2.0.2', '-OpenBLAS-0.2.6-LAPACK-3.4.2', {'name': 'gompi', 'version': '1.4.10'}), ] for i, (name, version, versionsuffix, toolchain) in enumerate(deps): self.assertEqual(ec['dependencies'][i].name(), name) self.assertEqual(ec['dependencies'][i].version(), version) self.assertEqual(ec['dependencies'][i].versionsuffix(), versionsuffix) self.assertEqual(ec['dependencies'][i].toolchain(), toolchain) # restore easybuild.tools.build_log.EXPERIMENTAL = orig_experimental def test_raw(self): """Test passing of raw contents to EasyConfigParser.""" ec_file1 = os.path.join(TESTDIRBASE, 'v1.0', 'GCC-4.6.3.eb') ec_txt1 = read_file(ec_file1) ec_file2 = os.path.join(TESTDIRBASE, 'v1.0', 'gzip-1.5-goolf-1.4.10.eb') ec_txt2 = read_file(ec_file2) ecparser = EasyConfigParser(ec_file1) self.assertEqual(ecparser.rawcontent, ec_txt1) ecparser = EasyConfigParser(rawcontent=ec_txt2) self.assertEqual(ecparser.rawcontent, ec_txt2) # rawcontent supersedes passed filepath ecparser = EasyConfigParser(ec_file1, rawcontent=ec_txt2) self.assertEqual(ecparser.rawcontent, ec_txt2) ec = ecparser.get_config_dict() self.assertEqual(ec['name'], 'gzip') self.assertEqual(ec['toolchain']['name'], 'goolf') self.assertErrorRegex(EasyBuildError, "Neither filename nor rawcontent provided", EasyConfigParser) def suite(): """ returns all the testcases in this module """ return TestLoader().loadTestsFromTestCase(EasyConfigParserTest) if __name__ == '__main__': # logToScreen(enable=True) # setLogLevelDebug() main()
gpl-2.0
danking/hail
hail/python/hail/utils/deduplicate.py
2
1428
from typing import List, Tuple, Optional, Set def deduplicate( ids: List[str], *, max_attempts: Optional[int] = None, already_used: Set[int] = None ) -> Tuple[List[Tuple[str, str]], List[str]]: """Deduplicate the strings in `ids`. Example ------- >>> deduplicate(['a', 'a', 'a']) ([('a', 'a_1'), ('a', 'a_2')], ['a', 'a_1', 'a_2']) >>> deduplicate(['a', 'a_1', 'a']) ([('a', 'a_2')], ['a', 'a_1', 'a_2']) Parameters ---------- ids : list of :class:`str` The list of strings, possibly containing duplicates. Returns ------- list of pairs of :class:`str` and :obj:`str` A string and the deduplicated string, for each occurrence after the first. list of :class:`str` A list, equal in length to `ids`, without duplicates. """ uniques = set(already_used) if already_used else set() mapping = [] new_ids = [] def fmt(s, i): return '{}_{}'.format(s, i) for s in ids: s_ = s i = 0 while s_ in uniques: i += 1 if max_attempts and i > max_attempts: raise RecursionError( f'cannot deduplicate {s} after {max_attempts} attempts') s_ = fmt(s, i) if s_ != s: mapping.append((s, s_)) uniques.add(s_) new_ids.append(s_) return mapping, new_ids
mit
akopytov/percona-xtrabackup
storage/innobase/xtrabackup/test/python/testtools/testcase.py
42
25812
# Copyright (c) 2008-2011 testtools developers. See LICENSE for details. """Test case related stuff.""" __metaclass__ = type __all__ = [ 'clone_test_with_new_id', 'ExpectedException', 'run_test_with', 'skip', 'skipIf', 'skipUnless', 'TestCase', ] import copy import itertools import re import sys import types import unittest from testtools import ( content, try_import, ) from testtools.compat import advance_iterator from testtools.matchers import ( Annotate, Equals, ) from testtools.monkey import patch from testtools.runtest import RunTest from testtools.testresult import TestResult wraps = try_import('functools.wraps') class TestSkipped(Exception): """Raised within TestCase.run() when a test is skipped.""" testSkipped = try_import('unittest2.case.SkipTest', TestSkipped) TestSkipped = try_import('unittest.case.SkipTest', TestSkipped) class _UnexpectedSuccess(Exception): """An unexpected success was raised. Note that this exception is private plumbing in testtools' testcase module. """ _UnexpectedSuccess = try_import( 'unittest2.case._UnexpectedSuccess', _UnexpectedSuccess) _UnexpectedSuccess = try_import( 'unittest.case._UnexpectedSuccess', _UnexpectedSuccess) class _ExpectedFailure(Exception): """An expected failure occured. Note that this exception is private plumbing in testtools' testcase module. """ _ExpectedFailure = try_import( 'unittest2.case._ExpectedFailure', _ExpectedFailure) _ExpectedFailure = try_import( 'unittest.case._ExpectedFailure', _ExpectedFailure) def run_test_with(test_runner, **kwargs): """Decorate a test as using a specific ``RunTest``. e.g.:: @run_test_with(CustomRunner, timeout=42) def test_foo(self): self.assertTrue(True) The returned decorator works by setting an attribute on the decorated function. `TestCase.__init__` looks for this attribute when deciding on a ``RunTest`` factory. If you wish to use multiple decorators on a test method, then you must either make this one the top-most decorator, or you must write your decorators so that they update the wrapping function with the attributes of the wrapped function. The latter is recommended style anyway. ``functools.wraps``, ``functools.wrapper`` and ``twisted.python.util.mergeFunctionMetadata`` can help you do this. :param test_runner: A ``RunTest`` factory that takes a test case and an optional list of exception handlers. See ``RunTest``. :param kwargs: Keyword arguments to pass on as extra arguments to 'test_runner'. :return: A decorator to be used for marking a test as needing a special runner. """ def decorator(function): # Set an attribute on 'function' which will inform TestCase how to # make the runner. function._run_test_with = ( lambda case, handlers=None: test_runner(case, handlers=handlers, **kwargs)) return function return decorator class TestCase(unittest.TestCase): """Extensions to the basic TestCase. :ivar exception_handlers: Exceptions to catch from setUp, runTest and tearDown. This list is able to be modified at any time and consists of (exception_class, handler(case, result, exception_value)) pairs. :cvar run_tests_with: A factory to make the ``RunTest`` to run tests with. Defaults to ``RunTest``. The factory is expected to take a test case and an optional list of exception handlers. """ skipException = TestSkipped run_tests_with = RunTest def __init__(self, *args, **kwargs): """Construct a TestCase. :param testMethod: The name of the method to run. :keyword runTest: Optional class to use to execute the test. If not supplied ``RunTest`` is used. The instance to be used is created when run() is invoked, so will be fresh each time. Overrides ``TestCase.run_tests_with`` if given. """ runTest = kwargs.pop('runTest', None) unittest.TestCase.__init__(self, *args, **kwargs) self._cleanups = [] self._unique_id_gen = itertools.count(1) # Generators to ensure unique traceback ids. Maps traceback label to # iterators. self._traceback_id_gens = {} self.__setup_called = False self.__teardown_called = False # __details is lazy-initialized so that a constructed-but-not-run # TestCase is safe to use with clone_test_with_new_id. self.__details = None test_method = self._get_test_method() if runTest is None: runTest = getattr( test_method, '_run_test_with', self.run_tests_with) self.__RunTest = runTest self.__exception_handlers = [] self.exception_handlers = [ (self.skipException, self._report_skip), (self.failureException, self._report_failure), (_ExpectedFailure, self._report_expected_failure), (_UnexpectedSuccess, self._report_unexpected_success), (Exception, self._report_error), ] if sys.version_info < (2, 6): # Catch old-style string exceptions with None as the instance self.exception_handlers.append((type(None), self._report_error)) def __eq__(self, other): eq = getattr(unittest.TestCase, '__eq__', None) if eq is not None and not unittest.TestCase.__eq__(self, other): return False return self.__dict__ == other.__dict__ def __repr__(self): # We add id to the repr because it makes testing testtools easier. return "<%s id=0x%0x>" % (self.id(), id(self)) def addDetail(self, name, content_object): """Add a detail to be reported with this test's outcome. For more details see pydoc testtools.TestResult. :param name: The name to give this detail. :param content_object: The content object for this detail. See testtools.content for more detail. """ if self.__details is None: self.__details = {} self.__details[name] = content_object def getDetails(self): """Get the details dict that will be reported with this test's outcome. For more details see pydoc testtools.TestResult. """ if self.__details is None: self.__details = {} return self.__details def patch(self, obj, attribute, value): """Monkey-patch 'obj.attribute' to 'value' while the test is running. If 'obj' has no attribute, then the monkey-patch will still go ahead, and the attribute will be deleted instead of restored to its original value. :param obj: The object to patch. Can be anything. :param attribute: The attribute on 'obj' to patch. :param value: The value to set 'obj.attribute' to. """ self.addCleanup(patch(obj, attribute, value)) def shortDescription(self): return self.id() def skipTest(self, reason): """Cause this test to be skipped. This raises self.skipException(reason). skipException is raised to permit a skip to be triggered at any point (during setUp or the testMethod itself). The run() method catches skipException and translates that into a call to the result objects addSkip method. :param reason: The reason why the test is being skipped. This must support being cast into a unicode string for reporting. """ raise self.skipException(reason) # skipTest is how python2.7 spells this. Sometime in the future # This should be given a deprecation decorator - RBC 20100611. skip = skipTest def _formatTypes(self, classOrIterable): """Format a class or a bunch of classes for display in an error.""" className = getattr(classOrIterable, '__name__', None) if className is None: className = ', '.join(klass.__name__ for klass in classOrIterable) return className def addCleanup(self, function, *arguments, **keywordArguments): """Add a cleanup function to be called after tearDown. Functions added with addCleanup will be called in reverse order of adding after tearDown, or after setUp if setUp raises an exception. If a function added with addCleanup raises an exception, the error will be recorded as a test error, and the next cleanup will then be run. Cleanup functions are always called before a test finishes running, even if setUp is aborted by an exception. """ self._cleanups.append((function, arguments, keywordArguments)) def addOnException(self, handler): """Add a handler to be called when an exception occurs in test code. This handler cannot affect what result methods are called, and is called before any outcome is called on the result object. An example use for it is to add some diagnostic state to the test details dict which is expensive to calculate and not interesting for reporting in the success case. Handlers are called before the outcome (such as addFailure) that the exception has caused. Handlers are called in first-added, first-called order, and if they raise an exception, that will propogate out of the test running machinery, halting test processing. As a result, do not call code that may unreasonably fail. """ self.__exception_handlers.append(handler) def _add_reason(self, reason): self.addDetail('reason', content.Content( content.ContentType('text', 'plain'), lambda: [reason.encode('utf8')])) def assertEqual(self, expected, observed, message=''): """Assert that 'expected' is equal to 'observed'. :param expected: The expected value. :param observed: The observed value. :param message: An optional message to include in the error. """ matcher = Equals(expected) if message: matcher = Annotate(message, matcher) self.assertThat(observed, matcher) failUnlessEqual = assertEquals = assertEqual def assertIn(self, needle, haystack): """Assert that needle is in haystack.""" self.assertTrue( needle in haystack, '%r not in %r' % (needle, haystack)) def assertIs(self, expected, observed, message=''): """Assert that 'expected' is 'observed'. :param expected: The expected value. :param observed: The observed value. :param message: An optional message describing the error. """ if message: message = ': ' + message self.assertTrue( expected is observed, '%r is not %r%s' % (expected, observed, message)) def assertIsNot(self, expected, observed, message=''): """Assert that 'expected' is not 'observed'.""" if message: message = ': ' + message self.assertTrue( expected is not observed, '%r is %r%s' % (expected, observed, message)) def assertNotIn(self, needle, haystack): """Assert that needle is not in haystack.""" self.assertTrue( needle not in haystack, '%r in %r' % (needle, haystack)) def assertIsInstance(self, obj, klass, msg=None): if msg is None: msg = '%r is not an instance of %s' % ( obj, self._formatTypes(klass)) self.assertTrue(isinstance(obj, klass), msg) def assertRaises(self, excClass, callableObj, *args, **kwargs): """Fail unless an exception of class excClass is thrown by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. """ try: ret = callableObj(*args, **kwargs) except excClass: return sys.exc_info()[1] else: excName = self._formatTypes(excClass) self.fail("%s not raised, %r returned instead." % (excName, ret)) failUnlessRaises = assertRaises def assertThat(self, matchee, matcher): """Assert that matchee is matched by matcher. :param matchee: An object to match with matcher. :param matcher: An object meeting the testtools.Matcher protocol. :raises self.failureException: When matcher does not match thing. """ mismatch = matcher.match(matchee) if not mismatch: return existing_details = self.getDetails() for (name, content) in mismatch.get_details().items(): full_name = name suffix = 1 while full_name in existing_details: full_name = "%s-%d" % (name, suffix) suffix += 1 self.addDetail(full_name, content) self.fail('Match failed. Matchee: "%s"\nMatcher: %s\nDifference: %s\n' % (matchee, matcher, mismatch.describe())) def defaultTestResult(self): return TestResult() def expectFailure(self, reason, predicate, *args, **kwargs): """Check that a test fails in a particular way. If the test fails in the expected way, a KnownFailure is caused. If it succeeds an UnexpectedSuccess is caused. The expected use of expectFailure is as a barrier at the point in a test where the test would fail. For example: >>> def test_foo(self): >>> self.expectFailure("1 should be 0", self.assertNotEqual, 1, 0) >>> self.assertEqual(1, 0) If in the future 1 were to equal 0, the expectFailure call can simply be removed. This separation preserves the original intent of the test while it is in the expectFailure mode. """ self._add_reason(reason) try: predicate(*args, **kwargs) except self.failureException: # GZ 2010-08-12: Don't know how to avoid exc_info cycle as the new # unittest _ExpectedFailure wants old traceback exc_info = sys.exc_info() try: self._report_traceback(exc_info) raise _ExpectedFailure(exc_info) finally: del exc_info else: raise _UnexpectedSuccess(reason) def getUniqueInteger(self): """Get an integer unique to this test. Returns an integer that is guaranteed to be unique to this instance. Use this when you need an arbitrary integer in your test, or as a helper for custom anonymous factory methods. """ return advance_iterator(self._unique_id_gen) def getUniqueString(self, prefix=None): """Get a string unique to this test. Returns a string that is guaranteed to be unique to this instance. Use this when you need an arbitrary string in your test, or as a helper for custom anonymous factory methods. :param prefix: The prefix of the string. If not provided, defaults to the id of the tests. :return: A bytestring of '<prefix>-<unique_int>'. """ if prefix is None: prefix = self.id() return '%s-%d' % (prefix, self.getUniqueInteger()) def onException(self, exc_info, tb_label='traceback'): """Called when an exception propogates from test code. :seealso addOnException: """ if exc_info[0] not in [ TestSkipped, _UnexpectedSuccess, _ExpectedFailure]: self._report_traceback(exc_info, tb_label=tb_label) for handler in self.__exception_handlers: handler(exc_info) @staticmethod def _report_error(self, result, err): result.addError(self, details=self.getDetails()) @staticmethod def _report_expected_failure(self, result, err): result.addExpectedFailure(self, details=self.getDetails()) @staticmethod def _report_failure(self, result, err): result.addFailure(self, details=self.getDetails()) @staticmethod def _report_skip(self, result, err): if err.args: reason = err.args[0] else: reason = "no reason given." self._add_reason(reason) result.addSkip(self, details=self.getDetails()) def _report_traceback(self, exc_info, tb_label='traceback'): id_gen = self._traceback_id_gens.setdefault( tb_label, itertools.count(0)) tb_id = advance_iterator(id_gen) if tb_id: tb_label = '%s-%d' % (tb_label, tb_id) self.addDetail(tb_label, content.TracebackContent(exc_info, self)) @staticmethod def _report_unexpected_success(self, result, err): result.addUnexpectedSuccess(self, details=self.getDetails()) def run(self, result=None): return self.__RunTest(self, self.exception_handlers).run(result) def _run_setup(self, result): """Run the setUp function for this test. :param result: A testtools.TestResult to report activity to. :raises ValueError: If the base class setUp is not called, a ValueError is raised. """ ret = self.setUp() if not self.__setup_called: raise ValueError( "TestCase.setUp was not called. Have you upcalled all the " "way up the hierarchy from your setUp? e.g. Call " "super(%s, self).setUp() from your setUp()." % self.__class__.__name__) return ret def _run_teardown(self, result): """Run the tearDown function for this test. :param result: A testtools.TestResult to report activity to. :raises ValueError: If the base class tearDown is not called, a ValueError is raised. """ ret = self.tearDown() if not self.__teardown_called: raise ValueError( "TestCase.tearDown was not called. Have you upcalled all the " "way up the hierarchy from your tearDown? e.g. Call " "super(%s, self).tearDown() from your tearDown()." % self.__class__.__name__) return ret def _get_test_method(self): absent_attr = object() # Python 2.5+ method_name = getattr(self, '_testMethodName', absent_attr) if method_name is absent_attr: # Python 2.4 method_name = getattr(self, '_TestCase__testMethodName') return getattr(self, method_name) def _run_test_method(self, result): """Run the test method for this test. :param result: A testtools.TestResult to report activity to. :return: None. """ return self._get_test_method()() def useFixture(self, fixture): """Use fixture in a test case. The fixture will be setUp, and self.addCleanup(fixture.cleanUp) called. :param fixture: The fixture to use. :return: The fixture, after setting it up and scheduling a cleanup for it. """ fixture.setUp() self.addCleanup(fixture.cleanUp) self.addCleanup(self._gather_details, fixture.getDetails) return fixture def _gather_details(self, getDetails): """Merge the details from getDetails() into self.getDetails().""" details = getDetails() my_details = self.getDetails() for name, content_object in details.items(): new_name = name disambiguator = itertools.count(1) while new_name in my_details: new_name = '%s-%d' % (name, advance_iterator(disambiguator)) name = new_name content_bytes = list(content_object.iter_bytes()) content_callback = lambda:content_bytes self.addDetail(name, content.Content(content_object.content_type, content_callback)) def setUp(self): unittest.TestCase.setUp(self) self.__setup_called = True def tearDown(self): unittest.TestCase.tearDown(self) self.__teardown_called = True class PlaceHolder(object): """A placeholder test. `PlaceHolder` implements much of the same interface as TestCase and is particularly suitable for being added to TestResults. """ def __init__(self, test_id, short_description=None): """Construct a `PlaceHolder`. :param test_id: The id of the placeholder test. :param short_description: The short description of the place holder test. If not provided, the id will be used instead. """ self._test_id = test_id self._short_description = short_description def __call__(self, result=None): return self.run(result=result) def __repr__(self): internal = [self._test_id] if self._short_description is not None: internal.append(self._short_description) return "<%s.%s(%s)>" % ( self.__class__.__module__, self.__class__.__name__, ", ".join(map(repr, internal))) def __str__(self): return self.id() def countTestCases(self): return 1 def debug(self): pass def id(self): return self._test_id def run(self, result=None): if result is None: result = TestResult() result.startTest(self) result.addSuccess(self) result.stopTest(self) def shortDescription(self): if self._short_description is None: return self.id() else: return self._short_description class ErrorHolder(PlaceHolder): """A placeholder test that will error out when run.""" failureException = None def __init__(self, test_id, error, short_description=None): """Construct an `ErrorHolder`. :param test_id: The id of the test. :param error: The exc info tuple that will be used as the test's error. :param short_description: An optional short description of the test. """ super(ErrorHolder, self).__init__( test_id, short_description=short_description) self._error = error def __repr__(self): internal = [self._test_id, self._error] if self._short_description is not None: internal.append(self._short_description) return "<%s.%s(%s)>" % ( self.__class__.__module__, self.__class__.__name__, ", ".join(map(repr, internal))) def run(self, result=None): if result is None: result = TestResult() result.startTest(self) result.addError(self, self._error) result.stopTest(self) # Python 2.4 did not know how to copy functions. if types.FunctionType not in copy._copy_dispatch: copy._copy_dispatch[types.FunctionType] = copy._copy_immutable def clone_test_with_new_id(test, new_id): """Copy a `TestCase`, and give the copied test a new id. This is only expected to be used on tests that have been constructed but not executed. """ newTest = copy.copy(test) newTest.id = lambda: new_id return newTest def skip(reason): """A decorator to skip unit tests. This is just syntactic sugar so users don't have to change any of their unit tests in order to migrate to python 2.7, which provides the @unittest.skip decorator. """ def decorator(test_item): if wraps is not None: @wraps(test_item) def skip_wrapper(*args, **kwargs): raise TestCase.skipException(reason) else: def skip_wrapper(test_item): test_item.skip(reason) return skip_wrapper return decorator def skipIf(condition, reason): """Skip a test if the condition is true.""" if condition: return skip(reason) def _id(obj): return obj return _id def skipUnless(condition, reason): """Skip a test unless the condition is true.""" if not condition: return skip(reason) def _id(obj): return obj return _id class ExpectedException: """A context manager to handle expected exceptions. In Python 2.5 or later:: def test_foo(self): with ExpectedException(ValueError, 'fo.*'): raise ValueError('foo') will pass. If the raised exception has a type other than the specified type, it will be re-raised. If it has a 'str()' that does not match the given regular expression, an AssertionError will be raised. If no exception is raised, an AssertionError will be raised. """ def __init__(self, exc_type, value_re): """Construct an `ExpectedException`. :param exc_type: The type of exception to expect. :param value_re: A regular expression to match against the 'str()' of the raised exception. """ self.exc_type = exc_type self.value_re = value_re def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: raise AssertionError('%s not raised.' % self.exc_type.__name__) if exc_type != self.exc_type: return False if not re.match(self.value_re, str(exc_value)): raise AssertionError('"%s" does not match "%s".' % (str(exc_value), self.value_re)) return True
gpl-2.0
nvoron23/node-gyp
gyp/pylib/gyp/generator/android.py
446
43487
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Notes: # # This generates makefiles suitable for inclusion into the Android build system # via an Android.mk file. It is based on make.py, the standard makefile # generator. # # The code below generates a separate .mk file for each target, but # all are sourced by the top-level GypAndroid.mk. This means that all # variables in .mk-files clobber one another, and furthermore that any # variables set potentially clash with other Android build system variables. # Try to avoid setting global variables where possible. import gyp import gyp.common import gyp.generator.make as make # Reuse global functions from make backend. import os import re import subprocess generator_default_variables = { 'OS': 'android', 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'SHARED_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'SHARED_LIB_SUFFIX': '.so', 'INTERMEDIATE_DIR': '$(gyp_intermediate_dir)', 'SHARED_INTERMEDIATE_DIR': '$(gyp_shared_intermediate_dir)', 'PRODUCT_DIR': '$(gyp_shared_intermediate_dir)', 'SHARED_LIB_DIR': '$(builddir)/lib.$(TOOLSET)', 'LIB_DIR': '$(obj).$(TOOLSET)', 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python. 'RULE_INPUT_DIRNAME': '%(INPUT_DIRNAME)s', # This gets expanded by Python. 'RULE_INPUT_PATH': '$(RULE_SOURCES)', 'RULE_INPUT_EXT': '$(suffix $<)', 'RULE_INPUT_NAME': '$(notdir $<)', 'CONFIGURATION_NAME': '$(GYP_CONFIGURATION)', } # Make supports multiple toolsets generator_supports_multiple_toolsets = True # Generator-specific gyp specs. generator_additional_non_configuration_keys = [ # Boolean to declare that this target does not want its name mangled. 'android_unmangled_name', ] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] SHARED_FOOTER = """\ # "gyp_all_modules" is a concatenation of the "gyp_all_modules" targets from # all the included sub-makefiles. This is just here to clarify. gyp_all_modules: """ header = """\ # This file is generated by gyp; do not edit. """ android_standard_include_paths = set([ # JNI_H_INCLUDE in build/core/binary.mk 'dalvik/libnativehelper/include/nativehelper', # from SRC_HEADERS in build/core/config.mk 'system/core/include', 'hardware/libhardware/include', 'hardware/libhardware_legacy/include', 'hardware/ril/include', 'dalvik/libnativehelper/include', 'frameworks/native/include', 'frameworks/native/opengl/include', 'frameworks/base/include', 'frameworks/base/opengl/include', 'frameworks/base/native/include', 'external/skia/include', # TARGET_C_INCLUDES in build/core/combo/TARGET_linux-arm.mk 'bionic/libc/arch-arm/include', 'bionic/libc/include', 'bionic/libstdc++/include', 'bionic/libc/kernel/common', 'bionic/libc/kernel/arch-arm', 'bionic/libm/include', 'bionic/libm/include/arm', 'bionic/libthread_db/include', ]) # Map gyp target types to Android module classes. MODULE_CLASSES = { 'static_library': 'STATIC_LIBRARIES', 'shared_library': 'SHARED_LIBRARIES', 'executable': 'EXECUTABLES', } def IsCPPExtension(ext): return make.COMPILABLE_EXTENSIONS.get(ext) == 'cxx' def Sourceify(path): """Convert a path to its source directory form. The Android backend does not support options.generator_output, so this function is a noop.""" return path # Map from qualified target to path to output. # For Android, the target of these maps is a tuple ('static', 'modulename'), # ('dynamic', 'modulename'), or ('path', 'some/path') instead of a string, # since we link by module. target_outputs = {} # Map from qualified target to any linkable output. A subset # of target_outputs. E.g. when mybinary depends on liba, we want to # include liba in the linker line; when otherbinary depends on # mybinary, we just want to build mybinary first. target_link_deps = {} class AndroidMkWriter(object): """AndroidMkWriter packages up the writing of one target-specific Android.mk. Its only real entry point is Write(), and is mostly used for namespacing. """ def __init__(self, android_top_dir): self.android_top_dir = android_top_dir def Write(self, qualified_target, relative_target, base_path, output_filename, spec, configs, part_of_all): """The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating relative_target: qualified target name relative to the root base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all' """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, 'w') self.fp.write(header) self.qualified_target = qualified_target self.relative_target = relative_target self.path = base_path self.target = spec['target_name'] self.type = spec['type'] self.toolset = spec['toolset'] deps, link_deps = self.ComputeDeps(spec) # Some of the generation below can add extra output, sources, or # link dependencies. All of the out params of the functions that # follow use names like extra_foo. extra_outputs = [] extra_sources = [] self.android_class = MODULE_CLASSES.get(self.type, 'GYP') self.android_module = self.ComputeAndroidModule(spec) (self.android_stem, self.android_suffix) = self.ComputeOutputParts(spec) self.output = self.output_binary = self.ComputeOutput(spec) # Standard header. self.WriteLn('include $(CLEAR_VARS)\n') # Module class and name. self.WriteLn('LOCAL_MODULE_CLASS := ' + self.android_class) self.WriteLn('LOCAL_MODULE := ' + self.android_module) # Only emit LOCAL_MODULE_STEM if it's different to LOCAL_MODULE. # The library module classes fail if the stem is set. ComputeOutputParts # makes sure that stem == modulename in these cases. if self.android_stem != self.android_module: self.WriteLn('LOCAL_MODULE_STEM := ' + self.android_stem) self.WriteLn('LOCAL_MODULE_SUFFIX := ' + self.android_suffix) self.WriteLn('LOCAL_MODULE_TAGS := optional') if self.toolset == 'host': self.WriteLn('LOCAL_IS_HOST_MODULE := true') # Grab output directories; needed for Actions and Rules. self.WriteLn('gyp_intermediate_dir := $(call local-intermediates-dir)') self.WriteLn('gyp_shared_intermediate_dir := ' '$(call intermediates-dir-for,GYP,shared)') self.WriteLn() # List files this target depends on so that actions/rules/copies/sources # can depend on the list. # TODO: doesn't pull in things through transitive link deps; needed? target_dependencies = [x[1] for x in deps if x[0] == 'path'] self.WriteLn('# Make sure our deps are built first.') self.WriteList(target_dependencies, 'GYP_TARGET_DEPENDENCIES', local_pathify=True) # Actions must come first, since they can generate more OBJs for use below. if 'actions' in spec: self.WriteActions(spec['actions'], extra_sources, extra_outputs) # Rules must be early like actions. if 'rules' in spec: self.WriteRules(spec['rules'], extra_sources, extra_outputs) if 'copies' in spec: self.WriteCopies(spec['copies'], extra_outputs) # GYP generated outputs. self.WriteList(extra_outputs, 'GYP_GENERATED_OUTPUTS', local_pathify=True) # Set LOCAL_ADDITIONAL_DEPENDENCIES so that Android's build rules depend # on both our dependency targets and our generated files. self.WriteLn('# Make sure our deps and generated files are built first.') self.WriteLn('LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) ' '$(GYP_GENERATED_OUTPUTS)') self.WriteLn() # Sources. if spec.get('sources', []) or extra_sources: self.WriteSources(spec, configs, extra_sources) self.WriteTarget(spec, configs, deps, link_deps, part_of_all) # Update global list of target outputs, used in dependency tracking. target_outputs[qualified_target] = ('path', self.output_binary) # Update global list of link dependencies. if self.type == 'static_library': target_link_deps[qualified_target] = ('static', self.android_module) elif self.type == 'shared_library': target_link_deps[qualified_target] = ('shared', self.android_module) self.fp.close() return self.android_module def WriteActions(self, actions, extra_sources, extra_outputs): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) """ for action in actions: name = make.StringToMakefileVariable('%s_%s' % (self.relative_target, action['action_name'])) self.WriteLn('### Rules for action "%s":' % action['action_name']) inputs = action['inputs'] outputs = action['outputs'] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: if not out.startswith('$'): print ('WARNING: Action for target "%s" writes output to local path ' '"%s".' % (self.target, out)) dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get('process_outputs_as_sources', False)): extra_sources += outputs # Prepare the actual command. command = gyp.common.EncodePOSIXShellList(action['action']) if 'message' in action: quiet_cmd = 'Gyp action: %s ($@)' % action['message'] else: quiet_cmd = 'Gyp action: %s ($@)' % name if len(dirs) > 0: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command cd_action = 'cd $(gyp_local_path)/%s; ' % self.path command = cd_action + command # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the gyp_* # variables for the action rule with an absolute version so that the # output goes in the right place. # Only write the gyp_* rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. main_output = make.QuoteSpaces(self.LocalPathify(outputs[0])) self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output) self.WriteLn('%s: gyp_intermediate_dir := ' '$(abspath $(gyp_intermediate_dir))' % main_output) self.WriteLn('%s: gyp_shared_intermediate_dir := ' '$(abspath $(gyp_shared_intermediate_dir))' % main_output) # Android's envsetup.sh adds a number of directories to the path including # the built host binary directory. This causes actions/rules invoked by # gyp to sometimes use these instead of system versions, e.g. bison. # The built host binaries may not be suitable, and can cause errors. # So, we remove them from the PATH using the ANDROID_BUILD_PATHS variable # set by envsetup. self.WriteLn('%s: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))' % main_output) for input in inputs: assert ' ' not in input, ( "Spaces in action input filenames not supported (%s)" % input) for output in outputs: assert ' ' not in output, ( "Spaces in action output filenames not supported (%s)" % output) self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' % (main_output, ' '.join(map(self.LocalPathify, inputs)))) self.WriteLn('\t@echo "%s"' % quiet_cmd) self.WriteLn('\t$(hide)%s\n' % command) for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. self.WriteLn('%s: %s ;' % (self.LocalPathify(output), main_output)) extra_outputs += outputs self.WriteLn() self.WriteLn() def WriteRules(self, rules, extra_sources, extra_outputs): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) """ if len(rules) == 0: return rule_trigger = '%s_rule_trigger' % self.android_module did_write_rule = False for rule in rules: if len(rule.get('rule_sources', [])) == 0: continue did_write_rule = True name = make.StringToMakefileVariable('%s_%s' % (self.relative_target, rule['rule_name'])) self.WriteLn('\n### Generated for rule "%s":' % name) self.WriteLn('# "%s":' % rule) inputs = rule.get('inputs') for rule_source in rule.get('rule_sources', []): (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = \ os.path.splitext(rule_source_basename) outputs = [self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule['outputs']] dirs = set() for out in outputs: if not out.startswith('$'): print ('WARNING: Rule for target %s writes output to local path %s' % (self.target, out)) dir = os.path.dirname(out) if dir: dirs.add(dir) extra_outputs += outputs if int(rule.get('process_outputs_as_sources', False)): extra_sources.extend(outputs) components = [] for component in rule['action']: component = self.ExpandInputRoot(component, rule_source_root, rule_source_dirname) if '$(RULE_SOURCES)' in component: component = component.replace('$(RULE_SOURCES)', rule_source) components.append(component) command = gyp.common.EncodePOSIXShellList(components) cd_action = 'cd $(gyp_local_path)/%s; ' % self.path command = cd_action + command if dirs: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command # We set up a rule to build the first output, and then set up # a rule for each additional output to depend on the first. outputs = map(self.LocalPathify, outputs) main_output = outputs[0] self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output) self.WriteLn('%s: gyp_intermediate_dir := ' '$(abspath $(gyp_intermediate_dir))' % main_output) self.WriteLn('%s: gyp_shared_intermediate_dir := ' '$(abspath $(gyp_shared_intermediate_dir))' % main_output) # See explanation in WriteActions. self.WriteLn('%s: export PATH := ' '$(subst $(ANDROID_BUILD_PATHS),,$(PATH))' % main_output) main_output_deps = self.LocalPathify(rule_source) if inputs: main_output_deps += ' ' main_output_deps += ' '.join([self.LocalPathify(f) for f in inputs]) self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' % (main_output, main_output_deps)) self.WriteLn('\t%s\n' % command) for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. self.WriteLn('%s: %s ;' % (output, main_output)) self.WriteLn('.PHONY: %s' % (rule_trigger)) self.WriteLn('%s: %s' % (rule_trigger, main_output)) self.WriteLn('') if did_write_rule: extra_sources.append(rule_trigger) # Force all rules to run. self.WriteLn('### Finished generating for all rules') self.WriteLn('') def WriteCopies(self, copies, extra_outputs): """Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) """ self.WriteLn('### Generated for copy rule.') variable = make.StringToMakefileVariable(self.relative_target + '_copies') outputs = [] for copy in copies: for path in copy['files']: # The Android build system does not allow generation of files into the # source tree. The destination should start with a variable, which will # typically be $(gyp_intermediate_dir) or # $(gyp_shared_intermediate_dir). Note that we can't use an assertion # because some of the gyp tests depend on this. if not copy['destination'].startswith('$'): print ('WARNING: Copy rule for target %s writes output to ' 'local path %s' % (self.target, copy['destination'])) # LocalPathify() calls normpath, stripping trailing slashes. path = Sourceify(self.LocalPathify(path)) filename = os.path.split(path)[1] output = Sourceify(self.LocalPathify(os.path.join(copy['destination'], filename))) self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES) | $(ACP)' % (output, path)) self.WriteLn('\t@echo Copying: $@') self.WriteLn('\t$(hide) mkdir -p $(dir $@)') self.WriteLn('\t$(hide) $(ACP) -rpf $< $@') self.WriteLn() outputs.append(output) self.WriteLn('%s = %s' % (variable, ' '.join(map(make.QuoteSpaces, outputs)))) extra_outputs.append('$(%s)' % variable) self.WriteLn() def WriteSourceFlags(self, spec, configs): """Write out the flags and include paths used to compile source files for the current target. Args: spec, configs: input from gyp. """ for configname, config in sorted(configs.iteritems()): extracted_includes = [] self.WriteLn('\n# Flags passed to both C and C++ files.') cflags, includes_from_cflags = self.ExtractIncludesFromCFlags( config.get('cflags', []) + config.get('cflags_c', [])) extracted_includes.extend(includes_from_cflags) self.WriteList(cflags, 'MY_CFLAGS_%s' % configname) self.WriteList(config.get('defines'), 'MY_DEFS_%s' % configname, prefix='-D', quoter=make.EscapeCppDefine) self.WriteLn('\n# Include paths placed before CFLAGS/CPPFLAGS') includes = list(config.get('include_dirs', [])) includes.extend(extracted_includes) includes = map(Sourceify, map(self.LocalPathify, includes)) includes = self.NormalizeIncludePaths(includes) self.WriteList(includes, 'LOCAL_C_INCLUDES_%s' % configname) self.WriteLn('\n# Flags passed to only C++ (and not C) files.') self.WriteList(config.get('cflags_cc'), 'LOCAL_CPPFLAGS_%s' % configname) self.WriteLn('\nLOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) ' '$(MY_DEFS_$(GYP_CONFIGURATION))') # Undefine ANDROID for host modules # TODO: the source code should not use macro ANDROID to tell if it's host # or target module. if self.toolset == 'host': self.WriteLn('# Undefine ANDROID for host modules') self.WriteLn('LOCAL_CFLAGS += -UANDROID') self.WriteLn('LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) ' '$(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))') self.WriteLn('LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))') def WriteSources(self, spec, configs, extra_sources): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. We need to handle shared_intermediate directory source files as a special case by copying them to the intermediate directory and treating them as a genereated sources. Otherwise the Android build rules won't pick them up. Args: spec, configs: input from gyp. extra_sources: Sources generated from Actions or Rules. """ sources = filter(make.Compilable, spec.get('sources', [])) generated_not_sources = [x for x in extra_sources if not make.Compilable(x)] extra_sources = filter(make.Compilable, extra_sources) # Determine and output the C++ extension used by these sources. # We simply find the first C++ file and use that extension. all_sources = sources + extra_sources local_cpp_extension = '.cpp' for source in all_sources: (root, ext) = os.path.splitext(source) if IsCPPExtension(ext): local_cpp_extension = ext break if local_cpp_extension != '.cpp': self.WriteLn('LOCAL_CPP_EXTENSION := %s' % local_cpp_extension) # We need to move any non-generated sources that are coming from the # shared intermediate directory out of LOCAL_SRC_FILES and put them # into LOCAL_GENERATED_SOURCES. We also need to move over any C++ files # that don't match our local_cpp_extension, since Android will only # generate Makefile rules for a single LOCAL_CPP_EXTENSION. local_files = [] for source in sources: (root, ext) = os.path.splitext(source) if '$(gyp_shared_intermediate_dir)' in source: extra_sources.append(source) elif '$(gyp_intermediate_dir)' in source: extra_sources.append(source) elif IsCPPExtension(ext) and ext != local_cpp_extension: extra_sources.append(source) else: local_files.append(os.path.normpath(os.path.join(self.path, source))) # For any generated source, if it is coming from the shared intermediate # directory then we add a Make rule to copy them to the local intermediate # directory first. This is because the Android LOCAL_GENERATED_SOURCES # must be in the local module intermediate directory for the compile rules # to work properly. If the file has the wrong C++ extension, then we add # a rule to copy that to intermediates and use the new version. final_generated_sources = [] # If a source file gets copied, we still need to add the orginal source # directory as header search path, for GCC searches headers in the # directory that contains the source file by default. origin_src_dirs = [] for source in extra_sources: local_file = source if not '$(gyp_intermediate_dir)/' in local_file: basename = os.path.basename(local_file) local_file = '$(gyp_intermediate_dir)/' + basename (root, ext) = os.path.splitext(local_file) if IsCPPExtension(ext) and ext != local_cpp_extension: local_file = root + local_cpp_extension if local_file != source: self.WriteLn('%s: %s' % (local_file, self.LocalPathify(source))) self.WriteLn('\tmkdir -p $(@D); cp $< $@') origin_src_dirs.append(os.path.dirname(source)) final_generated_sources.append(local_file) # We add back in all of the non-compilable stuff to make sure that the # make rules have dependencies on them. final_generated_sources.extend(generated_not_sources) self.WriteList(final_generated_sources, 'LOCAL_GENERATED_SOURCES') origin_src_dirs = gyp.common.uniquer(origin_src_dirs) origin_src_dirs = map(Sourceify, map(self.LocalPathify, origin_src_dirs)) self.WriteList(origin_src_dirs, 'GYP_COPIED_SOURCE_ORIGIN_DIRS') self.WriteList(local_files, 'LOCAL_SRC_FILES') # Write out the flags used to compile the source; this must be done last # so that GYP_COPIED_SOURCE_ORIGIN_DIRS can be used as an include path. self.WriteSourceFlags(spec, configs) def ComputeAndroidModule(self, spec): """Return the Android module name used for a gyp spec. We use the complete qualified target name to avoid collisions between duplicate targets in different directories. We also add a suffix to distinguish gyp-generated module names. """ if int(spec.get('android_unmangled_name', 0)): assert self.type != 'shared_library' or self.target.startswith('lib') return self.target if self.type == 'shared_library': # For reasons of convention, the Android build system requires that all # shared library modules are named 'libfoo' when generating -l flags. prefix = 'lib_' else: prefix = '' if spec['toolset'] == 'host': suffix = '_host_gyp' else: suffix = '_gyp' if self.path: name = '%s%s_%s%s' % (prefix, self.path, self.target, suffix) else: name = '%s%s%s' % (prefix, self.target, suffix) return make.StringToMakefileVariable(name) def ComputeOutputParts(self, spec): """Return the 'output basename' of a gyp spec, split into filename + ext. Android libraries must be named the same thing as their module name, otherwise the linker can't find them, so product_name and so on must be ignored if we are building a library, and the "lib" prepending is not done for Android. """ assert self.type != 'loadable_module' # TODO: not supported? target = spec['target_name'] target_prefix = '' target_ext = '' if self.type == 'static_library': target = self.ComputeAndroidModule(spec) target_ext = '.a' elif self.type == 'shared_library': target = self.ComputeAndroidModule(spec) target_ext = '.so' elif self.type == 'none': target_ext = '.stamp' elif self.type != 'executable': print ("ERROR: What output file should be generated?", "type", self.type, "target", target) if self.type != 'static_library' and self.type != 'shared_library': target_prefix = spec.get('product_prefix', target_prefix) target = spec.get('product_name', target) product_ext = spec.get('product_extension') if product_ext: target_ext = '.' + product_ext target_stem = target_prefix + target return (target_stem, target_ext) def ComputeOutputBasename(self, spec): """Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so' """ return ''.join(self.ComputeOutputParts(spec)) def ComputeOutput(self, spec): """Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so' """ if self.type == 'executable' and self.toolset == 'host': # We install host executables into shared_intermediate_dir so they can be # run by gyp rules that refer to PRODUCT_DIR. path = '$(gyp_shared_intermediate_dir)' elif self.type == 'shared_library': if self.toolset == 'host': path = '$(HOST_OUT_INTERMEDIATE_LIBRARIES)' else: path = '$(TARGET_OUT_INTERMEDIATE_LIBRARIES)' else: # Other targets just get built into their intermediate dir. if self.toolset == 'host': path = '$(call intermediates-dir-for,%s,%s,true)' % (self.android_class, self.android_module) else: path = '$(call intermediates-dir-for,%s,%s)' % (self.android_class, self.android_module) assert spec.get('product_dir') is None # TODO: not supported? return os.path.join(path, self.ComputeOutputBasename(spec)) def NormalizeIncludePaths(self, include_paths): """ Normalize include_paths. Convert absolute paths to relative to the Android top directory; filter out include paths that are already brought in by the Android build system. Args: include_paths: A list of unprocessed include paths. Returns: A list of normalized include paths. """ normalized = [] for path in include_paths: if path[0] == '/': path = gyp.common.RelativePath(path, self.android_top_dir) # Filter out the Android standard search path. if path not in android_standard_include_paths: normalized.append(path) return normalized def ExtractIncludesFromCFlags(self, cflags): """Extract includes "-I..." out from cflags Args: cflags: A list of compiler flags, which may be mixed with "-I.." Returns: A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed. """ clean_cflags = [] include_paths = [] for flag in cflags: if flag.startswith('-I'): include_paths.append(flag[2:]) else: clean_cflags.append(flag) return (clean_cflags, include_paths) def ComputeAndroidLibraryModuleNames(self, libraries): """Compute the Android module names from libraries, ie spec.get('libraries') Args: libraries: the value of spec.get('libraries') Returns: A tuple (static_lib_modules, dynamic_lib_modules) """ static_lib_modules = [] dynamic_lib_modules = [] for libs in libraries: # Libs can have multiple words. for lib in libs.split(): # Filter the system libraries, which are added by default by the Android # build system. if (lib == '-lc' or lib == '-lstdc++' or lib == '-lm' or lib.endswith('libgcc.a')): continue match = re.search(r'([^/]+)\.a$', lib) if match: static_lib_modules.append(match.group(1)) continue match = re.search(r'([^/]+)\.so$', lib) if match: dynamic_lib_modules.append(match.group(1)) continue # "-lstlport" -> libstlport if lib.startswith('-l'): if lib.endswith('_static'): static_lib_modules.append('lib' + lib[2:]) else: dynamic_lib_modules.append('lib' + lib[2:]) return (static_lib_modules, dynamic_lib_modules) def ComputeDeps(self, spec): """Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps). """ deps = [] link_deps = [] if 'dependencies' in spec: deps.extend([target_outputs[dep] for dep in spec['dependencies'] if target_outputs[dep]]) for dep in spec['dependencies']: if dep in target_link_deps: link_deps.append(target_link_deps[dep]) deps.extend(link_deps) return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps)) def WriteTargetFlags(self, spec, configs, link_deps): """Write Makefile code to specify the link flags and library dependencies. spec, configs: input from gyp. link_deps: link dependency list; see ComputeDeps() """ for configname, config in sorted(configs.iteritems()): ldflags = list(config.get('ldflags', [])) self.WriteLn('') self.WriteList(ldflags, 'LOCAL_LDFLAGS_%s' % configname) self.WriteLn('\nLOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))') # Libraries (i.e. -lfoo) libraries = gyp.common.uniquer(spec.get('libraries', [])) static_libs, dynamic_libs = self.ComputeAndroidLibraryModuleNames( libraries) # Link dependencies (i.e. libfoo.a, libfoo.so) static_link_deps = [x[1] for x in link_deps if x[0] == 'static'] shared_link_deps = [x[1] for x in link_deps if x[0] == 'shared'] self.WriteLn('') self.WriteList(static_libs + static_link_deps, 'LOCAL_STATIC_LIBRARIES') self.WriteLn('# Enable grouping to fix circular references') self.WriteLn('LOCAL_GROUP_STATIC_LIBRARIES := true') self.WriteLn('') self.WriteList(dynamic_libs + shared_link_deps, 'LOCAL_SHARED_LIBRARIES') def WriteTarget(self, spec, configs, deps, link_deps, part_of_all): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() part_of_all: flag indicating this target is part of 'all' """ self.WriteLn('### Rules for final target.') if self.type != 'none': self.WriteTargetFlags(spec, configs, link_deps) # Add to the set of targets which represent the gyp 'all' target. We use the # name 'gyp_all_modules' as the Android build system doesn't allow the use # of the Make target 'all' and because 'all_modules' is the equivalent of # the Make target 'all' on Android. if part_of_all: self.WriteLn('# Add target alias to "gyp_all_modules" target.') self.WriteLn('.PHONY: gyp_all_modules') self.WriteLn('gyp_all_modules: %s' % self.android_module) self.WriteLn('') # Add an alias from the gyp target name to the Android module name. This # simplifies manual builds of the target, and is required by the test # framework. if self.target != self.android_module: self.WriteLn('# Alias gyp target name.') self.WriteLn('.PHONY: %s' % self.target) self.WriteLn('%s: %s' % (self.target, self.android_module)) self.WriteLn('') # Add the command to trigger build of the target type depending # on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY # NOTE: This has to come last! modifier = '' if self.toolset == 'host': modifier = 'HOST_' if self.type == 'static_library': self.WriteLn('include $(BUILD_%sSTATIC_LIBRARY)' % modifier) elif self.type == 'shared_library': self.WriteLn('LOCAL_PRELINK_MODULE := false') self.WriteLn('include $(BUILD_%sSHARED_LIBRARY)' % modifier) elif self.type == 'executable': if self.toolset == 'host': self.WriteLn('LOCAL_MODULE_PATH := $(gyp_shared_intermediate_dir)') else: # Don't install target executables for now, as it results in them being # included in ROM. This can be revisited if there's a reason to install # them later. self.WriteLn('LOCAL_UNINSTALLABLE_MODULE := true') self.WriteLn('include $(BUILD_%sEXECUTABLE)' % modifier) else: self.WriteLn('LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp') self.WriteLn('LOCAL_UNINSTALLABLE_MODULE := true') self.WriteLn() self.WriteLn('include $(BUILD_SYSTEM)/base_rules.mk') self.WriteLn() self.WriteLn('$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)') self.WriteLn('\t$(hide) echo "Gyp timestamp: $@"') self.WriteLn('\t$(hide) mkdir -p $(dir $@)') self.WriteLn('\t$(hide) touch $@') def WriteList(self, value_list, variable=None, prefix='', quoter=make.QuoteIfNecessary, local_pathify=False): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = '' if value_list: value_list = [quoter(prefix + l) for l in value_list] if local_pathify: value_list = [self.LocalPathify(l) for l in value_list] values = ' \\\n\t' + ' \\\n\t'.join(value_list) self.fp.write('%s :=%s\n\n' % (variable, values)) def WriteLn(self, text=''): self.fp.write(text + '\n') def LocalPathify(self, path): """Convert a subdirectory-relative path into a normalized path which starts with the make variable $(LOCAL_PATH) (i.e. the top of the project tree). Absolute paths, or paths that contain variables, are just normalized.""" if '$(' in path or os.path.isabs(path): # path is not a file in the project tree in this case, but calling # normpath is still important for trimming trailing slashes. return os.path.normpath(path) local_path = os.path.join('$(LOCAL_PATH)', self.path, path) local_path = os.path.normpath(local_path) # Check that normalizing the path didn't ../ itself out of $(LOCAL_PATH) # - i.e. that the resulting path is still inside the project tree. The # path may legitimately have ended up containing just $(LOCAL_PATH), though, # so we don't look for a slash. assert local_path.startswith('$(LOCAL_PATH)'), ( 'Path %s attempts to escape from gyp path %s !)' % (path, self.path)) return local_path def ExpandInputRoot(self, template, expansion, dirname): if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template: return template path = template % { 'INPUT_ROOT': expansion, 'INPUT_DIRNAME': dirname, } return path def PerformBuild(data, configurations, params): # The android backend only supports the default configuration. options = params['options'] makefile = os.path.abspath(os.path.join(options.toplevel_dir, 'GypAndroid.mk')) env = dict(os.environ) env['ONE_SHOT_MAKEFILE'] = makefile arguments = ['make', '-C', os.environ['ANDROID_BUILD_TOP'], 'gyp_all_modules'] print 'Building: %s' % arguments subprocess.check_call(arguments, env=env) def GenerateOutput(target_list, target_dicts, data, params): options = params['options'] generator_flags = params.get('generator_flags', {}) builddir_name = generator_flags.get('output_dir', 'out') limit_to_target_all = generator_flags.get('limit_to_target_all', False) android_top_dir = os.environ.get('ANDROID_BUILD_TOP') assert android_top_dir, '$ANDROID_BUILD_TOP not set; you need to run lunch.' def CalculateMakefilePath(build_file, base_name): """Determine where to write a Makefile for a given gyp file.""" # Paths in gyp files are relative to the .gyp file, but we want # paths relative to the source root for the master makefile. Grab # the path of the .gyp file as the base to relativize against. # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp". base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.depth) # We write the file in the base_path directory. output_file = os.path.join(options.depth, base_path, base_name) assert not options.generator_output, ( 'The Android backend does not support options.generator_output.') base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.toplevel_dir) return base_path, output_file # TODO: search for the first non-'Default' target. This can go # away when we add verification that all targets have the # necessary configurations. default_configuration = None toolsets = set([target_dicts[target]['toolset'] for target in target_list]) for target in target_list: spec = target_dicts[target] if spec['default_configuration'] != 'Default': default_configuration = spec['default_configuration'] break if not default_configuration: default_configuration = 'Default' srcdir = '.' makefile_name = 'GypAndroid' + options.suffix + '.mk' makefile_path = os.path.join(options.toplevel_dir, makefile_name) assert not options.generator_output, ( 'The Android backend does not support options.generator_output.') gyp.common.EnsureDirExists(makefile_path) root_makefile = open(makefile_path, 'w') root_makefile.write(header) # We set LOCAL_PATH just once, here, to the top of the project tree. This # allows all the other paths we use to be relative to the Android.mk file, # as the Android build system expects. root_makefile.write('\nLOCAL_PATH := $(call my-dir)\n') # Find the list of targets that derive from the gyp file(s) being built. needed_targets = set() for build_file in params['build_files']: for target in gyp.common.AllTargets(target_list, target_dicts, build_file): needed_targets.add(target) build_files = set() include_list = set() android_modules = {} for qualified_target in target_list: build_file, target, toolset = gyp.common.ParseQualifiedTarget( qualified_target) relative_build_file = gyp.common.RelativePath(build_file, options.toplevel_dir) build_files.add(relative_build_file) included_files = data[build_file]['included_files'] for included_file in included_files: # The included_files entries are relative to the dir of the build file # that included them, so we have to undo that and then make them relative # to the root dir. relative_include_file = gyp.common.RelativePath( gyp.common.UnrelativePath(included_file, build_file), options.toplevel_dir) abs_include_file = os.path.abspath(relative_include_file) # If the include file is from the ~/.gyp dir, we should use absolute path # so that relocating the src dir doesn't break the path. if (params['home_dot_gyp'] and abs_include_file.startswith(params['home_dot_gyp'])): build_files.add(abs_include_file) else: build_files.add(relative_include_file) base_path, output_file = CalculateMakefilePath(build_file, target + '.' + toolset + options.suffix + '.mk') spec = target_dicts[qualified_target] configs = spec['configurations'] part_of_all = (qualified_target in needed_targets and not int(spec.get('suppress_wildcard', False))) if limit_to_target_all and not part_of_all: continue relative_target = gyp.common.QualifiedTarget(relative_build_file, target, toolset) writer = AndroidMkWriter(android_top_dir) android_module = writer.Write(qualified_target, relative_target, base_path, output_file, spec, configs, part_of_all=part_of_all) if android_module in android_modules: print ('ERROR: Android module names must be unique. The following ' 'targets both generate Android module name %s.\n %s\n %s' % (android_module, android_modules[android_module], qualified_target)) return android_modules[android_module] = qualified_target # Our root_makefile lives at the source root. Compute the relative path # from there to the output_file for including. mkfile_rel_path = gyp.common.RelativePath(output_file, os.path.dirname(makefile_path)) include_list.add(mkfile_rel_path) root_makefile.write('GYP_CONFIGURATION ?= %s\n' % default_configuration) # Write out the sorted list of includes. root_makefile.write('\n') for include_file in sorted(include_list): root_makefile.write('include $(LOCAL_PATH)/' + include_file + '\n') root_makefile.write('\n') root_makefile.write(SHARED_FOOTER) root_makefile.close()
mit
stevenmizuno/QGIS
python/plugins/processing/algs/grass7/ext/i_pca.py
21
1257
# -*- coding: utf-8 -*- """ *************************************************************************** i_pca.py -------- Date : March 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot fr *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Médéric Ribreux' __date__ = 'March 2016' __copyright__ = '(C) 2016, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from .i import verifyRasterNum def checkParameterValuesBeforeExecuting(alg, parameters, context): return verifyRasterNum(alg, parameters, context, 'input', 2)
gpl-2.0
RalphBariz/RalphsDotNet
Old/RalphsDotNet.Apps.OptimizationStudio/Resources/PyLib/scipy/integrate/info.py
55
1259
""" Integration routines ==================== Methods for Integrating Functions given function object. quad -- General purpose integration. dblquad -- General purpose double integration. tplquad -- General purpose triple integration. fixed_quad -- Integrate func(x) using Gaussian quadrature of order n. quadrature -- Integrate with given tolerance using Gaussian quadrature. romberg -- Integrate func using Romberg integration. Methods for Integrating Functions given fixed samples. trapz -- Use trapezoidal rule to compute integral from samples. cumtrapz -- Use trapezoidal rule to cumulatively compute integral. simps -- Use Simpson's rule to compute integral from samples. romb -- Use Romberg Integration to compute integral from (2**k + 1) evenly-spaced samples. See the special module's orthogonal polynomials (special) for Gaussian quadrature roots and weights for other weighting factors and regions. Interface to numerical integrators of ODE systems. odeint -- General integration of ordinary differential equations. ode -- Integrate ODE using VODE and ZVODE routines. """ postpone_import = 1
gpl-3.0
susilehtola/psi4
tests/pytests/test_aaa_profiling.py
12
1796
import time import pytest import numpy as np import multiprocessing import psi4 # Test below is fine on its own but erratic through pytest. Most likely # to succeed as first test collected, so here it lies. @pytest.mark.xfail(True, reason='threading treatment suspect', run=True) def disabled_test_threaded_blas(): threads = multiprocessing.cpu_count() threads = int(threads / 2) times = {} size = [200, 500, 2000, 5000] threads = [1, threads] for th in threads: psi4.set_num_threads(th) for sz in size: nruns = max(1, int(1.e10 / (sz ** 3))) a = psi4.core.Matrix(sz, sz) b = psi4.core.Matrix(sz, sz) c = psi4.core.Matrix(sz, sz) tp4 = time.time() for n in range(nruns): c.gemm(False, False, 1.0, a, b, 0.0) retp4 = (time.time() - tp4) / nruns tnp = time.time() for n in range(nruns): np.dot(a, b, out=np.asarray(c)) retnp = (time.time() - tnp) / nruns print("Time for threads %2d, size %5d: Psi4: %12.6f NumPy: %12.6f" % (th, sz, retp4, retnp)) if sz == 5000: times["p4-n{}".format(th)] = retp4 times["np-n{}".format(th)] = retnp assert psi4.get_num_threads() == th rat1 = times["np-n" + str(threads[-1])] / times["p4-n" + str(threads[-1])] rat2 = times["p4-n" + str(threads[0])] / times["p4-n" + str(threads[-1])] print(" NumPy@n%d : Psi4@n%d ratio (want ~1): %.2f" % (threads[-1], threads[-1], rat1)) print(" Psi4@n%d : Psi4@n%d ratio (want ~%d): %.2f" % (threads[0], threads[-1], threads[-1], rat2)) assert pytest.approx(rat1, 0.2) == 1.0 assert pytest.approx(rat2, 0.8) == threads[-1]
lgpl-3.0
bodylabs/lace
lace/test_stl.py
1
1608
import unittest import numpy as np from bltest import attr from lace.cache import sc from lace.serialization import stl @attr('missing_assets') class TestSTL(unittest.TestCase): def setUp(self): import tempfile self.tmp_dir = tempfile.mkdtemp('bodylabs-test') self.truth = { 'box_v': np.array([[0.5, -0.5, 0.5, -0.5, 0.5, -0.5, 0.5, -0.5], [0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5], [0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5]]).T, 'box_f': np.array([[0, 1, 2], [3, 2, 1], [0, 2, 4], [6, 4, 2], [0, 4, 1], [5, 1, 4], [7, 5, 6], [4, 6, 5], [7, 6, 3], [2, 3, 6], [7, 3, 5], [1, 5, 3]]), 'box_fn': np.array([[0, 0, 1], [0, 0, 1], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, -1], [-0, -0, -1], [0, -1, 0], [-0, -1, -0], [-1, 0, 0], [-1, -0, -0]]), } # Because STL gives duplicated verts self.truth['box_v'] = self.truth['box_v'][self.truth['box_f'].flatten()] self.truth['box_f'] = np.array(range(self.truth['box_v'].shape[0])).reshape((-1, 3)) self.test_stl_url = "s3://bodylabs-korper-assets/is/ps/shared/data/body/korper_testdata/test_box.stl" self.test_stl_path = sc(self.test_stl_url) def tearDown(self): import shutil shutil.rmtree(self.tmp_dir, ignore_errors=True) def test_loads_from_local_path_using_serializer(self): m = stl.load(self.test_stl_path) np.testing.assert_array_equal(m.v, self.truth['box_v']) np.testing.assert_array_equal(m.f, self.truth['box_f']) np.testing.assert_array_equal(m.fn, self.truth['box_fn'])
bsd-2-clause
mcking49/apache-flask
Python/Lib/unittest/case.py
35
42686
"""Test case implementation""" import collections import sys import functools import difflib import pprint import re import types import warnings from . import result from .util import ( strclass, safe_repr, unorderable_list_difference, _count_diff_all_purpose, _count_diff_hashable ) __unittest = True DIFF_OMITTED = ('\nDiff is %s characters long. ' 'Set self.maxDiff to None to see it.') class SkipTest(Exception): """ Raise this exception in a test to skip it. Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly. """ pass class _ExpectedFailure(Exception): """ Raise this when a test is expected to fail. This is an implementation detail. """ def __init__(self, exc_info): super(_ExpectedFailure, self).__init__() self.exc_info = exc_info class _UnexpectedSuccess(Exception): """ The test was supposed to fail, but it didn't! """ pass def _id(obj): return obj def skip(reason): """ Unconditionally skip a test. """ def decorator(test_item): if not isinstance(test_item, (type, types.ClassType)): @functools.wraps(test_item) def skip_wrapper(*args, **kwargs): raise SkipTest(reason) test_item = skip_wrapper test_item.__unittest_skip__ = True test_item.__unittest_skip_why__ = reason return test_item return decorator def skipIf(condition, reason): """ Skip a test if the condition is true. """ if condition: return skip(reason) return _id def skipUnless(condition, reason): """ Skip a test unless the condition is true. """ if not condition: return skip(reason) return _id def expectedFailure(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: func(*args, **kwargs) except Exception: raise _ExpectedFailure(sys.exc_info()) raise _UnexpectedSuccess return wrapper class _AssertRaisesContext(object): """A context manager used to implement TestCase.assertRaises* methods.""" def __init__(self, expected, test_case, expected_regexp=None): self.expected = expected self.failureException = test_case.failureException self.expected_regexp = expected_regexp def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if exc_type is None: try: exc_name = self.expected.__name__ except AttributeError: exc_name = str(self.expected) raise self.failureException( "{0} not raised".format(exc_name)) if not issubclass(exc_type, self.expected): # let unexpected exceptions pass through return False self.exception = exc_value # store for later retrieval if self.expected_regexp is None: return True expected_regexp = self.expected_regexp if not expected_regexp.search(str(exc_value)): raise self.failureException('"%s" does not match "%s"' % (expected_regexp.pattern, str(exc_value))) return True class TestCase(object): """A class whose instances are single test cases. By default, the test code itself should be placed in a method named 'runTest'. If the fixture may be used for many test cases, create as many test methods as are needed. When instantiating such a TestCase subclass, specify in the constructor arguments the name of the test method that the instance is to execute. Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test's environment ('fixture') can be implemented by overriding the 'setUp' and 'tearDown' methods respectively. If it is necessary to override the __init__ method, the base class __init__ method must always be called. It is important that subclasses should not change the signature of their __init__ method, since instances of the classes are instantiated automatically by parts of the framework in order to be run. When subclassing TestCase, you can set these attributes: * failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'. * longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in *addition* to any explicit message passed. * maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required. """ failureException = AssertionError longMessage = False maxDiff = 80*8 # If a string is longer than _diffThreshold, use normal comparison instead # of difflib. See #11763. _diffThreshold = 2**16 # Attribute used by TestSuite for classSetUp _classSetupFailed = False def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. """ self._testMethodName = methodName self._resultForDoCleanups = None try: testMethod = getattr(self, methodName) except AttributeError: raise ValueError("no such test method in %s: %s" % (self.__class__, methodName)) self._testMethodDoc = testMethod.__doc__ self._cleanups = [] # Map types to custom assertEqual functions that will compare # instances of said type in more detail to generate a more useful # error message. self._type_equality_funcs = {} self.addTypeEqualityFunc(dict, 'assertDictEqual') self.addTypeEqualityFunc(list, 'assertListEqual') self.addTypeEqualityFunc(tuple, 'assertTupleEqual') self.addTypeEqualityFunc(set, 'assertSetEqual') self.addTypeEqualityFunc(frozenset, 'assertSetEqual') try: self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual') except NameError: # No unicode support in this build pass def addTypeEqualityFunc(self, typeobj, function): """Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages. Args: typeobj: The data type to call this function on when both values are of the same type in assertEqual(). function: The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal. """ self._type_equality_funcs[typeobj] = function def addCleanup(self, function, *args, **kwargs): """Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. Cleanup items are called even if setUp fails (unlike tearDown).""" self._cleanups.append((function, args, kwargs)) def setUp(self): "Hook method for setting up the test fixture before exercising it." pass def tearDown(self): "Hook method for deconstructing the test fixture after testing it." pass @classmethod def setUpClass(cls): "Hook method for setting up class fixture before running tests in the class." @classmethod def tearDownClass(cls): "Hook method for deconstructing the class fixture after running all tests in the class." def countTestCases(self): return 1 def defaultTestResult(self): return result.TestResult() def shortDescription(self): """Returns a one-line description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the specified test method's docstring. """ doc = self._testMethodDoc return doc and doc.split("\n")[0].strip() or None def id(self): return "%s.%s" % (strclass(self.__class__), self._testMethodName) def __eq__(self, other): if type(self) is not type(other): return NotImplemented return self._testMethodName == other._testMethodName def __ne__(self, other): return not self == other def __hash__(self): return hash((type(self), self._testMethodName)) def __str__(self): return "%s (%s)" % (self._testMethodName, strclass(self.__class__)) def __repr__(self): return "<%s testMethod=%s>" % \ (strclass(self.__class__), self._testMethodName) def _addSkip(self, result, reason): addSkip = getattr(result, 'addSkip', None) if addSkip is not None: addSkip(self, reason) else: warnings.warn("TestResult has no addSkip method, skips not reported", RuntimeWarning, 2) result.addSuccess(self) def run(self, result=None): orig_result = result if result is None: result = self.defaultTestResult() startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None: startTestRun() self._resultForDoCleanups = result result.startTest(self) testMethod = getattr(self, self._testMethodName) if (getattr(self.__class__, "__unittest_skip__", False) or getattr(testMethod, "__unittest_skip__", False)): # If the class or method was skipped. try: skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') or getattr(testMethod, '__unittest_skip_why__', '')) self._addSkip(result, skip_why) finally: result.stopTest(self) return try: success = False try: self.setUp() except SkipTest as e: self._addSkip(result, str(e)) except KeyboardInterrupt: raise except: result.addError(self, sys.exc_info()) else: try: testMethod() except KeyboardInterrupt: raise except self.failureException: result.addFailure(self, sys.exc_info()) except _ExpectedFailure as e: addExpectedFailure = getattr(result, 'addExpectedFailure', None) if addExpectedFailure is not None: addExpectedFailure(self, e.exc_info) else: warnings.warn("TestResult has no addExpectedFailure method, reporting as passes", RuntimeWarning) result.addSuccess(self) except _UnexpectedSuccess: addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None) if addUnexpectedSuccess is not None: addUnexpectedSuccess(self) else: warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures", RuntimeWarning) result.addFailure(self, sys.exc_info()) except SkipTest as e: self._addSkip(result, str(e)) except: result.addError(self, sys.exc_info()) else: success = True try: self.tearDown() except KeyboardInterrupt: raise except: result.addError(self, sys.exc_info()) success = False cleanUpSuccess = self.doCleanups() success = success and cleanUpSuccess if success: result.addSuccess(self) finally: result.stopTest(self) if orig_result is None: stopTestRun = getattr(result, 'stopTestRun', None) if stopTestRun is not None: stopTestRun() def doCleanups(self): """Execute all cleanup functions. Normally called for you after tearDown.""" result = self._resultForDoCleanups ok = True while self._cleanups: function, args, kwargs = self._cleanups.pop(-1) try: function(*args, **kwargs) except KeyboardInterrupt: raise except: ok = False result.addError(self, sys.exc_info()) return ok def __call__(self, *args, **kwds): return self.run(*args, **kwds) def debug(self): """Run the test without collecting errors in a TestResult""" self.setUp() getattr(self, self._testMethodName)() self.tearDown() while self._cleanups: function, args, kwargs = self._cleanups.pop(-1) function(*args, **kwargs) def skipTest(self, reason): """Skip this test.""" raise SkipTest(reason) def fail(self, msg=None): """Fail immediately, with the given message.""" raise self.failureException(msg) def assertFalse(self, expr, msg=None): """Check that the expression is false.""" if expr: msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr)) raise self.failureException(msg) def assertTrue(self, expr, msg=None): """Check that the expression is true.""" if not expr: msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr)) raise self.failureException(msg) def _formatMessage(self, msg, standardMsg): """Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert If longMessage is True: * Use the standard message * If an explicit message is provided, plus ' : ' and the explicit message """ if not self.longMessage: return msg or standardMsg if msg is None: return standardMsg try: # don't switch to '{}' formatting in Python 2.X # it changes the way unicode input is handled return '%s : %s' % (standardMsg, msg) except UnicodeDecodeError: return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg)) def assertRaises(self, excClass, callableObj=None, *args, **kwargs): """Fail unless an exception of class excClass is raised by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. If called with callableObj omitted or None, will return a context object used like this:: with self.assertRaises(SomeException): do_something() The context manager keeps a reference to the exception as the 'exception' attribute. This allows you to inspect the exception after the assertion:: with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3) """ context = _AssertRaisesContext(excClass, self) if callableObj is None: return context with context: callableObj(*args, **kwargs) def _getAssertEqualityFunc(self, first, second): """Get a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types. """ # # NOTE(gregory.p.smith): I considered isinstance(first, type(second)) # and vice versa. I opted for the conservative approach in case # subclasses are not intended to be compared in detail to their super # class instances using a type equality func. This means testing # subtypes won't automagically use the detailed comparison. Callers # should use their type specific assertSpamEqual method to compare # subclasses if the detailed comparison is desired and appropriate. # See the discussion in http://bugs.python.org/issue2578. # if type(first) is type(second): asserter = self._type_equality_funcs.get(type(first)) if asserter is not None: if isinstance(asserter, basestring): asserter = getattr(self, asserter) return asserter return self._baseAssertEqual def _baseAssertEqual(self, first, second, msg=None): """The default assertEqual implementation, not type specific.""" if not first == second: standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second)) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '==' operator. """ assertion_func = self._getAssertEqualityFunc(first, second) assertion_func(first, second, msg=msg) def assertNotEqual(self, first, second, msg=None): """Fail if the two objects are equal as determined by the '!=' operator. """ if not first != second: msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first), safe_repr(second))) raise self.failureException(msg) def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None): """Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). If the two objects compare equal then they will automatically compare almost equal. """ if first == second: # shortcut return if delta is not None and places is not None: raise TypeError("specify delta or places not both") if delta is not None: if abs(first - second) <= delta: return standardMsg = '%s != %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)) else: if places is None: places = 7 if round(abs(second-first), places) == 0: return standardMsg = '%s != %s within %r places' % (safe_repr(first), safe_repr(second), places) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None): """Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). Objects that are equal automatically fail. """ if delta is not None and places is not None: raise TypeError("specify delta or places not both") if delta is not None: if not (first == second) and abs(first - second) > delta: return standardMsg = '%s == %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)) else: if places is None: places = 7 if not (first == second) and round(abs(second-first), places) != 0: return standardMsg = '%s == %s within %r places' % (safe_repr(first), safe_repr(second), places) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) # Synonyms for assertion methods # The plurals are undocumented. Keep them that way to discourage use. # Do not add more. Do not remove. # Going through a deprecation cycle on these would annoy many people. assertEquals = assertEqual assertNotEquals = assertNotEqual assertAlmostEquals = assertAlmostEqual assertNotAlmostEquals = assertNotAlmostEqual assert_ = assertTrue # These fail* assertion method names are pending deprecation and will # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578 def _deprecate(original_func): def deprecated_func(*args, **kwargs): warnings.warn( 'Please use {0} instead.'.format(original_func.__name__), PendingDeprecationWarning, 2) return original_func(*args, **kwargs) return deprecated_func failUnlessEqual = _deprecate(assertEqual) failIfEqual = _deprecate(assertNotEqual) failUnlessAlmostEqual = _deprecate(assertAlmostEqual) failIfAlmostEqual = _deprecate(assertNotAlmostEqual) failUnless = _deprecate(assertTrue) failUnlessRaises = _deprecate(assertRaises) failIf = _deprecate(assertFalse) def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): """An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no datatype should be enforced. msg: Optional message to use on failure instead of a list of differences. """ if seq_type is not None: seq_type_name = seq_type.__name__ if not isinstance(seq1, seq_type): raise self.failureException('First sequence is not a %s: %s' % (seq_type_name, safe_repr(seq1))) if not isinstance(seq2, seq_type): raise self.failureException('Second sequence is not a %s: %s' % (seq_type_name, safe_repr(seq2))) else: seq_type_name = "sequence" differing = None try: len1 = len(seq1) except (TypeError, NotImplementedError): differing = 'First %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: try: len2 = len(seq2) except (TypeError, NotImplementedError): differing = 'Second %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: if seq1 == seq2: return seq1_repr = safe_repr(seq1) seq2_repr = safe_repr(seq2) if len(seq1_repr) > 30: seq1_repr = seq1_repr[:30] + '...' if len(seq2_repr) > 30: seq2_repr = seq2_repr[:30] + '...' elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr) differing = '%ss differ: %s != %s\n' % elements for i in xrange(min(len1, len2)): try: item1 = seq1[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of first %s\n' % (i, seq_type_name)) break try: item2 = seq2[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of second %s\n' % (i, seq_type_name)) break if item1 != item2: differing += ('\nFirst differing element %d:\n%s\n%s\n' % (i, item1, item2)) break else: if (len1 == len2 and seq_type is None and type(seq1) != type(seq2)): # The sequences are the same, but have differing types. return if len1 > len2: differing += ('\nFirst %s contains %d additional ' 'elements.\n' % (seq_type_name, len1 - len2)) try: differing += ('First extra element %d:\n%s\n' % (len2, seq1[len2])) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of first %s\n' % (len2, seq_type_name)) elif len1 < len2: differing += ('\nSecond %s contains %d additional ' 'elements.\n' % (seq_type_name, len2 - len1)) try: differing += ('First extra element %d:\n%s\n' % (len1, seq2[len1])) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of second %s\n' % (len1, seq_type_name)) standardMsg = differing diffMsg = '\n' + '\n'.join( difflib.ndiff(pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines())) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg) def _truncateMessage(self, message, diff): max_diff = self.maxDiff if max_diff is None or len(diff) <= max_diff: return message + diff return message + (DIFF_OMITTED % len(diff)) def assertListEqual(self, list1, list2, msg=None): """A list-specific equality assertion. Args: list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of differences. """ self.assertSequenceEqual(list1, list2, msg, seq_type=list) def assertTupleEqual(self, tuple1, tuple2, msg=None): """A tuple-specific equality assertion. Args: tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of differences. """ self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple) def assertSetEqual(self, set1, set2, msg=None): """A set-specific equality assertion. Args: set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of differences. assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method). """ try: difference1 = set1.difference(set2) except TypeError, e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError, e: self.fail('first argument does not support set difference: %s' % e) try: difference2 = set2.difference(set1) except TypeError, e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError, e: self.fail('second argument does not support set difference: %s' % e) if not (difference1 or difference2): return lines = [] if difference1: lines.append('Items in the first set but not the second:') for item in difference1: lines.append(repr(item)) if difference2: lines.append('Items in the second set but not the first:') for item in difference2: lines.append(repr(item)) standardMsg = '\n'.join(lines) self.fail(self._formatMessage(msg, standardMsg)) def assertIn(self, member, container, msg=None): """Just like self.assertTrue(a in b), but with a nicer default message.""" if member not in container: standardMsg = '%s not found in %s' % (safe_repr(member), safe_repr(container)) self.fail(self._formatMessage(msg, standardMsg)) def assertNotIn(self, member, container, msg=None): """Just like self.assertTrue(a not in b), but with a nicer default message.""" if member in container: standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), safe_repr(container)) self.fail(self._formatMessage(msg, standardMsg)) def assertIs(self, expr1, expr2, msg=None): """Just like self.assertTrue(a is b), but with a nicer default message.""" if expr1 is not expr2: standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2)) self.fail(self._formatMessage(msg, standardMsg)) def assertIsNot(self, expr1, expr2, msg=None): """Just like self.assertTrue(a is not b), but with a nicer default message.""" if expr1 is expr2: standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),) self.fail(self._formatMessage(msg, standardMsg)) def assertDictEqual(self, d1, d2, msg=None): self.assertIsInstance(d1, dict, 'First argument is not a dictionary') self.assertIsInstance(d2, dict, 'Second argument is not a dictionary') if d1 != d2: standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True)) diff = ('\n' + '\n'.join(difflib.ndiff( pprint.pformat(d1).splitlines(), pprint.pformat(d2).splitlines()))) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertDictContainsSubset(self, expected, actual, msg=None): """Checks whether actual is a superset of expected.""" missing = [] mismatched = [] for key, value in expected.iteritems(): if key not in actual: missing.append(key) elif value != actual[key]: mismatched.append('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(actual[key]))) if not (missing or mismatched): return standardMsg = '' if missing: standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in missing) if mismatched: if standardMsg: standardMsg += '; ' standardMsg += 'Mismatched values: %s' % ','.join(mismatched) self.fail(self._formatMessage(msg, standardMsg)) def assertItemsEqual(self, expected_seq, actual_seq, msg=None): """An unordered sequence specific comparison. It asserts that actual_seq and expected_seq have the same element counts. Equivalent to:: self.assertEqual(Counter(iter(actual_seq)), Counter(iter(expected_seq))) Asserts that each element has the same count in both sequences. Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. """ first_seq, second_seq = list(expected_seq), list(actual_seq) with warnings.catch_warnings(): if sys.py3kwarning: # Silence Py3k warning raised during the sorting for _msg in ["(code|dict|type) inequality comparisons", "builtin_function_or_method order comparisons", "comparing unequal types"]: warnings.filterwarnings("ignore", _msg, DeprecationWarning) try: first = collections.Counter(first_seq) second = collections.Counter(second_seq) except TypeError: # Handle case with unhashable elements differences = _count_diff_all_purpose(first_seq, second_seq) else: if first == second: return differences = _count_diff_hashable(first_seq, second_seq) if differences: standardMsg = 'Element counts were not equal:\n' lines = ['First has %d, Second has %d: %r' % diff for diff in differences] diffMsg = '\n'.join(lines) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg) def assertMultiLineEqual(self, first, second, msg=None): """Assert that two multi-line strings are equal.""" self.assertIsInstance(first, basestring, 'First argument is not a string') self.assertIsInstance(second, basestring, 'Second argument is not a string') if first != second: # don't use difflib if the strings are too long if (len(first) > self._diffThreshold or len(second) > self._diffThreshold): self._baseAssertEqual(first, second, msg) firstlines = first.splitlines(True) secondlines = second.splitlines(True) if len(firstlines) == 1 and first.strip('\r\n') == first: firstlines = [first + '\n'] secondlines = [second + '\n'] standardMsg = '%s != %s' % (safe_repr(first, True), safe_repr(second, True)) diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines)) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertLess(self, a, b, msg=None): """Just like self.assertTrue(a < b), but with a nicer default message.""" if not a < b: standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertLessEqual(self, a, b, msg=None): """Just like self.assertTrue(a <= b), but with a nicer default message.""" if not a <= b: standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertGreater(self, a, b, msg=None): """Just like self.assertTrue(a > b), but with a nicer default message.""" if not a > b: standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertGreaterEqual(self, a, b, msg=None): """Just like self.assertTrue(a >= b), but with a nicer default message.""" if not a >= b: standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg)) def assertIsNone(self, obj, msg=None): """Same as self.assertTrue(obj is None), with a nicer default message.""" if obj is not None: standardMsg = '%s is not None' % (safe_repr(obj),) self.fail(self._formatMessage(msg, standardMsg)) def assertIsNotNone(self, obj, msg=None): """Included for symmetry with assertIsNone.""" if obj is None: standardMsg = 'unexpectedly None' self.fail(self._formatMessage(msg, standardMsg)) def assertIsInstance(self, obj, cls, msg=None): """Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.""" if not isinstance(obj, cls): standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls) self.fail(self._formatMessage(msg, standardMsg)) def assertNotIsInstance(self, obj, cls, msg=None): """Included for symmetry with assertIsInstance.""" if isinstance(obj, cls): standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls) self.fail(self._formatMessage(msg, standardMsg)) def assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs): """Asserts that the message in a raised exception matches a regexp. Args: expected_exception: Exception class expected to be raised. expected_regexp: Regexp (re pattern object or string) expected to be found in error message. callable_obj: Function to be called. args: Extra args. kwargs: Extra kwargs. """ if expected_regexp is not None: expected_regexp = re.compile(expected_regexp) context = _AssertRaisesContext(expected_exception, self, expected_regexp) if callable_obj is None: return context with context: callable_obj(*args, **kwargs) def assertRegexpMatches(self, text, expected_regexp, msg=None): """Fail the test unless the text matches the regular expression.""" if isinstance(expected_regexp, basestring): expected_regexp = re.compile(expected_regexp) if not expected_regexp.search(text): msg = msg or "Regexp didn't match" msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text) raise self.failureException(msg) def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None): """Fail the test if the text matches the regular expression.""" if isinstance(unexpected_regexp, basestring): unexpected_regexp = re.compile(unexpected_regexp) match = unexpected_regexp.search(text) if match: msg = msg or "Regexp matched" msg = '%s: %r matches %r in %r' % (msg, text[match.start():match.end()], unexpected_regexp.pattern, text) raise self.failureException(msg) class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the unittest framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): super(FunctionTestCase, self).__init__() self._setUpFunc = setUp self._tearDownFunc = tearDown self._testFunc = testFunc self._description = description def setUp(self): if self._setUpFunc is not None: self._setUpFunc() def tearDown(self): if self._tearDownFunc is not None: self._tearDownFunc() def runTest(self): self._testFunc() def id(self): return self._testFunc.__name__ def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self._setUpFunc == other._setUpFunc and \ self._tearDownFunc == other._tearDownFunc and \ self._testFunc == other._testFunc and \ self._description == other._description def __ne__(self, other): return not self == other def __hash__(self): return hash((type(self), self._setUpFunc, self._tearDownFunc, self._testFunc, self._description)) def __str__(self): return "%s (%s)" % (strclass(self.__class__), self._testFunc.__name__) def __repr__(self): return "<%s tec=%s>" % (strclass(self.__class__), self._testFunc) def shortDescription(self): if self._description is not None: return self._description doc = self._testFunc.__doc__ return doc and doc.split("\n")[0].strip() or None
mit
alrusdi/lettuce
tests/integration/lib/Django-1.2.5/django/contrib/gis/geometry/test_data.py
364
2994
""" This module has the mock object definitions used to hold reference geometry for the GEOS and GDAL tests. """ import gzip import os from django.contrib import gis from django.utils import simplejson # This global used to store reference geometry data. GEOMETRIES = None # Path where reference test data is located. TEST_DATA = os.path.join(os.path.dirname(gis.__file__), 'tests', 'data') def tuplize(seq): "Turn all nested sequences to tuples in given sequence." if isinstance(seq, (list, tuple)): return tuple([tuplize(i) for i in seq]) return seq def strconvert(d): "Converts all keys in dictionary to str type." return dict([(str(k), v) for k, v in d.iteritems()]) def get_ds_file(name, ext): return os.path.join(TEST_DATA, name, name + '.%s' % ext ) class TestObj(object): """ Base testing object, turns keyword args into attributes. """ def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) class TestDS(TestObj): """ Object for testing GDAL data sources. """ def __init__(self, name, **kwargs): # Shapefile is default extension, unless specified otherwise. ext = kwargs.pop('ext', 'shp') self.ds = get_ds_file(name, ext) super(TestDS, self).__init__(**kwargs) class TestGeom(TestObj): """ Testing object used for wrapping reference geometry data in GEOS/GDAL tests. """ def __init__(self, **kwargs): # Converting lists to tuples of certain keyword args # so coordinate test cases will match (JSON has no # concept of tuple). coords = kwargs.pop('coords', None) if coords: self.coords = tuplize(coords) centroid = kwargs.pop('centroid', None) if centroid: self.centroid = tuple(centroid) ext_ring_cs = kwargs.pop('ext_ring_cs', None) if ext_ring_cs: ext_ring_cs = tuplize(ext_ring_cs) self.ext_ring_cs = ext_ring_cs super(TestGeom, self).__init__(**kwargs) class TestGeomSet(object): """ Each attribute of this object is a list of `TestGeom` instances. """ def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, [TestGeom(**strconvert(kw)) for kw in value]) class TestDataMixin(object): """ Mixin used for GEOS/GDAL test cases that defines a `geometries` property, which returns and/or loads the reference geometry data. """ @property def geometries(self): global GEOMETRIES if GEOMETRIES is None: # Load up the test geometry data from fixture into global. gzf = gzip.GzipFile(os.path.join(TEST_DATA, 'geometries.json.gz')) geometries = simplejson.loads(gzf.read()) GEOMETRIES = TestGeomSet(**strconvert(geometries)) return GEOMETRIES
gpl-3.0
resmo/ansible
test/units/modules/network/fortimanager/test_fmgr_device_config.py
38
7073
# Copyright 2018 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <https://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json from ansible.module_utils.network.fortimanager.fortimanager import FortiManagerHandler import pytest try: from ansible.modules.network.fortimanager import fmgr_device_config except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) def load_fixtures(): fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') + "/{filename}.json".format( filename=os.path.splitext(os.path.basename(__file__))[0]) try: with open(fixture_path, "r") as fixture_file: fixture_data = json.load(fixture_file) except IOError: return [] return [fixture_data] @pytest.fixture(autouse=True) def module_mock(mocker): connection_class_mock = mocker.patch('ansible.module_utils.basic.AnsibleModule') return connection_class_mock @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible.modules.network.fortimanager.fmgr_device_config.Connection') return connection_class_mock @pytest.fixture(scope="function", params=load_fixtures()) def fixture_data(request): func_name = request.function.__name__.replace("test_", "") return request.param.get(func_name, None) fmg_instance = FortiManagerHandler(connection_mock, module_mock) def test_update_device_hostname(fixture_data, mocker): mocker.patch("ansible.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request", side_effect=fixture_data) # Fixture sets used:########################### ################################################## # adom: ansible # interface: None # device_unique_name: FGT1 # install_config: disable # device_hostname: ansible-fgt01 # interface_ip: None # interface_allow_access: None # mode: update ################################################## ################################################## # adom: ansible # interface: None # device_unique_name: FGT2 # install_config: disable # device_hostname: ansible-fgt02 # interface_ip: None # interface_allow_access: None # mode: update ################################################## ################################################## # adom: ansible # interface: None # device_unique_name: FGT3 # install_config: disable # device_hostname: ansible-fgt03 # interface_ip: None # interface_allow_access: None # mode: update ################################################## # Test using fixture 1 # output = fmgr_device_config.update_device_hostname(fmg_instance, fixture_data[0]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 # Test using fixture 2 # output = fmgr_device_config.update_device_hostname(fmg_instance, fixture_data[1]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 # Test using fixture 3 # output = fmgr_device_config.update_device_hostname(fmg_instance, fixture_data[2]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 def test_update_device_interface(fixture_data, mocker): mocker.patch("ansible.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request", side_effect=fixture_data) # Fixture sets used:########################### ################################################## # adom: ansible # install_config: disable # device_unique_name: FGT1 # interface: port2 # device_hostname: None # interface_ip: 10.1.1.1/24 # interface_allow_access: ping, telnet, https, http # mode: update ################################################## ################################################## # adom: ansible # install_config: disable # device_unique_name: FGT2 # interface: port2 # device_hostname: None # interface_ip: 10.1.2.1/24 # interface_allow_access: ping, telnet, https, http # mode: update ################################################## ################################################## # adom: ansible # install_config: disable # device_unique_name: FGT3 # interface: port2 # device_hostname: None # interface_ip: 10.1.3.1/24 # interface_allow_access: ping, telnet, https, http # mode: update ################################################## # Test using fixture 1 # output = fmgr_device_config.update_device_interface(fmg_instance, fixture_data[0]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 # Test using fixture 2 # output = fmgr_device_config.update_device_interface(fmg_instance, fixture_data[1]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 # Test using fixture 3 # output = fmgr_device_config.update_device_interface(fmg_instance, fixture_data[2]['paramgram_used']) assert output['raw_response']['status']['code'] == 0 def test_exec_config(fixture_data, mocker): mocker.patch("ansible.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request", side_effect=fixture_data) # Fixture sets used:########################### ################################################## # adom: ansible # interface: None # device_unique_name: FGT1 # install_config: enable # device_hostname: None # interface_ip: None # interface_allow_access: None # mode: exec ################################################## ################################################## # adom: ansible # install_config: enable # device_unique_name: FGT2, FGT3 # interface: None # device_hostname: None # interface_ip: None # interface_allow_access: None # mode: exec ################################################## # Test using fixture 1 # output = fmgr_device_config.exec_config(fmg_instance, fixture_data[0]['paramgram_used']) assert isinstance(output['raw_response'], dict) is True # Test using fixture 2 # output = fmgr_device_config.exec_config(fmg_instance, fixture_data[1]['paramgram_used']) assert isinstance(output['raw_response'], dict) is True
gpl-3.0
anthonysandrin/kafka-utils
tests/util/metadata_test.py
1
4235
# -*- coding: utf-8 -*- # Copyright 2016 Yelp Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import mock from kafka.common import PartitionMetadata from kafka_utils.util.config import ClusterConfig from kafka_utils.util.metadata import get_topic_partition_with_error from kafka_utils.util.metadata import LEADER_NOT_AVAILABLE_ERROR from kafka_utils.util.metadata import REPLICA_NOT_AVAILABLE_ERROR METADATA_RESPONSE_ALL_FINE = { 'topic0': { 0: PartitionMetadata( topic='topic0', partition=0, leader=13, replicas=(13, 100), isr=(13, 100), error=0, ), 1: PartitionMetadata( topic='topic0', partition=1, leader=100, replicas=(13, 100), isr=(13, 100), error=0, ), }, 'topic1': { 0: PartitionMetadata( topic='topic1', partition=0, leader=666, replicas=(300, 500, 666), isr=(300, 500, 666), error=0, ), 1: PartitionMetadata( topic='topic1', partition=1, leader=300, replicas=(300, 500, 666), isr=(300, 500, 666), error=0, ), }, } METADATA_RESPONSE_WITH_ERRORS = { 'topic0': { 0: PartitionMetadata( topic='topic0', partition=0, leader=13, replicas=(13, 100), isr=(13, 100), error=9, ), 1: PartitionMetadata( topic='topic0', partition=1, leader=100, replicas=(13, 100), isr=(13, 100), error=5, ), }, 'topic1': { 0: PartitionMetadata( topic='topic1', partition=0, leader=666, replicas=(300, 500, 666), isr=(300, 500, 666), error=0, ), 1: PartitionMetadata( topic='topic1', partition=1, leader=300, replicas=(300, 500, 666), isr=(300, 500, 666), error=9, ), }, } @mock.patch( 'kafka_utils.util.metadata.get_topic_partition_metadata', ) class TestMetadata(object): cluster_config = ClusterConfig( type='mytype', name='some_cluster', broker_list='some_list', zookeeper='some_ip' ) def test_get_topic_partition_metadata_empty(self, mock_get_metadata): mock_get_metadata.return_value = {} actual = get_topic_partition_with_error(self.cluster_config, 5) expected = set([]) assert actual == expected mock_get_metadata.asserd_called_wity('some_list') def test_get_topic_partition_metadata_no_errors(self, mock_get_metadata): mock_get_metadata.return_value = METADATA_RESPONSE_ALL_FINE actual = get_topic_partition_with_error(self.cluster_config, 5) expected = set([]) assert actual == expected def test_get_topic_partition_metadata_replica_not_available(self, mock_get_metadata): mock_get_metadata.return_value = METADATA_RESPONSE_WITH_ERRORS actual = get_topic_partition_with_error(self.cluster_config, REPLICA_NOT_AVAILABLE_ERROR) expected = set([('topic0', 0), ('topic1', 1)]) assert actual == expected def test_get_topic_partition_metadata_leader_not_available(self, mock_get_metadata): mock_get_metadata.return_value = METADATA_RESPONSE_WITH_ERRORS actual = get_topic_partition_with_error(self.cluster_config, LEADER_NOT_AVAILABLE_ERROR) expected = set([('topic0', 1)]) assert actual == expected
apache-2.0
teozkr/Flask-Pushrod
docs/conf.py
1
8412
# -*- coding: utf-8 -*- # # Flask-Pushrod documentation build configuration file, created by # sphinx-quickstart on Wed Oct 03 21:54:06 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.join(os.path.abspath(__file__), '..')) sys.path.append(os.path.join(os.path.abspath(__file__), '_flask_themes')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Flask-Pushrod' copyright = u'2012, Nullable' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1-dev' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'pushrod' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'index_logo': None, 'github_fork': 'dontcare4free/Flask-Pushrod', } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_flask_themes', '_themes'] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Flask-Pushroddoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Flask-Pushrod.tex', u'Flask-Pushrod Documentation', u'Nullable', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'flask-pushrod', u'Flask-Pushrod Documentation', [u'Nullable'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Flask-Pushrod', u'Flask-Pushrod Documentation', u'Nullable', 'Flask-Pushrod', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'python': ('http://docs.python.org/', None), 'flask': ('http://flask.pocoo.org/docs/', None), 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None), }
mit
spiderbit/canta-ng
event/observers/main_cube_observer.py
1
2664
#! /usr/bin/python -O # -*- coding: utf-8 -*- # # CANTA - A free entertaining educational software for singing # Copyright (C) 2007 S. Huchler, A. Kattner, F. Lopez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from event.observers.cube_observer import CubeObserver class MainCubeObserver(CubeObserver): def __init__(self, parent_world, color, min_pitch=0., max_pitch=11.): CubeObserver.__init__(self, parent_world, min_pitch, max_pitch) self.color = color def _next_line(self, song): """Draw the whole line that is selected (song.line_nr). pitch = (integer) pitch value from File words = list of SongSegments """ properties = {} line_nr = song.line_nr tone_list = song.lines[line_nr].segments self.calc_start_end_size(song) # length = len(song.lines[line_nr].segments) for word in tone_list: properties['length'] = word.duration properties['rotate'] = False # if word.special: # properties['diffuse'] = self.color['special'] # elif word.freestyle: # properties['diffuse'] = self.color['freestyle'] # else: # properties['diffuse'] = self.color['normal'] pos = tone_list.index(word) self.draw_tone(word.time_stamp, word.pitch, word.duration, properties, pos) def update(self, subject): status = subject.data['type'] if status == 'roundStart': pass elif status == 'activateNote': #if self.debug: # print subject.data['pos'] self._activate_note(subject.data['pos']) elif status == 'deActivateNote': #if self.debug: # print subject.data['old_pos'] self._de_activate_note(subject.data['old_pos']) elif status == 'nextLine': self._delete_all() self._next_line(subject.data['song']) elif status == 'end': self._end()
gpl-3.0
elin-moco/bedrock
bedrock/facebookapps/tests/__init__.py
25
3381
# -*- coding: utf-8 -*- # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import cgi import hashlib import hmac import json from base64 import urlsafe_b64encode from time import time from bedrock.mozorg import tests as mozorg_tests from nose.tools import eq_, ok_ from pyquery import PyQuery as pq DUMMY_CONTENT = 'I like pie.' DUMMY_DICT = {'pie': 'pumpkin', 'pizza': 'yes'} DUMMY_APP_DATA_QUERY = 'app_data[pie]=pumpkin&app_data[pizza]=yes' DUMMY_PATH = '/dummy-path' class TestCase(mozorg_tests.TestCase): def assert_response_redirect(self, response, url, status_code=302): eq_(response.status_code, status_code, 'Redirect response status_code' ' should be {code}. Received {bad_code}.'.format( code=status_code, bad_code=response.status_code)) ok_(response.has_header('Location'), 'No `Location` header found in ' 'response:\n\n{response}.'.format(response=response)) eq_(response['Location'], url) def assert_js_redirect(self, response, url, status_code=200, selector='#redirect', data_attr='redirect-url'): eq_(response.status_code, status_code, 'JavaScript redirect ' 'status_code should be {code}. Received {bad_code}.' .format(code=status_code, bad_code=response.status_code)) doc = pq(response.content) element = doc(selector) ok_(element, 'No element with selector `{selector}` found in response:' '\n\n{response}'.format(selector=selector, response=response.content)) escaped_url = cgi.escape(url) data_value = element.attr('data-{attr}'.format(attr=data_attr)) eq_(data_value, escaped_url, 'Attribute `data-{attr}` should be ' '{value}. Received `{bad_value}`.'.format(attr=data_attr, value=escaped_url, bad_value=data_value)) def assert_iframe_able(self, response): header = 'X-Frame-Options' self.assertFalse(response.has_header(header), '{header} header present in response.'.format(header=header)) def create_payload(user_id=None, algorithm='HMAC-SHA256', country='us', locale='en_US', app_data=None): """ Creates a signed request payload with the proper structure. Adapted from Affiliates' `facebook` app tests (http://bit.ly/11kieLq). """ payload = { 'algorithm': algorithm, 'issued_at': int(time()), 'user': { 'country': country, 'locale': locale } } if user_id: payload['user_id'] = user_id if app_data: payload['app_data'] = app_data return payload def create_signed_request(payload): """ Creates an encoded signed request like the one Facebook sends to iframe apps. Adapted from Affiliates' `facebook` app tests (http://bit.ly/XWH98V). """ payload = create_payload() if not payload else payload json_payload = json.dumps(payload) encoded_json = urlsafe_b64encode(json_payload) signature = hmac.new('APP_SECRET', encoded_json, hashlib.sha256).digest() encoded_signature = urlsafe_b64encode(signature) return '.'.join((encoded_signature, encoded_json))
mpl-2.0
pcreech/pulp_openstack
plugins/test/unit/plugins/distributors/test_configuration.py
3
3870
import os import shutil import tempfile import unittest from mock import Mock from pulp.devel.unit.server.util import assert_validation_exception from pulp.plugins.config import PluginCallConfiguration from pulp_openstack.common import constants, error_codes from pulp_openstack.plugins.distributors import configuration class TestValidateConfig(unittest.TestCase): def test_server_url_fully_qualified(self): config = { constants.CONFIG_KEY_REDIRECT_URL: 'http://www.pulpproject.org/foo' } self.assertEquals((True, None), configuration.validate_config(config)) def test_server_url_fully_qualified_with_port(self): config = { constants.CONFIG_KEY_REDIRECT_URL: 'http://www.pulpproject.org:440/foo' } self.assertEquals((True, None), configuration.validate_config(config)) def test_server_url_empty(self): config = { constants.CONFIG_KEY_REDIRECT_URL: '' } # This is valid as the default server should be used self.assertEquals((True, None), configuration.validate_config(config)) def test_server_url_missing_host_and_path(self): config = { constants.CONFIG_KEY_REDIRECT_URL: 'http://' } assert_validation_exception(configuration.validate_config, [error_codes.OST1002, error_codes.OST1003], config) def test_server_url_missing_scheme(self): config = { constants.CONFIG_KEY_REDIRECT_URL: 'www.pulpproject.org/foo' } assert_validation_exception(configuration.validate_config, [error_codes.OST1001, error_codes.OST1002], config) def test_configuration_protected_true(self): config = PluginCallConfiguration({ constants.CONFIG_KEY_PROTECTED: True }, {}) self.assertEquals((True, None), configuration.validate_config(config)) def test_configuration_protected_false_str(self): config = PluginCallConfiguration({ constants.CONFIG_KEY_PROTECTED: 'false' }, {}) self.assertEquals((True, None), configuration.validate_config(config)) def test_configuration_protected_bad_str(self): config = PluginCallConfiguration({ constants.CONFIG_KEY_PROTECTED: 'apple' }, {}) assert_validation_exception(configuration.validate_config, [error_codes.OST1004], config) class TestConfigurationGetters(unittest.TestCase): def setUp(self): self.working_directory = tempfile.mkdtemp() self.publish_dir = os.path.join(self.working_directory, 'publish') self.repo_working = os.path.join(self.working_directory, 'work') self.repo = Mock(id='foo', working_dir=self.repo_working) self.config = { constants.CONFIG_KEY_GLANCE_PUBLISH_DIRECTORY: self.publish_dir } def tearDown(self): shutil.rmtree(self.working_directory) def test_get_root_publish_directory(self): directory = configuration.get_root_publish_directory(self.config) self.assertEquals(directory, self.publish_dir) def test_get_master_publish_dir(self): directory = configuration.get_master_publish_dir(self.repo, self.config) self.assertEquals(directory, os.path.join(self.publish_dir, 'master', self.repo.id)) def test_get_web_publish_dir(self): directory = configuration.get_web_publish_dir(self.repo, self.config) self.assertEquals(directory, os.path.join(self.publish_dir, 'web', self.repo.id)) def test_get_repo_relative_path(self): directory = configuration.get_repo_relative_path(self.repo, self.config) self.assertEquals(directory, self.repo.id)
gpl-2.0
compas-dev/compas
src/compas_rhino/forms/etoforms/text.py
1
1568
from __future__ import print_function from __future__ import absolute_import from __future__ import division import clr clr.AddReference("Eto") clr.AddReference("Rhino.UI") import Rhino # noqa: E402 import Rhino.UI # noqa: E402 import Eto.Drawing # noqa: E402 import Eto.Forms # noqa: E402 __all__ = ['TextForm'] class TextForm(Eto.Forms.Dialog[bool]): def __init__(self, text, title='Message'): self.text = text self.textbox = textbox = Eto.Forms.TextArea() textbox.ReadOnly = True textbox.Append(text) layout = Eto.Forms.DynamicLayout() layout.AddRow(textbox) layout.Add(None) layout.BeginVertical() layout.BeginHorizontal() layout.AddRow(None, self.ok, self.cancel) layout.EndHorizontal() layout.EndVertical() self.Title = title self.Padding = Eto.Drawing.Padding(12) self.Resizable = False self.Content = layout self.ClientSize = Eto.Drawing.Size(400, 600) @property def ok(self): self.DefaultButton = Eto.Forms.Button(Text='OK') self.DefaultButton.Click += self.on_ok return self.DefaultButton @property def cancel(self): self.AbortButton = Eto.Forms.Button(Text='Cancel') self.AbortButton.Click += self.on_cancel return self.AbortButton def on_ok(self, sender, e): self.Close(True) def on_cancel(self, sender, e): self.Close(False) def show(self): return self.ShowModal(Rhino.UI.RhinoEtoApp.MainWindow)
mit
w1ll1am23/home-assistant
homeassistant/components/tellduslive/config_flow.py
3
5338
"""Config flow for Tellduslive.""" import asyncio import logging import os import async_timeout from tellduslive import Session, supports_local_api import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_HOST from homeassistant.util.json import load_json from .const import ( APPLICATION_NAME, CLOUD_NAME, DOMAIN, KEY_SCAN_INTERVAL, KEY_SESSION, NOT_SO_PRIVATE_KEY, PUBLIC_KEY, SCAN_INTERVAL, TELLDUS_CONFIG_FILE, ) KEY_TOKEN = "token" KEY_TOKEN_SECRET = "token_secret" _LOGGER = logging.getLogger(__name__) @config_entries.HANDLERS.register(DOMAIN) class FlowHandler(config_entries.ConfigFlow): """Handle a config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def __init__(self): """Init config flow.""" self._hosts = [CLOUD_NAME] self._host = None self._session = None self._scan_interval = SCAN_INTERVAL def _get_auth_url(self): self._session = Session( public_key=PUBLIC_KEY, private_key=NOT_SO_PRIVATE_KEY, host=self._host, application=APPLICATION_NAME, ) return self._session.authorize_url async def async_step_user(self, user_input=None): """Let user select host or cloud.""" if self.hass.config_entries.async_entries(DOMAIN): return self.async_abort(reason="already_setup") if user_input is not None or len(self._hosts) == 1: if user_input is not None and user_input[CONF_HOST] != CLOUD_NAME: self._host = user_input[CONF_HOST] return await self.async_step_auth() return self.async_show_form( step_id="user", data_schema=vol.Schema( {vol.Required(CONF_HOST): vol.In(list(self._hosts))} ), ) async def async_step_auth(self, user_input=None): """Handle the submitted configuration.""" errors = {} if user_input is not None: if await self.hass.async_add_executor_job(self._session.authorize): host = self._host or CLOUD_NAME if self._host: session = {CONF_HOST: host, KEY_TOKEN: self._session.access_token} else: session = { KEY_TOKEN: self._session.access_token, KEY_TOKEN_SECRET: self._session.access_token_secret, } return self.async_create_entry( title=host, data={ CONF_HOST: host, KEY_SCAN_INTERVAL: self._scan_interval.seconds, KEY_SESSION: session, }, ) errors["base"] = "invalid_auth" try: with async_timeout.timeout(10): auth_url = await self.hass.async_add_executor_job(self._get_auth_url) if not auth_url: return self.async_abort(reason="unknown_authorize_url_generation") except asyncio.TimeoutError: return self.async_abort(reason="authorize_url_timeout") except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected error generating auth url") return self.async_abort(reason="unknown_authorize_url_generation") _LOGGER.debug("Got authorization URL %s", auth_url) return self.async_show_form( step_id="auth", errors=errors, description_placeholders={ "app_name": APPLICATION_NAME, "auth_url": auth_url, }, ) async def async_step_discovery(self, discovery_info): """Run when a Tellstick is discovered.""" await self._async_handle_discovery_without_unique_id() _LOGGER.info("Discovered tellstick device: %s", discovery_info) if supports_local_api(discovery_info[1]): _LOGGER.info("%s support local API", discovery_info[1]) self._hosts.append(discovery_info[0]) return await self.async_step_user() async def async_step_import(self, user_input): """Import a config entry.""" if self.hass.config_entries.async_entries(DOMAIN): return self.async_abort(reason="already_setup") self._scan_interval = user_input[KEY_SCAN_INTERVAL] if user_input[CONF_HOST] != DOMAIN: self._hosts.append(user_input[CONF_HOST]) if not await self.hass.async_add_executor_job( os.path.isfile, self.hass.config.path(TELLDUS_CONFIG_FILE) ): return await self.async_step_user() conf = await self.hass.async_add_executor_job( load_json, self.hass.config.path(TELLDUS_CONFIG_FILE) ) host = next(iter(conf)) if user_input[CONF_HOST] != host: return await self.async_step_user() host = CLOUD_NAME if host == "tellduslive" else host return self.async_create_entry( title=host, data={ CONF_HOST: host, KEY_SCAN_INTERVAL: self._scan_interval.seconds, KEY_SESSION: next(iter(conf.values())), }, )
apache-2.0
Suwmlee/XX-Net
gae_proxy/server/lib/google/appengine/ext/builtins/__init__.py
8
3483
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Repository for all builtin handlers information. On initialization, this file generates a list of builtin handlers that have associated app.yaml information. This file can then be called to read that information and make it available. """ import logging import os DEFAULT_DIR = os.path.join(os.path.dirname(__file__)) _handler_dir = None _available_builtins = None BUILTINS_NOT_AVAIABLE_IN_PYTHON27 = set(['datastore_admin', 'mapreduce']) INCLUDE_FILENAME_TEMPLATE = 'include-%s.yaml' DEFAULT_INCLUDE_FILENAME = 'include.yaml' class InvalidBuiltinName(Exception): """Raised whenever a builtin handler name is specified that is not found.""" def reset_builtins_dir(): """Public method for resetting builtins directory to default.""" set_builtins_dir(DEFAULT_DIR) def set_builtins_dir(path): """Sets the appropriate path for testing and reinitializes the module.""" global _handler_dir, _available_builtins _handler_dir = path _available_builtins = [] _initialize_builtins() def _initialize_builtins(): """Scan the immediate subdirectories of the builtins module. Encountered subdirectories with an app.yaml file are added to AVAILABLE_BUILTINS. """ if os.path.isdir(_handler_dir): for filename in os.listdir(_handler_dir): if os.path.isfile(_get_yaml_path(filename, '')): _available_builtins.append(filename) def _get_yaml_path(builtin_name, runtime): """Return expected path to a builtin handler's yaml file without error check. """ runtime_specific = os.path.join(_handler_dir, builtin_name, INCLUDE_FILENAME_TEMPLATE % runtime) if runtime and os.path.exists(runtime_specific): return runtime_specific return os.path.join(_handler_dir, builtin_name, DEFAULT_INCLUDE_FILENAME) def get_yaml_path(builtin_name, runtime=''): """Returns the full path to a yaml file by giving the builtin module's name. Args: builtin_name: single word name of builtin handler runtime: name of the runtime Raises: ValueError: if handler does not exist in expected directory Returns: the absolute path to a valid builtin handler include.yaml file """ if _handler_dir is None: set_builtins_dir(DEFAULT_DIR) available_builtins = set(_available_builtins) if runtime == 'python27': available_builtins = available_builtins - BUILTINS_NOT_AVAIABLE_IN_PYTHON27 if builtin_name not in available_builtins: raise InvalidBuiltinName( '%s is not the name of a valid builtin.\n' 'Available handlers are: %s' % ( builtin_name, ', '.join(sorted(available_builtins)))) return _get_yaml_path(builtin_name, runtime) def get_yaml_basepath(): """Returns the full path of the directory in which builtins are located.""" if _handler_dir is None: set_builtins_dir(DEFAULT_DIR) return _handler_dir
bsd-2-clause
benpatterson/edx-platform
common/djangoapps/student/migrations/0037_auto__add_courseregistrationcode.py
114
14263
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'CourseRegistrationCode' db.create_table('student_courseregistrationcode', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('code', self.gf('django.db.models.fields.CharField')(max_length=32, db_index=True)), ('course_id', self.gf('xmodule_django.models.CourseKeyField')(max_length=255, db_index=True)), ('transaction_group_name', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=255, null=True, blank=True)), ('created_by', self.gf('django.db.models.fields.related.ForeignKey')(related_name='created_by_user', to=orm['auth.User'])), ('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2014, 6, 24, 0, 0))), ('redeemed_by', self.gf('django.db.models.fields.related.ForeignKey')(related_name='redeemed_by_user', null=True, to=orm['auth.User'])), ('redeemed_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2014, 6, 24, 0, 0), null=True)), )) db.send_create_signal('student', ['CourseRegistrationCode']) def backwards(self, orm): # Deleting model 'CourseRegistrationCode' db.delete_table('student_courseregistrationcode') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'student.anonymoususerid': { 'Meta': {'object_name': 'AnonymousUserId'}, 'anonymous_user_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}), 'course_id': ('xmodule_django.models.CourseKeyField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.courseaccessrole': { 'Meta': {'unique_together': "(('user', 'org', 'course_id', 'role'),)", 'object_name': 'CourseAccessRole'}, 'course_id': ('xmodule_django.models.CourseKeyField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'org': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '64', 'blank': 'True'}), 'role': ('django.db.models.fields.CharField', [], {'max_length': '64', 'db_index': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.courseenrollment': { 'Meta': {'ordering': "('user', 'course_id')", 'unique_together': "(('user', 'course_id'),)", 'object_name': 'CourseEnrollment'}, 'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'mode': ('django.db.models.fields.CharField', [], {'default': "'honor'", 'max_length': '100'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.courseenrollmentallowed': { 'Meta': {'unique_together': "(('email', 'course_id'),)", 'object_name': 'CourseEnrollmentAllowed'}, 'auto_enroll': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'student.courseregistrationcode': { 'Meta': {'object_name': 'CourseRegistrationCode'}, 'code': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 6, 24, 0, 0)'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_by_user'", 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'redeemed_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 6, 24, 0, 0)', 'null': 'True'}), 'redeemed_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'redeemed_by_user'", 'null': 'True', 'to': "orm['auth.User']"}), 'transaction_group_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}) }, 'student.loginfailures': { 'Meta': {'object_name': 'LoginFailures'}, 'failure_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'lockout_until': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.passwordhistory': { 'Meta': {'object_name': 'PasswordHistory'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'time_set': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.pendingemailchange': { 'Meta': {'object_name': 'PendingEmailChange'}, 'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_email': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'student.pendingnamechange': { 'Meta': {'object_name': 'PendingNameChange'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'rationale': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'student.registration': { 'Meta': {'object_name': 'Registration', 'db_table': "'auth_registration'"}, 'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'student.userprofile': { 'Meta': {'object_name': 'UserProfile', 'db_table': "'auth_userprofile'"}, 'allow_certificate': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'city': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'country': ('django_countries.fields.CountryField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'courseware': ('django.db.models.fields.CharField', [], {'default': "'course.xml'", 'max_length': '255', 'blank': 'True'}), 'gender': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '6', 'null': 'True', 'blank': 'True'}), 'goals': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'level_of_education': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '6', 'null': 'True', 'blank': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'mailing_address': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'meta': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"}), 'year_of_birth': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}) }, 'student.userstanding': { 'Meta': {'object_name': 'UserStanding'}, 'account_status': ('django.db.models.fields.CharField', [], {'max_length': '31', 'blank': 'True'}), 'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'standing_last_changed_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'standing'", 'unique': 'True', 'to': "orm['auth.User']"}) }, 'student.usertestgroup': { 'Meta': {'object_name': 'UserTestGroup'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'db_index': 'True', 'symmetrical': 'False'}) } } complete_apps = ['student']
agpl-3.0
JioCloud/nova_test_latest
nova/api/openstack/compute/plugins/v3/servers.py
17
51453
# Copyright 2010 OpenStack Foundation # Copyright 2011 Piston Cloud Computing, Inc # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import base64 import re from oslo_config import cfg from oslo_log import log as logging import oslo_messaging as messaging from oslo_utils import strutils from oslo_utils import timeutils from oslo_utils import uuidutils import six import stevedore import webob from webob import exc from nova.api.openstack import api_version_request from nova.api.openstack import common from nova.api.openstack.compute.schemas.v3 import servers as schema_servers from nova.api.openstack.compute.views import servers as views_servers from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api import validation from nova import compute from nova.compute import flavors from nova import exception from nova.i18n import _ from nova.i18n import _LW from nova.image import glance from nova import objects from nova import utils ALIAS = 'servers' CONF = cfg.CONF CONF.import_opt('enable_instance_password', 'nova.api.openstack.compute.servers') CONF.import_opt('network_api_class', 'nova.network') CONF.import_opt('reclaim_instance_interval', 'nova.compute.manager') CONF.import_opt('extensions_blacklist', 'nova.api.openstack', group='osapi_v3') CONF.import_opt('extensions_whitelist', 'nova.api.openstack', group='osapi_v3') LOG = logging.getLogger(__name__) authorize = extensions.os_compute_authorizer(ALIAS) class ServersController(wsgi.Controller): """The Server API base controller class for the OpenStack API.""" EXTENSION_CREATE_NAMESPACE = 'nova.api.v3.extensions.server.create' EXTENSION_DESERIALIZE_EXTRACT_SERVER_NAMESPACE = ( 'nova.api.v3.extensions.server.create.deserialize') EXTENSION_REBUILD_NAMESPACE = 'nova.api.v3.extensions.server.rebuild' EXTENSION_DESERIALIZE_EXTRACT_REBUILD_NAMESPACE = ( 'nova.api.v3.extensions.server.rebuild.deserialize') EXTENSION_UPDATE_NAMESPACE = 'nova.api.v3.extensions.server.update' EXTENSION_RESIZE_NAMESPACE = 'nova.api.v3.extensions.server.resize' _view_builder_class = views_servers.ViewBuilderV3 schema_server_create = schema_servers.base_create schema_server_update = schema_servers.base_update schema_server_rebuild = schema_servers.base_rebuild schema_server_resize = schema_servers.base_resize @staticmethod def _add_location(robj): # Just in case... if 'server' not in robj.obj: return robj link = filter(lambda l: l['rel'] == 'self', robj.obj['server']['links']) if link: robj['Location'] = utils.utf8(link[0]['href']) # Convenience return return robj def __init__(self, **kwargs): def _check_load_extension(required_function): def check_whiteblack_lists(ext): # Check whitelist is either empty or if not then the extension # is in the whitelist if (not CONF.osapi_v3.extensions_whitelist or ext.obj.alias in CONF.osapi_v3.extensions_whitelist): # Check the extension is not in the blacklist if ext.obj.alias not in CONF.osapi_v3.extensions_blacklist: return True else: LOG.warning(_LW("Not loading %s because it is " "in the blacklist"), ext.obj.alias) return False else: LOG.warning( _LW("Not loading %s because it is not in the " "whitelist"), ext.obj.alias) return False def check_load_extension(ext): if isinstance(ext.obj, extensions.V3APIExtensionBase): # Filter out for the existence of the required # function here rather than on every request. We # don't have a new abstract base class to reduce # duplication in the extensions as they may want # to implement multiple server (and other) entry # points if hasattr(ext.obj, 'server_create'): if hasattr(ext.obj, required_function): LOG.debug('extension %(ext_alias)s detected by ' 'servers extension for function %(func)s', {'ext_alias': ext.obj.alias, 'func': required_function}) return check_whiteblack_lists(ext) else: LOG.debug( 'extension %(ext_alias)s is missing %(func)s', {'ext_alias': ext.obj.alias, 'func': required_function}) return False else: return False return check_load_extension self.extension_info = kwargs.pop('extension_info') super(ServersController, self).__init__(**kwargs) self.compute_api = compute.API(skip_policy_check=True) # Look for implementation of extension point of server creation self.create_extension_manager = \ stevedore.enabled.EnabledExtensionManager( namespace=self.EXTENSION_CREATE_NAMESPACE, check_func=_check_load_extension('server_create'), invoke_on_load=True, invoke_kwds={"extension_info": self.extension_info}, propagate_map_exceptions=True) if not list(self.create_extension_manager): LOG.debug("Did not find any server create extensions") # Look for implementation of extension point of server rebuild self.rebuild_extension_manager = \ stevedore.enabled.EnabledExtensionManager( namespace=self.EXTENSION_REBUILD_NAMESPACE, check_func=_check_load_extension('server_rebuild'), invoke_on_load=True, invoke_kwds={"extension_info": self.extension_info}, propagate_map_exceptions=True) if not list(self.rebuild_extension_manager): LOG.debug("Did not find any server rebuild extensions") # Look for implementation of extension point of server update self.update_extension_manager = \ stevedore.enabled.EnabledExtensionManager( namespace=self.EXTENSION_UPDATE_NAMESPACE, check_func=_check_load_extension('server_update'), invoke_on_load=True, invoke_kwds={"extension_info": self.extension_info}, propagate_map_exceptions=True) if not list(self.update_extension_manager): LOG.debug("Did not find any server update extensions") # Look for implementation of extension point of server resize self.resize_extension_manager = \ stevedore.enabled.EnabledExtensionManager( namespace=self.EXTENSION_RESIZE_NAMESPACE, check_func=_check_load_extension('server_resize'), invoke_on_load=True, invoke_kwds={"extension_info": self.extension_info}, propagate_map_exceptions=True) if not list(self.resize_extension_manager): LOG.debug("Did not find any server resize extensions") # Look for API schema of server create extension self.create_schema_manager = \ stevedore.enabled.EnabledExtensionManager( namespace=self.EXTENSION_CREATE_NAMESPACE, check_func=_check_load_extension('get_server_create_schema'), invoke_on_load=True, invoke_kwds={"extension_info": self.extension_info}, propagate_map_exceptions=True) if list(self.create_schema_manager): self.create_schema_manager.map(self._create_extension_schema, self.schema_server_create) else: LOG.debug("Did not find any server create schemas") # Look for API schema of server update extension self.update_schema_manager = \ stevedore.enabled.EnabledExtensionManager( namespace=self.EXTENSION_UPDATE_NAMESPACE, check_func=_check_load_extension('get_server_update_schema'), invoke_on_load=True, invoke_kwds={"extension_info": self.extension_info}, propagate_map_exceptions=True) if list(self.update_schema_manager): self.update_schema_manager.map(self._update_extension_schema, self.schema_server_update) else: LOG.debug("Did not find any server update schemas") # Look for API schema of server rebuild extension self.rebuild_schema_manager = \ stevedore.enabled.EnabledExtensionManager( namespace=self.EXTENSION_REBUILD_NAMESPACE, check_func=_check_load_extension('get_server_rebuild_schema'), invoke_on_load=True, invoke_kwds={"extension_info": self.extension_info}, propagate_map_exceptions=True) if list(self.rebuild_schema_manager): self.rebuild_schema_manager.map(self._rebuild_extension_schema, self.schema_server_rebuild) else: LOG.debug("Did not find any server rebuild schemas") # Look for API schema of server resize extension self.resize_schema_manager = \ stevedore.enabled.EnabledExtensionManager( namespace=self.EXTENSION_RESIZE_NAMESPACE, check_func=_check_load_extension('get_server_resize_schema'), invoke_on_load=True, invoke_kwds={"extension_info": self.extension_info}, propagate_map_exceptions=True) if list(self.resize_schema_manager): self.resize_schema_manager.map(self._resize_extension_schema, self.schema_server_resize) else: LOG.debug("Did not find any server resize schemas") @extensions.expected_errors((400, 403)) def index(self, req): """Returns a list of server names and ids for a given user.""" context = req.environ['nova.context'] authorize(context, action="index") try: servers = self._get_servers(req, is_detail=False) except exception.Invalid as err: raise exc.HTTPBadRequest(explanation=err.format_message()) return servers @extensions.expected_errors((400, 403)) def detail(self, req): """Returns a list of server details for a given user.""" context = req.environ['nova.context'] authorize(context, action="detail") try: servers = self._get_servers(req, is_detail=True) except exception.Invalid as err: raise exc.HTTPBadRequest(explanation=err.format_message()) return servers def _get_servers(self, req, is_detail): """Returns a list of servers, based on any search options specified.""" search_opts = {} search_opts.update(req.GET) context = req.environ['nova.context'] remove_invalid_options(context, search_opts, self._get_server_search_options(req)) # Verify search by 'status' contains a valid status. # Convert it to filter by vm_state or task_state for compute_api. search_opts.pop('status', None) if 'status' in req.GET.keys(): statuses = req.GET.getall('status') states = common.task_and_vm_state_from_status(statuses) vm_state, task_state = states if not vm_state and not task_state: return {'servers': []} search_opts['vm_state'] = vm_state # When we search by vm state, task state will return 'default'. # So we don't need task_state search_opt. if 'default' not in task_state: search_opts['task_state'] = task_state if 'changes-since' in search_opts: try: parsed = timeutils.parse_isotime(search_opts['changes-since']) except ValueError: msg = _('Invalid changes-since value') raise exc.HTTPBadRequest(explanation=msg) search_opts['changes-since'] = parsed # By default, compute's get_all() will return deleted instances. # If an admin hasn't specified a 'deleted' search option, we need # to filter out deleted instances by setting the filter ourselves. # ... Unless 'changes-since' is specified, because 'changes-since' # should return recently deleted images according to the API spec. if 'deleted' not in search_opts: if 'changes-since' not in search_opts: # No 'changes-since', so we only want non-deleted servers search_opts['deleted'] = False else: # Convert deleted filter value to a valid boolean. # Return non-deleted servers if an invalid value # is passed with deleted filter. search_opts['deleted'] = strutils.bool_from_string( search_opts['deleted'], default=False) if search_opts.get("vm_state") == ['deleted']: if context.is_admin: search_opts['deleted'] = True else: msg = _("Only administrators may list deleted instances") raise exc.HTTPForbidden(explanation=msg) # If tenant_id is passed as a search parameter this should # imply that all_tenants is also enabled unless explicitly # disabled. Note that the tenant_id parameter is filtered out # by remove_invalid_options above unless the requestor is an # admin. # TODO(gmann): 'all_tenants' flag should not be required while # searching with 'tenant_id'. Ref bug# 1185290 # +microversions to achieve above mentioned behavior by # uncommenting below code. # if 'tenant_id' in search_opts and 'all_tenants' not in search_opts: # We do not need to add the all_tenants flag if the tenant # id associated with the token is the tenant id # specified. This is done so a request that does not need # the all_tenants flag does not fail because of lack of # policy permission for compute:get_all_tenants when it # doesn't actually need it. # if context.project_id != search_opts.get('tenant_id'): # search_opts['all_tenants'] = 1 # If all tenants is passed with 0 or false as the value # then remove it from the search options. Nothing passed as # the value for all_tenants is considered to enable the feature all_tenants = search_opts.get('all_tenants') if all_tenants: try: if not strutils.bool_from_string(all_tenants, True): del search_opts['all_tenants'] except ValueError as err: raise exception.InvalidInput(six.text_type(err)) elevated = None if 'all_tenants' in search_opts: if is_detail: authorize(context, action="detail:get_all_tenants") else: authorize(context, action="index:get_all_tenants") del search_opts['all_tenants'] elevated = context.elevated() else: if context.project_id: search_opts['project_id'] = context.project_id else: search_opts['user_id'] = context.user_id limit, marker = common.get_limit_and_marker(req) sort_keys, sort_dirs = common.get_sort_params(req.params) try: instance_list = self.compute_api.get_all(elevated or context, search_opts=search_opts, limit=limit, marker=marker, want_objects=True, expected_attrs=['pci_devices'], sort_keys=sort_keys, sort_dirs=sort_dirs) except exception.MarkerNotFound: msg = _('marker [%s] not found') % marker raise exc.HTTPBadRequest(explanation=msg) except exception.FlavorNotFound: LOG.debug("Flavor '%s' could not be found ", search_opts['flavor']) instance_list = objects.InstanceList() if is_detail: instance_list.fill_faults() response = self._view_builder.detail(req, instance_list) else: response = self._view_builder.index(req, instance_list) req.cache_db_instances(instance_list) return response def _get_server(self, context, req, instance_uuid): """Utility function for looking up an instance by uuid.""" instance = common.get_instance(self.compute_api, context, instance_uuid, expected_attrs=['pci_devices', 'flavor']) req.cache_db_instance(instance) return instance def _check_string_length(self, value, name, max_length=None): try: if isinstance(value, six.string_types): value = value.strip() utils.check_string_length(value, name, min_length=1, max_length=max_length) except exception.InvalidInput as e: raise exc.HTTPBadRequest(explanation=e.format_message()) def _get_requested_networks(self, requested_networks): """Create a list of requested networks from the networks attribute.""" networks = [] network_uuids = [] for network in requested_networks: request = objects.NetworkRequest() try: # fixed IP address is optional # if the fixed IP address is not provided then # it will use one of the available IP address from the network request.address = network.get('fixed_ip', None) request.port_id = network.get('port', None) if request.port_id: request.network_id = None if not utils.is_neutron(): # port parameter is only for neutron v2.0 msg = _("Unknown argument: port") raise exc.HTTPBadRequest(explanation=msg) if request.address is not None: msg = _("Specified Fixed IP '%(addr)s' cannot be used " "with port '%(port)s': port already has " "a Fixed IP allocated.") % { "addr": request.address, "port": request.port_id} raise exc.HTTPBadRequest(explanation=msg) else: request.network_id = network['uuid'] if (not request.port_id and not uuidutils.is_uuid_like(request.network_id)): br_uuid = request.network_id.split('-', 1)[-1] if not uuidutils.is_uuid_like(br_uuid): msg = _("Bad networks format: network uuid is " "not in proper format " "(%s)") % request.network_id raise exc.HTTPBadRequest(explanation=msg) # duplicate networks are allowed only for neutron v2.0 if (not utils.is_neutron() and request.network_id and request.network_id in network_uuids): expl = (_("Duplicate networks" " (%s) are not allowed") % request.network_id) raise exc.HTTPBadRequest(explanation=expl) network_uuids.append(request.network_id) networks.append(request) except KeyError as key: expl = _('Bad network format: missing %s') % key raise exc.HTTPBadRequest(explanation=expl) except TypeError: expl = _('Bad networks format') raise exc.HTTPBadRequest(explanation=expl) return objects.NetworkRequestList(objects=networks) # NOTE(vish): Without this regex, b64decode will happily # ignore illegal bytes in the base64 encoded # data. B64_REGEX = re.compile('^(?:[A-Za-z0-9+\/]{4})*' '(?:[A-Za-z0-9+\/]{2}==' '|[A-Za-z0-9+\/]{3}=)?$') def _decode_base64(self, data): data = re.sub(r'\s', '', data) if not self.B64_REGEX.match(data): return None try: return base64.b64decode(data) except TypeError: return None @extensions.expected_errors(404) def show(self, req, id): """Returns server details by server id.""" context = req.environ['nova.context'] instance = common.get_instance(self.compute_api, context, id, expected_attrs=['pci_devices', 'flavor']) authorize(context, action="show") req.cache_db_instance(instance) return self._view_builder.show(req, instance) @wsgi.response(202) @extensions.expected_errors((400, 403, 409, 413)) @validation.schema(schema_server_create) def create(self, req, body): """Creates a new server for a given user.""" context = req.environ['nova.context'] server_dict = body['server'] password = self._get_server_admin_password(server_dict) name = server_dict['name'] # Arguments to be passed to instance create function create_kwargs = {} # Query extensions which want to manipulate the keyword # arguments. # NOTE(cyeoh): This is the hook that extensions use # to replace the extension specific code below. # When the extensions are ported this will also result # in some convenience function from this class being # moved to the extension if list(self.create_extension_manager): self.create_extension_manager.map(self._create_extension_point, server_dict, create_kwargs, body) availability_zone = create_kwargs.get("availability_zone") target = { 'project_id': context.project_id, 'user_id': context.user_id, 'availability_zone': availability_zone} authorize(context, target, 'create') # TODO(Shao He, Feng) move this policy check to os-availabilty-zone # extension after refactor it. if availability_zone: _dummy, host, node = self.compute_api._handle_availability_zone( context, availability_zone) if host or node: authorize(context, {}, 'create:forced_host') block_device_mapping = create_kwargs.get("block_device_mapping") # TODO(Shao He, Feng) move this policy check to os-block-device-mapping # extension after refactor it. if block_device_mapping: authorize(context, target, 'create:attach_volume') image_uuid = self._image_from_req_data(server_dict, create_kwargs) # NOTE(cyeoh): Although an extension can set # return_reservation_id in order to request that a reservation # id be returned to the client instead of the newly created # instance information we do not want to pass this parameter # to the compute create call which always returns both. We use # this flag after the instance create call to determine what # to return to the client return_reservation_id = create_kwargs.pop('return_reservation_id', False) requested_networks = None if ('os-networks' in self.extension_info.get_extensions() or utils.is_neutron()): requested_networks = server_dict.get('networks') if requested_networks is not None: requested_networks = self._get_requested_networks( requested_networks) if requested_networks and len(requested_networks): authorize(context, target, 'create:attach_network') try: flavor_id = self._flavor_id_from_req_data(body) except ValueError: msg = _("Invalid flavorRef provided.") raise exc.HTTPBadRequest(explanation=msg) try: inst_type = flavors.get_flavor_by_flavor_id( flavor_id, ctxt=context, read_deleted="no") (instances, resv_id) = self.compute_api.create(context, inst_type, image_uuid, display_name=name, display_description=name, metadata=server_dict.get('metadata', {}), admin_password=password, requested_networks=requested_networks, check_server_group_quota=True, **create_kwargs) except (exception.QuotaError, exception.PortLimitExceeded) as error: raise exc.HTTPForbidden( explanation=error.format_message(), headers={'Retry-After': 0}) except exception.ImageNotFound: msg = _("Can not find requested image") raise exc.HTTPBadRequest(explanation=msg) except exception.FlavorNotFound: msg = _("Invalid flavorRef provided.") raise exc.HTTPBadRequest(explanation=msg) except exception.KeypairNotFound: msg = _("Invalid key_name provided.") raise exc.HTTPBadRequest(explanation=msg) except exception.ConfigDriveInvalidValue: msg = _("Invalid config_drive provided.") raise exc.HTTPBadRequest(explanation=msg) except exception.ExternalNetworkAttachForbidden as error: raise exc.HTTPForbidden(explanation=error.format_message()) except messaging.RemoteError as err: msg = "%(err_type)s: %(err_msg)s" % {'err_type': err.exc_type, 'err_msg': err.value} raise exc.HTTPBadRequest(explanation=msg) except UnicodeDecodeError as error: msg = "UnicodeError: %s" % error raise exc.HTTPBadRequest(explanation=msg) except (exception.ImageNotActive, exception.FlavorDiskTooSmall, exception.FlavorMemoryTooSmall, exception.InvalidMetadata, exception.InvalidRequest, exception.InvalidVolume, exception.MultiplePortsNotApplicable, exception.InvalidFixedIpAndMaxCountRequest, exception.InstanceUserDataMalformed, exception.InstanceUserDataTooLarge, exception.PortNotFound, exception.FixedIpAlreadyInUse, exception.SecurityGroupNotFound, exception.PortRequiresFixedIP, exception.NetworkRequiresSubnet, exception.NetworkNotFound, exception.NetworkDuplicated, exception.InvalidBDMSnapshot, exception.InvalidBDMVolume, exception.InvalidBDMImage, exception.InvalidBDMBootSequence, exception.InvalidBDMLocalsLimit, exception.InvalidBDMVolumeNotBootable, exception.AutoDiskConfigDisabledByImage, exception.ImageNUMATopologyIncomplete, exception.ImageNUMATopologyForbidden, exception.ImageNUMATopologyAsymmetric, exception.ImageNUMATopologyCPUOutOfRange, exception.ImageNUMATopologyCPUDuplicates, exception.ImageNUMATopologyCPUsUnassigned, exception.ImageNUMATopologyMemoryOutOfRange) as error: raise exc.HTTPBadRequest(explanation=error.format_message()) except (exception.PortInUse, exception.InstanceExists, exception.NetworkAmbiguous, exception.NoUniqueMatch) as error: raise exc.HTTPConflict(explanation=error.format_message()) # If the caller wanted a reservation_id, return it if return_reservation_id: # NOTE(cyeoh): In v3 reservation_id was wrapped in # servers_reservation but this is reverted for V2 API # compatibility. In the long term with the tasks API we # will probably just drop the concept of reservation_id return wsgi.ResponseObject({'reservation_id': resv_id}) req.cache_db_instances(instances) server = self._view_builder.create(req, instances[0]) if CONF.enable_instance_password: server['server']['adminPass'] = password robj = wsgi.ResponseObject(server) return self._add_location(robj) # NOTE(gmann): Parameter 'req_body' is placed to handle scheduler_hint # extension for V2.1. No other extension supposed to use this as # it will be removed soon. def _create_extension_point(self, ext, server_dict, create_kwargs, req_body): handler = ext.obj LOG.debug("Running _create_extension_point for %s", ext.obj) handler.server_create(server_dict, create_kwargs, req_body) def _rebuild_extension_point(self, ext, rebuild_dict, rebuild_kwargs): handler = ext.obj LOG.debug("Running _rebuild_extension_point for %s", ext.obj) handler.server_rebuild(rebuild_dict, rebuild_kwargs) def _resize_extension_point(self, ext, resize_dict, resize_kwargs): handler = ext.obj LOG.debug("Running _resize_extension_point for %s", ext.obj) handler.server_resize(resize_dict, resize_kwargs) def _update_extension_point(self, ext, update_dict, update_kwargs): handler = ext.obj LOG.debug("Running _update_extension_point for %s", ext.obj) handler.server_update(update_dict, update_kwargs) def _create_extension_schema(self, ext, create_schema): handler = ext.obj LOG.debug("Running _create_extension_schema for %s", ext.obj) schema = handler.get_server_create_schema() if ext.obj.name == 'SchedulerHints': # NOTE(oomichi): The request parameter position of scheduler-hint # extension is different from the other extensions, so here handles # the difference. create_schema['properties'].update(schema) else: create_schema['properties']['server']['properties'].update(schema) def _update_extension_schema(self, ext, update_schema): handler = ext.obj LOG.debug("Running _update_extension_schema for %s", ext.obj) schema = handler.get_server_update_schema() update_schema['properties']['server']['properties'].update(schema) def _rebuild_extension_schema(self, ext, rebuild_schema): handler = ext.obj LOG.debug("Running _rebuild_extension_schema for %s", ext.obj) schema = handler.get_server_rebuild_schema() rebuild_schema['properties']['rebuild']['properties'].update(schema) def _resize_extension_schema(self, ext, resize_schema): handler = ext.obj LOG.debug("Running _resize_extension_schema for %s", ext.obj) schema = handler.get_server_resize_schema() resize_schema['properties']['resize']['properties'].update(schema) def _delete(self, context, req, instance_uuid): authorize(context, action='delete') instance = self._get_server(context, req, instance_uuid) if CONF.reclaim_instance_interval: try: self.compute_api.soft_delete(context, instance) except exception.InstanceInvalidState: # Note(yufang521247): instance which has never been active # is not allowed to be soft_deleted. Thus we have to call # delete() to clean up the instance. self.compute_api.delete(context, instance) else: self.compute_api.delete(context, instance) @extensions.expected_errors((400, 404)) @validation.schema(schema_server_update) def update(self, req, id, body): """Update server then pass on to version-specific controller.""" ctxt = req.environ['nova.context'] update_dict = {} authorize(ctxt, action='update') if 'name' in body['server']: update_dict['display_name'] = body['server']['name'] if list(self.update_extension_manager): self.update_extension_manager.map(self._update_extension_point, body['server'], update_dict) instance = common.get_instance(self.compute_api, ctxt, id, expected_attrs=['pci_devices']) try: # NOTE(mikal): this try block needs to stay because save() still # might throw an exception. req.cache_db_instance(instance) instance.update(update_dict) instance.save() return self._view_builder.show(req, instance, extend_address=False) except exception.InstanceNotFound: msg = _("Instance could not be found") raise exc.HTTPNotFound(explanation=msg) # NOTE(gmann): Returns 204 for backwards compatibility but should be 202 # for representing async API as this API just accepts the request and # request hypervisor driver to complete the same in async mode. @wsgi.response(204) @extensions.expected_errors((400, 404, 409)) @wsgi.action('confirmResize') def _action_confirm_resize(self, req, id, body): context = req.environ['nova.context'] authorize(context, action='confirm_resize') instance = self._get_server(context, req, id) try: self.compute_api.confirm_resize(context, instance) except exception.MigrationNotFound: msg = _("Instance has not been resized.") raise exc.HTTPBadRequest(explanation=msg) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'confirmResize', id) @wsgi.response(202) @extensions.expected_errors((400, 404, 409)) @wsgi.action('revertResize') def _action_revert_resize(self, req, id, body): context = req.environ['nova.context'] authorize(context, action='revert_resize') instance = self._get_server(context, req, id) try: self.compute_api.revert_resize(context, instance) except exception.MigrationNotFound: msg = _("Instance has not been resized.") raise exc.HTTPBadRequest(explanation=msg) except exception.FlavorNotFound: msg = _("Flavor used by the instance could not be found.") raise exc.HTTPBadRequest(explanation=msg) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'revertResize', id) @wsgi.response(202) @extensions.expected_errors((404, 409)) @wsgi.action('reboot') @validation.schema(schema_servers.reboot) def _action_reboot(self, req, id, body): reboot_type = body['reboot']['type'].upper() context = req.environ['nova.context'] authorize(context, action='reboot') instance = self._get_server(context, req, id) try: self.compute_api.reboot(context, instance, reboot_type) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'reboot', id) def _resize(self, req, instance_id, flavor_id, **kwargs): """Begin the resize process with given instance/flavor.""" context = req.environ["nova.context"] authorize(context, action='resize') instance = self._get_server(context, req, instance_id) try: self.compute_api.resize(context, instance, flavor_id, **kwargs) except exception.QuotaError as error: raise exc.HTTPForbidden( explanation=error.format_message(), headers={'Retry-After': 0}) except exception.FlavorNotFound: msg = _("Unable to locate requested flavor.") raise exc.HTTPBadRequest(explanation=msg) except exception.CannotResizeToSameFlavor: msg = _("Resize requires a flavor change.") raise exc.HTTPBadRequest(explanation=msg) except (exception.CannotResizeDisk, exception.AutoDiskConfigDisabledByImage) as e: raise exc.HTTPBadRequest(explanation=e.format_message()) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'resize', instance_id) except exception.ImageNotAuthorized: msg = _("You are not authorized to access the image " "the instance was started with.") raise exc.HTTPUnauthorized(explanation=msg) except exception.ImageNotFound: msg = _("Image that the instance was started " "with could not be found.") raise exc.HTTPBadRequest(explanation=msg) except (exception.NoValidHost, exception.AutoDiskConfigDisabledByImage) as e: raise exc.HTTPBadRequest(explanation=e.format_message()) except exception.Invalid: msg = _("Invalid instance image.") raise exc.HTTPBadRequest(explanation=msg) @wsgi.response(204) @extensions.expected_errors((404, 409)) def delete(self, req, id): """Destroys a server.""" try: self._delete(req.environ['nova.context'], req, id) except exception.InstanceNotFound: msg = _("Instance could not be found") raise exc.HTTPNotFound(explanation=msg) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'delete', id) def _image_uuid_from_href(self, image_href): # If the image href was generated by nova api, strip image_href # down to an id and use the default glance connection params image_uuid = image_href.split('/').pop() if not uuidutils.is_uuid_like(image_uuid): msg = _("Invalid imageRef provided.") raise exc.HTTPBadRequest(explanation=msg) return image_uuid def _image_from_req_data(self, server_dict, create_kwargs): """Get image data from the request or raise appropriate exceptions. The field imageRef is mandatory when no block devices have been defined and must be a proper uuid when present. """ image_href = server_dict.get('imageRef') if not image_href and create_kwargs.get('block_device_mapping'): return '' elif image_href: return self._image_uuid_from_href(six.text_type(image_href)) else: msg = _("Missing imageRef attribute") raise exc.HTTPBadRequest(explanation=msg) def _flavor_id_from_req_data(self, data): flavor_ref = data['server']['flavorRef'] return common.get_id_from_href(flavor_ref) @wsgi.response(202) @extensions.expected_errors((400, 401, 403, 404, 409)) @wsgi.action('resize') @validation.schema(schema_server_resize) def _action_resize(self, req, id, body): """Resizes a given instance to the flavor size requested.""" resize_dict = body['resize'] flavor_ref = str(resize_dict["flavorRef"]) resize_kwargs = {} if list(self.resize_extension_manager): self.resize_extension_manager.map(self._resize_extension_point, resize_dict, resize_kwargs) self._resize(req, id, flavor_ref, **resize_kwargs) @wsgi.response(202) @extensions.expected_errors((400, 403, 404, 409, 413)) @wsgi.action('rebuild') @validation.schema(schema_server_rebuild) def _action_rebuild(self, req, id, body): """Rebuild an instance with the given attributes.""" rebuild_dict = body['rebuild'] image_href = rebuild_dict["imageRef"] image_href = self._image_uuid_from_href(image_href) password = self._get_server_admin_password(rebuild_dict) context = req.environ['nova.context'] authorize(context, action='rebuild') instance = self._get_server(context, req, id) attr_map = { 'name': 'display_name', 'metadata': 'metadata', } rebuild_kwargs = {} if list(self.rebuild_extension_manager): self.rebuild_extension_manager.map(self._rebuild_extension_point, rebuild_dict, rebuild_kwargs) for request_attribute, instance_attribute in attr_map.items(): try: rebuild_kwargs[instance_attribute] = rebuild_dict[ request_attribute] except (KeyError, TypeError): pass try: self.compute_api.rebuild(context, instance, image_href, password, **rebuild_kwargs) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'rebuild', id) except exception.InstanceNotFound: msg = _("Instance could not be found") raise exc.HTTPNotFound(explanation=msg) except exception.ImageNotFound: msg = _("Cannot find image for rebuild") raise exc.HTTPBadRequest(explanation=msg) except exception.QuotaError as error: raise exc.HTTPForbidden(explanation=error.format_message()) except (exception.ImageNotActive, exception.FlavorDiskTooSmall, exception.FlavorMemoryTooSmall, exception.InvalidMetadata, exception.AutoDiskConfigDisabledByImage) as error: raise exc.HTTPBadRequest(explanation=error.format_message()) instance = self._get_server(context, req, id) view = self._view_builder.show(req, instance, extend_address=False) # Add on the admin_password attribute since the view doesn't do it # unless instance passwords are disabled if CONF.enable_instance_password: view['server']['adminPass'] = password robj = wsgi.ResponseObject(view) return self._add_location(robj) @wsgi.response(202) @extensions.expected_errors((400, 403, 404, 409)) @wsgi.action('createImage') @common.check_snapshots_enabled @validation.schema(schema_servers.create_image) def _action_create_image(self, req, id, body): """Snapshot a server instance.""" context = req.environ['nova.context'] authorize(context, action='create_image') entity = body["createImage"] image_name = entity["name"] metadata = entity.get('metadata', {}) common.check_img_metadata_properties_quota(context, metadata) instance = self._get_server(context, req, id) bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance.uuid) try: if self.compute_api.is_volume_backed_instance(context, instance, bdms): authorize(context, action="create_image:allow_volume_backed") img = instance.image_ref if not img: properties = bdms.root_metadata( context, self.compute_api.image_api, self.compute_api.volume_api) image_meta = {'properties': properties} else: image_meta = self.compute_api.image_api.get(context, img) image = self.compute_api.snapshot_volume_backed( context, instance, image_meta, image_name, extra_properties= metadata) else: image = self.compute_api.snapshot(context, instance, image_name, extra_properties=metadata) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'createImage', id) except exception.Invalid as err: raise exc.HTTPBadRequest(explanation=err.format_message()) # build location of newly-created image entity image_id = str(image['id']) image_ref = glance.generate_image_url(image_id) resp = webob.Response(status_int=202) resp.headers['Location'] = image_ref return resp def _get_server_admin_password(self, server): """Determine the admin password for a server on creation.""" try: password = server['adminPass'] except KeyError: password = utils.generate_password() return password def _get_server_search_options(self, req): """Return server search options allowed by non-admin.""" opt_list = ('reservation_id', 'name', 'status', 'image', 'flavor', 'ip', 'changes-since', 'all_tenants') req_ver = req.api_version_request if req_ver > api_version_request.APIVersionRequest("2.4"): opt_list += ('ip6',) return opt_list def _get_instance(self, context, instance_uuid): try: attrs = ['system_metadata', 'metadata'] return objects.Instance.get_by_uuid(context, instance_uuid, expected_attrs=attrs) except exception.InstanceNotFound as e: raise webob.exc.HTTPNotFound(explanation=e.format_message()) @wsgi.response(202) @extensions.expected_errors((404, 409)) @wsgi.action('os-start') def _start_server(self, req, id, body): """Start an instance.""" context = req.environ['nova.context'] instance = self._get_instance(context, id) authorize(context, instance, 'start') LOG.debug('start instance', instance=instance) try: self.compute_api.start(context, instance) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'start', id) except (exception.InstanceNotReady, exception.InstanceIsLocked) as e: raise webob.exc.HTTPConflict(explanation=e.format_message()) @wsgi.response(202) @extensions.expected_errors((404, 409)) @wsgi.action('os-stop') def _stop_server(self, req, id, body): """Stop an instance.""" context = req.environ['nova.context'] instance = self._get_instance(context, id) authorize(context, instance, 'stop') LOG.debug('stop instance', instance=instance) try: self.compute_api.stop(context, instance) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'stop', id) except (exception.InstanceNotReady, exception.InstanceIsLocked) as e: raise webob.exc.HTTPConflict(explanation=e.format_message()) def remove_invalid_options(context, search_options, allowed_search_options): """Remove search options that are not valid for non-admin API/context.""" if context.is_admin: # Allow all options return # Otherwise, strip out all unknown options unknown_options = [opt for opt in search_options if opt not in allowed_search_options] LOG.debug("Removing options '%s' from query", ", ".join(unknown_options)) for opt in unknown_options: search_options.pop(opt, None) class Servers(extensions.V3APIExtensionBase): """Servers.""" name = "Servers" alias = ALIAS version = 1 def get_resources(self): member_actions = {'action': 'POST'} collection_actions = {'detail': 'GET'} resources = [ extensions.ResourceExtension( ALIAS, ServersController(extension_info=self.extension_info), member_name='server', collection_actions=collection_actions, member_actions=member_actions)] return resources def get_controller_extensions(self): return []
apache-2.0
jithinbp/SEELablet-apps
seel_res/GUI/B_ELECTRONICS/B_Diodes/D_ZenerIV.py
1
3205
#!/usr/bin/python ''' Study Current Voltage characteristics of PN junctions. ''' from __future__ import print_function import os from SEEL_Apps.utilitiesClass import utilitiesClass from PyQt4 import QtCore, QtGui import time,sys from .templates import ui_diodeIV as diodeIV import sys import pyqtgraph as pg import numpy as np params = { 'image' : 'diodeIV.png', 'helpfile': 'diodeIV.html', 'name':'Zener IV\nCharacteristics', 'hint':"Study Current-Voltage Characteristics of PN junctions.\n uses PV1 as the voltage source for sweeping voltage via a 1K current limiting resistor connected in series. \nThe voltage drop across the diode is monitored via CH1. " } class AppWindow(QtGui.QMainWindow, diodeIV.Ui_MainWindow,utilitiesClass): def __init__(self, parent=None,**kwargs): super(AppWindow, self).__init__(parent) self.setupUi(self) self.I=kwargs.get('I',None) self.setWindowTitle(self.I.H.version_string+' : '+params.get('name','').replace('\n',' ') ) self.plot=self.add2DPlot(self.plot_area) labelStyle = {'color': 'rgb(255,255,255)', 'font-size': '11pt'} self.plot.setLabel('left','Current -->', units='A',**labelStyle) self.plot.setLabel('bottom','Voltage -->', units='V',**labelStyle) self.startV.setValue(-5) self.totalpoints=2000 self.X=[] self.Y=[] self.plotnum=0 self.curves=[] self.curveLabels=[] self.looptimer = self.newTimer() self.looptimer.timeout.connect(self.acquire) def savePlots(self): self.saveDataWindow(self.curves) def run(self): self.looptimer.stop() self.X=[];self.Y=[] self.plotnum+=1 self.curves.append( self.addCurve(self.plot ,'Plot #%d'%(self.plotnum)) ) self.V = self.startV.value() self.I.set_pv1(self.V) time.sleep(0.2) P=self.plot.getPlotItem() P.enableAutoRange(True,True) self.plot.setXRange(-5,1) self.plot.setYRange(-4e-3,4e-3) self.looptimer.start(20) def acquire(self): V=self.I.set_pv1(self.V) VC = self.I.get_voltage('CH1',samples=20) self.X.append(VC) self.Y.append((V-VC)/1.e3) # list( ( np.linspace(V,V+self.stepV.value(),1000)-VC)/1.e3) self.curves[-1].setData(self.X,self.Y) self.V+=self.stepV.value() if self.V>self.stopV.value(): self.looptimer.stop() txt='<div style="text-align: center"><span style="color: #FFF;font-size:8pt;"># %d</span></div>'%(self.plotnum) text = pg.TextItem(html=txt, anchor=(0,0), border='w', fill=(0, 0, 255, 100)) self.plot.addItem(text) text.setPos(self.X[-1],self.Y[-1]) self.curveLabels.append(text) self.tracesBox.addItem('#%d'%(self.plotnum)) def delete_curve(self): c = self.tracesBox.currentIndex() if c>-1: self.tracesBox.removeItem(c) self.removeCurve(self.plot,self.curves[c]); self.plot.removeItem(self.curveLabels[c]); self.curves.pop(c);self.curveLabels.pop(c); if len(self.curves)==0: # reset counter for plot numbers self.plotnum=0 def __del__(self): self.looptimer.stop() print ('bye') def closeEvent(self, event): self.looptimer.stop() self.finished=True if __name__ == "__main__": from SEEL import interface app = QtGui.QApplication(sys.argv) myapp = AppWindow(I=interface.connect()) myapp.show() sys.exit(app.exec_())
gpl-3.0
gaqzi/ansible-modules-extras
notification/slack.py
8
7666
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Ramon de la Fuente <ramon@delafuente.nl> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = """ module: slack short_description: Send Slack notifications description: - The M(slack) module sends notifications to U(http://slack.com) via the Incoming WebHook integration version_added: 1.6 author: '"Ramon de la Fuente (@ramondelafuente)" <ramon@delafuente.nl>' options: domain: description: - Slack (sub)domain for your environment without protocol. (i.e. C(future500.slack.com)) In 1.8 and beyond, this is deprecated and may be ignored. See token documentation for information. required: false token: description: - Slack integration token. This authenticates you to the slack service. Prior to 1.8, a token looked like C(3Ffe373sfhRE6y42Fg3rvf4GlK). In 1.8 and above, ansible adapts to the new slack API where tokens look like C(G922VJP24/D921DW937/3Ffe373sfhRE6y42Fg3rvf4GlK). If tokens are in the new format then slack will ignore any value of domain. If the token is in the old format the domain is required. Ansible has no control of when slack will get rid of the old API. When slack does that the old format will stop working. required: true msg: description: - Message to send. required: true channel: description: - Channel to send the message to. If absent, the message goes to the channel selected for the I(token). required: false username: description: - This is the sender of the message. required: false default: ansible icon_url: description: - Url for the message sender's icon (default C(http://www.ansible.com/favicon.ico)) required: false icon_emoji: description: - Emoji for the message sender. See Slack documentation for options. (if I(icon_emoji) is set, I(icon_url) will not be used) required: false link_names: description: - Automatically create links for channels and usernames in I(msg). required: false default: 1 choices: - 1 - 0 parse: description: - Setting for the message parser at Slack required: false choices: - 'full' - 'none' validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. required: false default: 'yes' choices: - 'yes' - 'no' color: version_added: 2.0 description: - Allow text to use default colors - use the default of 'normal' to not send a custom color bar at the start of the message required: false default: 'normal' choices: - 'normal' - 'good' - 'warning' - 'danger' """ EXAMPLES = """ - name: Send notification message via Slack local_action: module: slack domain: future500.slack.com token: thetokengeneratedbyslack msg: "{{ inventory_hostname }} completed" - name: Send notification message via Slack all options local_action: module: slack domain: future500.slack.com token: thetokengeneratedbyslack msg: "{{ inventory_hostname }} completed" channel: "#ansible" username: "Ansible on {{ inventory_hostname }}" icon_url: "http://www.example.com/some-image-file.png" link_names: 0 parse: 'none' - name: insert a color bar in front of the message for visibility purposes and use the default webhook icon and name configured in Slack slack: domain: future500.slack.com token: thetokengeneratedbyslack msg: "{{ inventory_hostname }} is alive!" color: good username: "" icon_url: "" """ OLD_SLACK_INCOMING_WEBHOOK = 'https://%s/services/hooks/incoming-webhook?token=%s' SLACK_INCOMING_WEBHOOK = 'https://hooks.slack.com/services/%s' def build_payload_for_slack(module, text, channel, username, icon_url, icon_emoji, link_names, parse, color): if color == 'normal': payload = dict(text=text) else: payload = dict(attachments=[dict(text=text, color=color)]) if channel is not None: if (channel[0] == '#') or (channel[0] == '@'): payload['channel'] = channel else: payload['channel'] = '#'+channel if username is not None: payload['username'] = username if icon_emoji is not None: payload['icon_emoji'] = icon_emoji else: payload['icon_url'] = icon_url if link_names is not None: payload['link_names'] = link_names if parse is not None: payload['parse'] = parse payload="payload=" + module.jsonify(payload) return payload def do_notify_slack(module, domain, token, payload): if token.count('/') >= 2: # New style token slack_incoming_webhook = SLACK_INCOMING_WEBHOOK % (token) else: if not domain: module.fail_json(msg="Slack has updated its webhook API. You need to specify a token of the form XXXX/YYYY/ZZZZ in your playbook") slack_incoming_webhook = OLD_SLACK_INCOMING_WEBHOOK % (domain, token) response, info = fetch_url(module, slack_incoming_webhook, data=payload) if info['status'] != 200: obscured_incoming_webhook = SLACK_INCOMING_WEBHOOK % ('[obscured]') module.fail_json(msg=" failed to send %s to %s: %s" % (payload, obscured_incoming_webhook, info['msg'])) def main(): module = AnsibleModule( argument_spec = dict( domain = dict(type='str', required=False, default=None), token = dict(type='str', required=True), msg = dict(type='str', required=True), channel = dict(type='str', default=None), username = dict(type='str', default='Ansible'), icon_url = dict(type='str', default='http://www.ansible.com/favicon.ico'), icon_emoji = dict(type='str', default=None), link_names = dict(type='int', default=1, choices=[0,1]), parse = dict(type='str', default=None, choices=['none', 'full']), validate_certs = dict(default='yes', type='bool'), color = dict(type='str', default='normal', choices=['normal', 'good', 'warning', 'danger']) ) ) domain = module.params['domain'] token = module.params['token'] text = module.params['msg'] channel = module.params['channel'] username = module.params['username'] icon_url = module.params['icon_url'] icon_emoji = module.params['icon_emoji'] link_names = module.params['link_names'] parse = module.params['parse'] color = module.params['color'] payload = build_payload_for_slack(module, text, channel, username, icon_url, icon_emoji, link_names, parse, color) do_notify_slack(module, domain, token, payload) module.exit_json(msg="OK") # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.urls import * main()
gpl-3.0