CombinedText
stringlengths
4
3.42M
#!/usr/bin/env python import logging l = logging.getLogger("simuvex.plugins.memory") import claripy from ..plugins.plugin import SimStatePlugin class SimMemory(SimStatePlugin): def __init__(self, endness=None): SimStatePlugin.__init__(self) self.id = None self._endness = "Iend_BE" if endness is None else endness @staticmethod def _deps_unpack(a): if isinstance(a, SimActionObject): return a.ast, a.reg_deps, a.tmp_deps else: return a, None, None def store(self, addr, data, size=None, condition=None, fallback=None, add_constraints=None, endness=None, action=None): ''' Stores content into memory. @param addr: a claripy expression representing the address to store at @param data: the data to store (claripy expression) @param size: a claripy expression representing the size of the data to store @param condition: (optional) a claripy expression representing a condition if the store is conditional @param fallback: (optional) a claripy expression representing what the write should resolve to if the condition evaluates to false (default: whatever was there before) @param add_constraints: add constraints resulting from the merge (default: True) @param action: a SimActionData to fill out with the final written value and constraints ''' add_constraints = True if add_constraints is None else add_constraints addr_e = _raw_ast(addr) data_e = _raw_ast(data) size_e = _raw_ast(size) condition_e = _raw_ast(condition) fallback_e = _raw_ast(fallback) # TODO: first, simplify stuff if (self.id == 'mem' and o.SIMPLIFY_MEMORY_WRITES) or (self.id == 'reg' and o.SIMPLIFY_REGISTER_WRITES): l.debug("simplifying %s write...", self.id) data_e = self.state.simplify(data_e) # store everything as a BV data_e = data_e.to_bv() # the endness endness = self._endness if endness is None else endness if endness == "Iend_LE": data_e = data_e.reversed if o.AUTO_REFS in self.state.options and action is None: ref_size = size if size is not None else data_e.size() action = SimActionData(self.state, self.id, 'write', addr=addr, data=data, size=ref_size, condition=condition, fallback=fallback) self.state.log.add_action(action) a,r,c = self._store(addr_e, data_e, size=size_e, condition=condition_e, fallback=fallback_e) if add_constraints: self.state.add_constraints(*c) if action is not None: action.actual_addrs = a action.actual_value = action._make_object(r) action.added_constraints = action._make_object(self.state.se.And(*c) if len(c) > 0 else self.state.se.true) def _store(self, addr, data, size=None, condition=None, fallback=None): raise NotImplementedError() def store_cases(self, addr, contents, conditions, fallback=None, add_constraints=None, action=None): ''' Stores content into memory, conditional by case. @param addr: a claripy expression representing the address to store at @param contents: a list of bitvectors, not necessarily of the same size. Use None to denote an empty write @param conditions: a list of conditions. Must be equal in length to contents @param fallback: (optional) a claripy expression representing what the write should resolve to if all conditions evaluate to false (default: whatever was there before) @param add_constraints: add constraints resulting from the merge (default: True) @param action: a SimActionData to fill out with the final written value and constraints ''' if fallback is None and not any([ not c is None for c in contents ]): l.debug("Avoiding an empty write.") return addr_e = _raw_ast(addr) contents_e = _raw_ast(contents) conditions_e = _raw_ast(conditions) fallback_e = _raw_ast(fallback) max_bits = max(c.length for c in contents_e if isinstance(c, claripy.ast.Bits)) if fallback is None else fallback.length fallback_e = self.load(addr, max_bits/8, add_constraints=add_constraints) if fallback_e is None else fallback_e a,r,c = self._store_cases(addr_e, contents_e, conditions_e, fallback_e) if add_constraints: self.state.add_constraints(*c) if o.AUTO_REFS in self.state.options and action is None: action = SimActionData(self.state, self.id, 'write', addr=addr, data=r, size=max_bits/8, condition=self.state.se.Or(*conditions), fallback=fallback) self.state.log.add_action(action) if action is not None: action.actual_addrs = a action.actual_value = action._make_object(r) action.added_constraints = action._make_object(self.state.se.And(*c) if len(c) > 0 else self.state.se.true) def _store_cases(self, addr, contents, conditions, fallback): extended_contents = [ ] for c in contents: if c is None: c = fallback else: need_bits = fallback.length - c.length if need_bits > 0: c = c.concat(fallback[need_bits-1:0]) extended_contents.append(c) cases = zip(conditions, extended_contents) ite = self.state.se.ite_cases(cases, fallback) return self._store(addr, ite) def load(self, addr, size, condition=None, fallback=None, add_constraints=None, action=None): ''' Loads size bytes from dst. @param dst: the address to load from @param size: the size (in bytes) of the load @param condition: a claripy expression representing a condition for a conditional load @param fallback: a fallback value if the condition ends up being False @param add_constraints: add constraints resulting from the merge (default: True) @param action: a SimActionData to fill out with the constraints There are a few possible return values. If no condition or fallback are passed in, then the return is the bytes at the address, in the form of a claripy expression. For example: <A BVV(0x41, 32)> On the other hand, if a condition and fallback are provided, the value is conditional: <A If(condition, BVV(0x41, 32), fallback)> ''' add_constraints = True if add_constraints is None else add_constraints addr_e = _raw_ast(addr) size_e = _raw_ast(size) condition_e = _raw_ast(condition) fallback_e = _raw_ast(fallback) a,r,c = self._load(addr_e, size_e, condition=condition_e, fallback=fallback_e) if add_constraints: self.state.add_constraints(*c) if o.UNINITIALIZED_ACCESS_AWARENESS in self.state.options and \ self.state.uninitialized_access_handler is not None and \ (r.op == 'Reverse' or r.op == 'I') and \ hasattr(r.model, 'uninitialized') and \ r.model.uninitialized: converted_addrs = [ (a[0], a[1]) if not isinstance(a, (tuple, list)) else a for a in self.normalize_address(addr) ] self.state.uninitialized_access_handler(self.id, converted_addrs, size, r, self.state.scratch.bbl_addr, self.state.scratch.stmt_idx) if o.AST_DEPS in self.state.options and self.id == 'reg': r = SimActionObject(r, reg_deps=frozenset((addr,))) if o.AUTO_REFS in self.state.options and action is None: ref_size = size if size is not None else r.size() action = SimActionData(self.state, self.id, 'read', addr=addr, data=r, size=ref_size, condition=condition, fallback=fallback) self.state.log.add_action(action) if action is not None: action.actual_addrs = a action.added_constraints = action._make_object(self.state.se.And(*c) if len(c) > 0 else self.state.se.true) return r def normalize_address(self, addr, is_write=False): #pylint:disable=no-self-use,unused-argument ''' Normalizes the address for use in static analysis (with the abstract memory model). In non-abstract mode, simply returns the address in a single-element list. ''' return [ addr ] def _load(self, addr, size, condition=None, fallback=None): raise NotImplementedError() def find(self, addr, what, max_search=None, max_symbolic_bytes=None, default=None): ''' Returns the address of bytes equal to 'what', starting from 'start'. Note that, if you don't specify a default value, this search could cause the state to go unsat if no possible matching byte exists. @param start: the start address @param what: what to search for @param max_search: search at most this many bytes @param max_symbolic_bytes: search through at most this many symbolic bytes @param default: the default value, if what you're looking for wasn't found @returns an expression representing the address of the matching byte ''' addr = _raw_ast(addr) what = _raw_ast(what) default = _raw_ast(default) r,c,m = self._find(addr, what, max_search=max_search, max_symbolic_bytes=max_symbolic_bytes, default=default) if o.AST_DEPS in self.state.options and self.id == 'reg': r = SimActionObject(r, reg_deps=frozenset((addr,))) return r,c,m def _find(self, addr, what, max_search=None, max_symbolic_bytes=None, default=None): raise NotImplementedError() def copy_contents(self, dst, src, size, condition=None, src_memory=None): ''' Copies data within a memory. @param dst: claripy expression representing the address of the destination @param src: claripy expression representing the address of the source @param src_memory: (optional) copy data from this SimMemory instead of self @param size: claripy expression representing the size of the copy @param condition: claripy expression representing a condition, if the write should be conditional. If this is determined to be false, the size of the copy will be 0 ''' dst = _raw_ast(dst) src = _raw_ast(src) size = _raw_ast(size) condition = _raw_ast(condition) return self._copy_contents(dst, src, size, condition=condition, src_memory=src_memory) def _copy_contents(self, dst, src, size, condition=None, src_memory=None): raise NotImplementedError() from .. import s_options as o from ..s_action import SimActionData from ..s_action_object import SimActionObject, _raw_ast simplify ite conditions in SimMemory #!/usr/bin/env python import logging l = logging.getLogger("simuvex.plugins.memory") import claripy from ..plugins.plugin import SimStatePlugin class SimMemory(SimStatePlugin): def __init__(self, endness=None): SimStatePlugin.__init__(self) self.id = None self._endness = "Iend_BE" if endness is None else endness @staticmethod def _deps_unpack(a): if isinstance(a, SimActionObject): return a.ast, a.reg_deps, a.tmp_deps else: return a, None, None def store(self, addr, data, size=None, condition=None, fallback=None, add_constraints=None, endness=None, action=None): ''' Stores content into memory. @param addr: a claripy expression representing the address to store at @param data: the data to store (claripy expression) @param size: a claripy expression representing the size of the data to store @param condition: (optional) a claripy expression representing a condition if the store is conditional @param fallback: (optional) a claripy expression representing what the write should resolve to if the condition evaluates to false (default: whatever was there before) @param add_constraints: add constraints resulting from the merge (default: True) @param action: a SimActionData to fill out with the final written value and constraints ''' add_constraints = True if add_constraints is None else add_constraints addr_e = _raw_ast(addr) data_e = _raw_ast(data) size_e = _raw_ast(size) condition_e = _raw_ast(condition) fallback_e = _raw_ast(fallback) # TODO: first, simplify stuff if (self.id == 'mem' and o.SIMPLIFY_MEMORY_WRITES) or (self.id == 'reg' and o.SIMPLIFY_REGISTER_WRITES): l.debug("simplifying %s write...", self.id) data_e = self.state.simplify(data_e) # store everything as a BV data_e = data_e.to_bv() # the endness endness = self._endness if endness is None else endness if endness == "Iend_LE": data_e = data_e.reversed if o.AUTO_REFS in self.state.options and action is None: ref_size = size if size is not None else data_e.size() action = SimActionData(self.state, self.id, 'write', addr=addr, data=data, size=ref_size, condition=condition, fallback=fallback) self.state.log.add_action(action) a,r,c = self._store(addr_e, data_e, size=size_e, condition=condition_e, fallback=fallback_e) if add_constraints: self.state.add_constraints(*c) if action is not None: action.actual_addrs = a action.actual_value = action._make_object(r) action.added_constraints = action._make_object(self.state.se.And(*c) if len(c) > 0 else self.state.se.true) def _store(self, addr, data, size=None, condition=None, fallback=None): raise NotImplementedError() def store_cases(self, addr, contents, conditions, fallback=None, add_constraints=None, action=None): ''' Stores content into memory, conditional by case. @param addr: a claripy expression representing the address to store at @param contents: a list of bitvectors, not necessarily of the same size. Use None to denote an empty write @param conditions: a list of conditions. Must be equal in length to contents @param fallback: (optional) a claripy expression representing what the write should resolve to if all conditions evaluate to false (default: whatever was there before) @param add_constraints: add constraints resulting from the merge (default: True) @param action: a SimActionData to fill out with the final written value and constraints ''' if fallback is None and not any([ not c is None for c in contents ]): l.debug("Avoiding an empty write.") return addr_e = _raw_ast(addr) contents_e = _raw_ast(contents) conditions_e = _raw_ast(conditions) fallback_e = _raw_ast(fallback) max_bits = max(c.length for c in contents_e if isinstance(c, claripy.ast.Bits)) if fallback is None else fallback.length fallback_e = self.load(addr, max_bits/8, add_constraints=add_constraints) if fallback_e is None else fallback_e a,r,c = self._store_cases(addr_e, contents_e, conditions_e, fallback_e) if add_constraints: self.state.add_constraints(*c) if o.AUTO_REFS in self.state.options and action is None: action = SimActionData(self.state, self.id, 'write', addr=addr, data=r, size=max_bits/8, condition=self.state.se.Or(*conditions), fallback=fallback) self.state.log.add_action(action) if action is not None: action.actual_addrs = a action.actual_value = action._make_object(r) action.added_constraints = action._make_object(self.state.se.And(*c) if len(c) > 0 else self.state.se.true) def _store_cases(self, addr, contents, conditions, fallback): extended_contents = [ ] for c in contents: if c is None: c = fallback else: need_bits = fallback.length - c.length if need_bits > 0: c = c.concat(fallback[need_bits-1:0]) extended_contents.append(self.state.se.simplify(c.simplified).simplified) cases = zip(conditions, extended_contents) ite = self.state.se.simplify(self.state.se.ite_cases(cases, fallback).simplified).simplified return self._store(addr, ite) def load(self, addr, size, condition=None, fallback=None, add_constraints=None, action=None): ''' Loads size bytes from dst. @param dst: the address to load from @param size: the size (in bytes) of the load @param condition: a claripy expression representing a condition for a conditional load @param fallback: a fallback value if the condition ends up being False @param add_constraints: add constraints resulting from the merge (default: True) @param action: a SimActionData to fill out with the constraints There are a few possible return values. If no condition or fallback are passed in, then the return is the bytes at the address, in the form of a claripy expression. For example: <A BVV(0x41, 32)> On the other hand, if a condition and fallback are provided, the value is conditional: <A If(condition, BVV(0x41, 32), fallback)> ''' add_constraints = True if add_constraints is None else add_constraints addr_e = _raw_ast(addr) size_e = _raw_ast(size) condition_e = _raw_ast(condition) fallback_e = _raw_ast(fallback) a,r,c = self._load(addr_e, size_e, condition=condition_e, fallback=fallback_e) if add_constraints: self.state.add_constraints(*c) if o.UNINITIALIZED_ACCESS_AWARENESS in self.state.options and \ self.state.uninitialized_access_handler is not None and \ (r.op == 'Reverse' or r.op == 'I') and \ hasattr(r.model, 'uninitialized') and \ r.model.uninitialized: converted_addrs = [ (a[0], a[1]) if not isinstance(a, (tuple, list)) else a for a in self.normalize_address(addr) ] self.state.uninitialized_access_handler(self.id, converted_addrs, size, r, self.state.scratch.bbl_addr, self.state.scratch.stmt_idx) if o.AST_DEPS in self.state.options and self.id == 'reg': r = SimActionObject(r, reg_deps=frozenset((addr,))) if o.AUTO_REFS in self.state.options and action is None: ref_size = size if size is not None else r.size() action = SimActionData(self.state, self.id, 'read', addr=addr, data=r, size=ref_size, condition=condition, fallback=fallback) self.state.log.add_action(action) if action is not None: action.actual_addrs = a action.added_constraints = action._make_object(self.state.se.And(*c) if len(c) > 0 else self.state.se.true) return r def normalize_address(self, addr, is_write=False): #pylint:disable=no-self-use,unused-argument ''' Normalizes the address for use in static analysis (with the abstract memory model). In non-abstract mode, simply returns the address in a single-element list. ''' return [ addr ] def _load(self, addr, size, condition=None, fallback=None): raise NotImplementedError() def find(self, addr, what, max_search=None, max_symbolic_bytes=None, default=None): ''' Returns the address of bytes equal to 'what', starting from 'start'. Note that, if you don't specify a default value, this search could cause the state to go unsat if no possible matching byte exists. @param start: the start address @param what: what to search for @param max_search: search at most this many bytes @param max_symbolic_bytes: search through at most this many symbolic bytes @param default: the default value, if what you're looking for wasn't found @returns an expression representing the address of the matching byte ''' addr = _raw_ast(addr) what = _raw_ast(what) default = _raw_ast(default) r,c,m = self._find(addr, what, max_search=max_search, max_symbolic_bytes=max_symbolic_bytes, default=default) if o.AST_DEPS in self.state.options and self.id == 'reg': r = SimActionObject(r, reg_deps=frozenset((addr,))) return r,c,m def _find(self, addr, what, max_search=None, max_symbolic_bytes=None, default=None): raise NotImplementedError() def copy_contents(self, dst, src, size, condition=None, src_memory=None): ''' Copies data within a memory. @param dst: claripy expression representing the address of the destination @param src: claripy expression representing the address of the source @param src_memory: (optional) copy data from this SimMemory instead of self @param size: claripy expression representing the size of the copy @param condition: claripy expression representing a condition, if the write should be conditional. If this is determined to be false, the size of the copy will be 0 ''' dst = _raw_ast(dst) src = _raw_ast(src) size = _raw_ast(size) condition = _raw_ast(condition) return self._copy_contents(dst, src, size, condition=condition, src_memory=src_memory) def _copy_contents(self, dst, src, size, condition=None, src_memory=None): raise NotImplementedError() from .. import s_options as o from ..s_action import SimActionData from ..s_action_object import SimActionObject, _raw_ast
import sys import time import logging from threading import Thread import urwid from .leetcode import Leetcode, Quiz from views.home import HomeView from views.detail import DetailView from views.help import HelpView from views.loading import * from views.viewhelper import * from views.result import ResultView from .config import config import auth from .code import * palette = [ ('body', 'dark cyan', ''), ('focus', 'white', ''), ('head', 'white', 'dark gray'), ('lock', 'dark gray', ''), ('tag', 'white', 'light cyan', 'standout'), ('hometag', 'dark red', ''), ('accepted', 'dark green', '') ] class Terminal(object): def __init__(self): self.home_view = None self.loop = None self.leetcode = Leetcode() self.help_view = None self.quit_confirm_view = None self.submit_confirm_view = None self.view_stack = [] self.detail_view = None self.search_view = None self.loading_view = None self.logger = logging.getLogger(__name__) @property def current_view(self): return None if not len(self.view_stack) else self.view_stack[-1] @property def is_home(self): return len(self.view_stack) == 1 def goto_view(self, view): self.loop.widget = view self.view_stack.append(view) def go_back(self): self.view_stack.pop() self.loop.widget = self.current_view def keystroke(self, key): if self.quit_confirm_view and self.current_view == self.quit_confirm_view: if key is 'y': raise urwid.ExitMainLoop() else: self.go_back() elif self.submit_confirm_view and self.current_view == self.submit_confirm_view: self.go_back() if key is 'y': self.send_code(self.detail_view.quiz) elif self.current_view == self.search_view: if key is 'enter': text = self.search_view.contents[1][0].original_widget.get_edit_text() self.home_view.handle_search(text) self.go_back() elif key is 'esc': self.go_back() elif key in ('q', 'Q'): self.goto_view(self.make_quit_confirmation()) elif key is 's': self.goto_view(self.make_submit_confirmation()) elif not self.is_home and (key is 'left' or key is 'h'): self.go_back() elif key is 'H': if not self.help_view: self.make_helpview() self.goto_view(self.help_view) elif key is 'R': if self.is_home: self.reload_list() elif key is 'f': if self.is_home: self.enter_search() elif key in ('enter', 'right'): if self.is_home and self.home_view.is_current_item_enterable(): self.enter_detail(self.home_view.get_current_item_data()) else: return key def enter_search(self): self.make_search_view() self.goto_view(self.search_view) def enter_detail(self, data): self.show_loading('Loading Quiz', 17, self.current_view) self.t = Thread(target=self.run_retrieve_detail, args=(data,)) self.t.start() def reload_list(self): '''Press R in home view to retrieve quiz list''' self.leetcode.load() if self.leetcode.quizzes and len(self.leetcode.quizzes) > 0: self.home_view = self.make_listview(self.leetcode.quizzes) self.view_stack = [] self.goto_view(self.home_view) def make_quit_confirmation(self): text = urwid.AttrMap(urwid.Text('Do you really want to quit ? (y/n)'), 'body') self.quit_confirm_view = urwid.Overlay(text, self.current_view, 'left', ('relative', 100), 'bottom', None) return self.quit_confirm_view def make_submit_confirmation(self): text = urwid.AttrMap(urwid.Text('Do you want to submit your code ? (y/n)'), 'body') self.submit_confirm_view = urwid.Overlay(text, self.current_view, 'left', ('relative', 100), 'bottom', None) return self.submit_confirm_view def make_search_view(self): text = urwid.AttrMap(urwid.Edit('Search by id: ', ''), 'body') self.search_view = urwid.Overlay(text, self.current_view, 'left', ('relative', 100), 'bottom', None) return self.search_view def make_detailview(self, data): self.detail_view = DetailView(data, self.loop) return self.detail_view def make_listview(self, data): header = self.make_header() self.home_view = HomeView(data, header) return self.home_view def make_header(self): if self.leetcode.is_login: columns = [ ('fixed', 15, urwid.Padding(urwid.AttrWrap( urwid.Text('%s' % config.username), 'head', ''))), urwid.AttrWrap(urwid.Text('You have solved %d / %d problems. ' % (len(self.leetcode.solved), len(self.leetcode.quizzes))), 'head', ''), ] return urwid.Columns(columns) else: text = urwid.AttrWrap(urwid.Text('Not login'), 'head') return text def make_helpview(self): self.help_view = HelpView() return self.help_view def show_loading(self, text, width, host_view=urwid.SolidFill()): self.loading_view = LoadingView(text, width, host_view, self.loop) self.loop.widget = self.loading_view self.loading_view.start() def end_loading(self): if self.loading_view: self.loading_view.end() self.loading_view = None def retrieve_home_done(self, quizzes): self.home_view = self.make_listview(quizzes) self.view_stack = [] self.goto_view(self.home_view) self.end_loading() delay_refresh(self.loop) def retrieve_detail_done(self, data): data.id = self.home_view.listbox.get_focus()[0].data.id data.url = self.home_view.listbox.get_focus()[0].data.url self.goto_view(self.make_detailview(data)) self.end_loading() delay_refresh(self.loop) def run_retrieve_home(self): self.leetcode.is_login = auth.is_login() if not self.leetcode.is_login: self.leetcode.is_login = auth.login() if self.loading_view: self.loading_view.set_text('Loading') self.leetcode.load() if self.leetcode.quizzes and len(self.leetcode.quizzes) > 0: self.retrieve_home_done(self.leetcode.quizzes) else: self.end_loading() toast = Toast('Request fail!', 10, self.current_view, self.loop) toast.show() self.logger.error('get quiz list fail') def run_retrieve_detail(self, quiz): ret = quiz.load() if ret: self.retrieve_detail_done(quiz) else: self.end_loading() toast = Toast('Request fail!', 10, self.current_view, self.loop) toast.show() self.logger.error('get detail %s fail', quiz.id) def run_send_code(self, quiz): filepath = get_code_file_path(quiz.id) if not os.path.exists(filepath): return code = get_code_for_submission(filepath) code = code.replace('\n', '\r\n') success, text_or_id = quiz.submit(code) if success: self.loading_view.set_text('Retrieving') code = 1 while code > 0: r = quiz.check_submission_result(text_or_id) code = r[0] self.end_loading() if code < -1: toast = Toast('error: %s' % r[1], 10 + len(r[1]), self.current_view, self.loop) toast.show() else: try: result = ResultView(quiz, self.detail_view, r[1], loop=self.loop) result.show() except ValueError as e: toast = Toast('error: %s' % e, 10 + len(str(e)), self.current_view, self.loop) toast.show() delay_refresh(self.loop) else: self.end_loading() toast = Toast('error: %s' % text_or_id, 10 + len(text_or_id), self.current_view, self.loop) toast.show() self.logger.error('send data fail') def send_code(self, data): self.show_loading('Sending code', 17, self.current_view) self.t = Thread(target=self.run_send_code, args=(data,)) self.t.start() def run(self): self.loop = urwid.MainLoop(None, palette, unhandled_input=self.keystroke) self.show_loading('Log In', 12) self.t = Thread(target=self.run_retrieve_home) self.t.start() try: self.loop.run() except KeyboardInterrupt: self.logger.info('Keyboard interrupt') except Exception,e: self.logger.exception("Fatal error in main loop") finally: self.clear_thread() sys.exit() def clear_thread(self): if self.loading_view: self.loading_view.end() if self.t and self.t.is_alive(): t.join() disable s in main view import sys import time import logging from threading import Thread import urwid from .leetcode import Leetcode, Quiz from views.home import HomeView from views.detail import DetailView from views.help import HelpView from views.loading import * from views.viewhelper import * from views.result import ResultView from .config import config import auth from .code import * palette = [ ('body', 'dark cyan', ''), ('focus', 'white', ''), ('head', 'white', 'dark gray'), ('lock', 'dark gray', ''), ('tag', 'white', 'light cyan', 'standout'), ('hometag', 'dark red', ''), ('accepted', 'dark green', '') ] class Terminal(object): def __init__(self): self.home_view = None self.loop = None self.leetcode = Leetcode() self.help_view = None self.quit_confirm_view = None self.submit_confirm_view = None self.view_stack = [] self.detail_view = None self.search_view = None self.loading_view = None self.logger = logging.getLogger(__name__) @property def current_view(self): return None if not len(self.view_stack) else self.view_stack[-1] @property def is_home(self): return len(self.view_stack) == 1 def goto_view(self, view): self.loop.widget = view self.view_stack.append(view) def go_back(self): self.view_stack.pop() self.loop.widget = self.current_view def keystroke(self, key): if self.quit_confirm_view and self.current_view == self.quit_confirm_view: if key is 'y': raise urwid.ExitMainLoop() else: self.go_back() elif self.submit_confirm_view and self.current_view == self.submit_confirm_view: self.go_back() if key is 'y': self.send_code(self.detail_view.quiz) elif self.current_view == self.search_view: if key is 'enter': text = self.search_view.contents[1][0].original_widget.get_edit_text() self.home_view.handle_search(text) self.go_back() elif key is 'esc': self.go_back() elif key in ('q', 'Q'): self.goto_view(self.make_quit_confirmation()) elif key is 's': if not self.is_home: self.goto_view(self.make_submit_confirmation()) elif not self.is_home and (key is 'left' or key is 'h'): self.go_back() elif key is 'H': if not self.help_view: self.make_helpview() self.goto_view(self.help_view) elif key is 'R': if self.is_home: self.reload_list() elif key is 'f': if self.is_home: self.enter_search() elif key in ('enter', 'right'): if self.is_home and self.home_view.is_current_item_enterable(): self.enter_detail(self.home_view.get_current_item_data()) else: return key def enter_search(self): self.make_search_view() self.goto_view(self.search_view) def enter_detail(self, data): self.show_loading('Loading Quiz', 17, self.current_view) self.t = Thread(target=self.run_retrieve_detail, args=(data,)) self.t.start() def reload_list(self): '''Press R in home view to retrieve quiz list''' self.leetcode.load() if self.leetcode.quizzes and len(self.leetcode.quizzes) > 0: self.home_view = self.make_listview(self.leetcode.quizzes) self.view_stack = [] self.goto_view(self.home_view) def make_quit_confirmation(self): text = urwid.AttrMap(urwid.Text('Do you really want to quit ? (y/n)'), 'body') self.quit_confirm_view = urwid.Overlay(text, self.current_view, 'left', ('relative', 100), 'bottom', None) return self.quit_confirm_view def make_submit_confirmation(self): text = urwid.AttrMap(urwid.Text('Do you want to submit your code ? (y/n)'), 'body') self.submit_confirm_view = urwid.Overlay(text, self.current_view, 'left', ('relative', 100), 'bottom', None) return self.submit_confirm_view def make_search_view(self): text = urwid.AttrMap(urwid.Edit('Search by id: ', ''), 'body') self.search_view = urwid.Overlay(text, self.current_view, 'left', ('relative', 100), 'bottom', None) return self.search_view def make_detailview(self, data): self.detail_view = DetailView(data, self.loop) return self.detail_view def make_listview(self, data): header = self.make_header() self.home_view = HomeView(data, header) return self.home_view def make_header(self): if self.leetcode.is_login: columns = [ ('fixed', 15, urwid.Padding(urwid.AttrWrap( urwid.Text('%s' % config.username), 'head', ''))), urwid.AttrWrap(urwid.Text('You have solved %d / %d problems. ' % (len(self.leetcode.solved), len(self.leetcode.quizzes))), 'head', ''), ] return urwid.Columns(columns) else: text = urwid.AttrWrap(urwid.Text('Not login'), 'head') return text def make_helpview(self): self.help_view = HelpView() return self.help_view def show_loading(self, text, width, host_view=urwid.SolidFill()): self.loading_view = LoadingView(text, width, host_view, self.loop) self.loop.widget = self.loading_view self.loading_view.start() def end_loading(self): if self.loading_view: self.loading_view.end() self.loading_view = None def retrieve_home_done(self, quizzes): self.home_view = self.make_listview(quizzes) self.view_stack = [] self.goto_view(self.home_view) self.end_loading() delay_refresh(self.loop) def retrieve_detail_done(self, data): data.id = self.home_view.listbox.get_focus()[0].data.id data.url = self.home_view.listbox.get_focus()[0].data.url self.goto_view(self.make_detailview(data)) self.end_loading() delay_refresh(self.loop) def run_retrieve_home(self): self.leetcode.is_login = auth.is_login() if not self.leetcode.is_login: self.leetcode.is_login = auth.login() if self.loading_view: self.loading_view.set_text('Loading') self.leetcode.load() if self.leetcode.quizzes and len(self.leetcode.quizzes) > 0: self.retrieve_home_done(self.leetcode.quizzes) else: self.end_loading() toast = Toast('Request fail!', 10, self.current_view, self.loop) toast.show() self.logger.error('get quiz list fail') def run_retrieve_detail(self, quiz): ret = quiz.load() if ret: self.retrieve_detail_done(quiz) else: self.end_loading() toast = Toast('Request fail!', 10, self.current_view, self.loop) toast.show() self.logger.error('get detail %s fail', quiz.id) def run_send_code(self, quiz): filepath = get_code_file_path(quiz.id) if not os.path.exists(filepath): return code = get_code_for_submission(filepath) code = code.replace('\n', '\r\n') success, text_or_id = quiz.submit(code) if success: self.loading_view.set_text('Retrieving') code = 1 while code > 0: r = quiz.check_submission_result(text_or_id) code = r[0] self.end_loading() if code < -1: toast = Toast('error: %s' % r[1], 10 + len(r[1]), self.current_view, self.loop) toast.show() else: try: result = ResultView(quiz, self.detail_view, r[1], loop=self.loop) result.show() except ValueError as e: toast = Toast('error: %s' % e, 10 + len(str(e)), self.current_view, self.loop) toast.show() delay_refresh(self.loop) else: self.end_loading() toast = Toast('error: %s' % text_or_id, 10 + len(text_or_id), self.current_view, self.loop) toast.show() self.logger.error('send data fail') def send_code(self, data): self.show_loading('Sending code', 17, self.current_view) self.t = Thread(target=self.run_send_code, args=(data,)) self.t.start() def run(self): self.loop = urwid.MainLoop(None, palette, unhandled_input=self.keystroke) self.show_loading('Log In', 12) self.t = Thread(target=self.run_retrieve_home) self.t.start() try: self.loop.run() except KeyboardInterrupt: self.logger.info('Keyboard interrupt') except Exception,e: self.logger.exception("Fatal error in main loop") finally: self.clear_thread() sys.exit() def clear_thread(self): if self.loading_view: self.loading_view.end() if self.t and self.t.is_alive(): t.join()
#!/usr/bin/env python # # The MIT License (MIT) # # Copyright (c) 2015 Kevin Griesser, 2016 Matthew A. Klein, William Baskin # # 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 rospy import math from math import sin, cos from geometry_msgs.msg import Twist from sensor_msgs.msg import LaserScan from collections import namedtuple Obstacle = namedtuple('Obstacle', ['r', 'theta']) class ObstacleAvoidance: def __init__(self): self.last_scan = [] rospy.init_node('obstacle_avoidance') self.MAX_WIDTH = rospy.get_param('~maximum_width', 1) # input is lidar data lidarTopic = rospy.get_param('~lidar_topic', 'base_scan') rospy.Subscriber(lidarTopic, LaserScan, self.obsDetect) # and commanded velocity (pre obstaacle detection) inVelTopic = rospy.get_param('~in_vel_topic', 'cmd_vel_pre') rospy.Subscriber(inVelTopic, Twist, self.obsAvoid) # output is velocity command (to avoid the obstacle) outVelTopic = rospy.get_param('~out_vel_topic', 'cmd_vel') self.velPub = rospy.Publisher(outVelTopic, Twist, queue_size = 1) def obsDetect(self, msg: LaserScan): # Detect obstacles using incoming LIDAR scan self.last_scan = msg min_angle = msg.angle_min max_angle = msg.angle_max angle_increment = msg.angle_increment readings = [] for index, range_ in enumerate(msg.ranges): angle = min_angle + index*angle_increment r = range_ readings.append(Obstacle(r=r, theta=angle)) self.last_readings = readings def obsAvoid(self, msg: Twist): # Create a twist message vel_cmd = Twist() # Filter out points that are outside the travel circle filtered_points = self.filter_by_drive_circle( msg.linear.x, msg.angular.z, self.last_readings) # Identify the (0, 1, 2) points that need to be avoided left, right = self.select_closest_obstacles(v, w, filtered_points) # Calculate the minimum change to avoid those points # Choose that as the adjustment to make to cmd_vel # Do stuff (Currently just a pass through.) vel_cmd.linear.x = msg.linear.x vel_cmd.angular.z = msg.angular.z # Publish velocity command to avoid obstacle self.velPub.publish(vel_cmd) def filter_by_drive_circle(self, v, w, points): if (abs(w) < 0.001): # drive stright case for point in points: dx = point.r * sin(point.theta) dy = point.r * cos(point.theta) if abs(dx) < self.MAX_WIDTH / 2.: yield point else: # curved case travel_r = v / w min_avoidance_r = travel_r - self.MAX_WIDTH/2.0 max_avoidance_r = travel_r + self.MAX_WIDTH/2.0 for point in points: dx_robot = point.r * sin(point.theta) dy_robot = point.r * cos(point.theta) dx_turning = dx_robot + travel_r point_turing_radius = math.sqrt(math.pow(dx_turning, 2)+math.pow(dy_robot, 2)) if (point_turning_radius > min_avoidance_r and point_turning_radius < max_avoidance_r): yield point def select_closest_obstacles(self, v, w, points): if len(points) <= 0: return (None, None,) elif len(points) == 1: return (points[0], points[0]) for index, point in enumerate(points): pass return (points[0], points[1],) if __name__ == "__main__": oa = ObstacleAvoidance() rospy.spin() Added semicircle filter. #!/usr/bin/env python # # The MIT License (MIT) # # Copyright (c) 2015 Kevin Griesser, 2016 Matthew A. Klein, William Baskin # # 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 rospy import math from math import sin, cos from geometry_msgs.msg import Twist from sensor_msgs.msg import LaserScan from collections import namedtuple Obstacle = namedtuple('Obstacle', ['r', 'theta']) class ObstacleAvoidance: def __init__(self): self.last_scan = [] rospy.init_node('obstacle_avoidance') self.PATH_WIDTH = rospy.get_param('~path_width', 1) self.R_MAX = rospy.get_param('~r_max', 3) # input is lidar data lidarTopic = rospy.get_param('~lidar_topic', 'base_scan') rospy.Subscriber(lidarTopic, LaserScan, self.detectObstacles) # and commanded velocity (pre obstaacle detection) inVelTopic = rospy.get_param('~in_vel_topic', 'cmd_vel_pre') rospy.Subscriber(inVelTopic, Twist, self.avoidObstacles) # output is velocity command (to avoid the obstacle) outVelTopic = rospy.get_param('~out_vel_topic', 'cmd_vel') self.velPub = rospy.Publisher(outVelTopic, Twist, queue_size = 1) def detectObstacles(self, msg: LaserScan): # Detect obstacles using incoming LIDAR scan self.last_scan = msg min_angle = msg.angle_min max_angle = msg.angle_max angle_increment = msg.angle_increment readings = [] for index, range_ in enumerate(msg.ranges): angle = min_angle + index*angle_increment r = range_ readings.append(Obstacle(r=r, theta=angle)) self.last_readings = readings def avoidObstacles(self, msg: Twist): # Create a twist message vel_cmd = Twist() # Filter out points that are outside the travel circle filtered_points = self.filterBySemicircleROI(self.last_readings, self.R_MAX) # Identify The (0, 1, 2) points that need to be avoided left, right = self.select_closest_obstacles(v, w, filtered_points) # Calculate the minimum change to avoid those points # Choose that as the adjustment to make to cmd_vel # Do stuff (Currently just a pass through.) vel_cmd.linear.x = msg.linear.x vel_cmd.angular.z = msg.angular.z # Publish velocity command to avoid obstacle self.velPub.publish(vel_cmd) def filterBySemicircleROI(ranges,rMax): for range in ranges: if range < rMax: yield range def filter_by_drive_circle(self, v, w, points): if (abs(w) < 0.001): # drive stright case for point in points: dx = point.r * sin(point.theta) dy = point.r * cos(point.theta) if abs(dx) < self.PATH_WIDTH / 2.: yield point else: # curved case travel_r = v / w min_avoidance_r = travel_r - self.PATH_WIDTH/2.0 max_avoidance_r = travel_r + self.PATH_WIDTH/2.0 for point in points: dx_robot = point.r * sin(point.theta) dy_robot = point.r * cos(point.theta) dx_turning = dx_robot + travel_r point_turing_radius = math.sqrt(math.pow(dx_turning, 2)+math.pow(dy_robot, 2)) if (point_turning_radius > min_avoidance_r and point_turning_radius < max_avoidance_r): yield point def select_closest_obstacles(self, v, w, points): if len(points) <= 0: return (None, None,) elif len(points) == 1: return (points[0], points[0]) for index, point in enumerate(points): pass return (points[0], points[1],) if __name__ == "__main__": oa = ObstacleAvoidance() rospy.spin()
from cm.utils.embed import embed_html from cm.activity import register_activity from cm.client import jsonize, get_filter_datas, edit_comment, remove_comment, \ add_comment, RequestComplexEncoder, comments_thread, own_notify from cm.cm_settings import NEW_TEXT_VERSION_ON_EDIT from cm.exception import UnauthorizedException from cm.message import * from cm.models import * from django.forms.util import ErrorList from cm.models_base import generate_key from cm.security import get_texts_with_perm, has_perm, get_viewable_comments, \ has_perm_on_text from cm.utils import get_among, get_among, get_int from cm.utils.html import on_content_receive from cm.utils.comment_positioning import compute_new_comment_positions, \ insert_comment_markers from cm.utils.spannifier import spannify from cm.views import get_keys_from_dict, get_textversion_by_keys_or_404, get_text_by_keys_or_404, redirect from cm.views.export import content_export2, content_export from cm.views.user import AnonUserRoleForm, cm_login from difflib import unified_diff from django import forms from django.conf import settings from django.contrib.auth import login as django_login from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db.models import Q from django.forms import ModelForm from django.forms.models import BaseModelFormSet, modelformset_factory from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.template.loader import render_to_string from django.utils.translation import ugettext as _, ugettext_lazy from django.views.generic.list_detail import object_list from tagging.models import Tag import difflib import logging import mimetypes import simplejson import sys import re from django.db.models.sql.datastructures import EmptyResultSet def get_text_and_admin(key, adminkey, assert_admin = False): """ assert_admin => redirect to unauthorized if not admin """ admin = False if adminkey: text = Text.objects.get(key = key, adminkey = adminkey) if text: admin = True else: text = Text.objects.get(key=key) if assert_admin and not admin: raise UnauthorizedException('Is not admin') return text, admin ACTIVITY_PAGINATION = 10 RECENT_TEXT_NB = 5 RECENT_COMMENT_NB = RECENT_TEXT_NB MODERATE_NB = 5 def dashboard(request): request.session.set_test_cookie() if request.user.is_authenticated(): act_view = { 'view_texts' : get_int(request.GET,'view_texts',1), 'view_comments' : get_int(request.GET,'view_comments',1), 'view_users' : get_int(request.GET,'view_users',1), } paginate_by = get_int(request.GET,'paginate',ACTIVITY_PAGINATION) # texts with can_view_unapproved_comment perms moderator_texts = get_texts_with_perm(request, 'can_view_unapproved_comment') viewer_texts = get_texts_with_perm(request, 'can_view_approved_comment') all_texts_ids = [t.id for t in moderator_texts] + [t.id for t in viewer_texts] span = get_among(request.GET,'span',('day','month','week',),'week') template_dict = { 'span' : span, 'last_texts' : get_texts_with_perm(request, 'can_view_text').order_by('-modified')[:RECENT_TEXT_NB], 'last_comments' : Comment.objects.filter(text_version__text__in=all_texts_ids).order_by('-created')[:RECENT_COMMENT_NB],# TODO: useful? #'last_users' : User.objects.all().order_by('-date_joined')[:5], } template_dict.update(act_view) all_activities = { 'view_comments' : ['comment_created','comment_removed'], 'view_users' : ['user_created', 'user_activated', 'user_suspended','user_enabled',], 'view_texts' : ['text_created','text_removed', 'text_edited', 'text_edited_new_version'], } selected_activities = [] [selected_activities.extend(all_activities[k]) for k in act_view.keys() if act_view[k]] activities = Activity.objects.filter(type__in = selected_activities) if not has_perm(request,'can_manage_workspace'): texts = get_texts_with_perm(request, 'can_view_text') activities = activities.filter(Q(text__in=texts)) comments = [] [comments.extend(get_viewable_comments(request, t.last_text_version.comment_set.all(), t)) for t in texts] activities = activities.filter(Q(comment__in=comments) | Q(comment=None) ) template_dict['to_mod_profiles'] = [] else: template_dict['to_mod_profiles'] = UserProfile.objects.filter(user__is_active=False).filter(is_suspended=True).order_by('-user__date_joined')[:MODERATE_NB] template_dict['to_mod_comments'] = Comment.objects.filter(state='pending').filter(text_version__text__in=moderator_texts).order_by('-modified')[:MODERATE_NB-len(template_dict['to_mod_profiles'])] activities = activities.order_by('-created') return object_list(request, activities, template_name = 'site/dashboard.html', paginate_by = paginate_by, extra_context = template_dict, ) else: if request.method == 'POST': form = AuthenticationForm(request, request.POST) if form.is_valid(): user = form.get_user() user.backend = 'django.contrib.auth.backends.ModelBackend' cm_login(request, user) display_message(request, _(u"You're logged in!")) return HttpResponseRedirect(reverse('index')) else: form = AuthenticationForm() public_texts = get_texts_with_perm(request, 'can_view_text').order_by('-modified') template_dict = { 'form' : form, 'texts' : public_texts, } return render_to_response('site/non_authenticated_index.html', template_dict, context_instance=RequestContext(request)) TEXT_PAGINATION = 10 # security check inside view # TODO: set global access perm def text_list(request): paginate_by = get_int(request.GET,'paginate',TEXT_PAGINATION) tag_selected = request.GET.get('tag_selected', 0) order_by = get_among(request.GET,'order',('title','author','modified','-title','-author','-modified'),'-modified') if request.method == 'POST': action = request.POST.get('action',None) text_keys = get_keys_from_dict(request.POST, 'check-').keys() if action == 'delete': for text_key in text_keys: text = Text.objects.get(key=text_key) if has_perm(request, 'can_delete_text', text=text): text.delete() else: raise UnauthorizedException('No perm can_delete_text on comment') display_message(request, _(u'%(nb_texts)i text(s) deleted') %{'nb_texts':len(text_keys)}) return HttpResponseRedirect(reverse('text')) texts = get_texts_with_perm(request, 'can_view_text').order_by(order_by) try: tag_list = Tag.objects.usage_for_queryset(TextVersion.objects.filter(id__in = [t.last_text_version_id for t in get_texts_with_perm(request, 'can_view_text')])) except EmptyResultSet: tag_list = [] context = { 'tag_list' : tag_list, 'tag_selected': tag_selected, } if tag_selected: tag_ids = Tag.objects.filter(name=tag_selected) if tag_ids: content_type_id = ContentType.objects.get_for_model(TextVersion).pk # table cm_userprofile is not present if display_suspended_users: fix this texts = texts.extra(where=['tagging_taggeditem.object_id = cm_text.last_text_version_id', 'tagging_taggeditem.content_type_id = %i' %content_type_id, 'tagging_taggeditem.tag_id = %i' %tag_ids[0].id], tables=['tagging_taggeditem'], ) return object_list(request, texts, template_name = 'site/text_list.html', paginate_by = paginate_by, extra_context=context, ) @has_perm_on_text('can_view_text') def text_view(request, key, adminkey=None): text = get_text_by_keys_or_404(key) register_activity(request, "text_view", text=text) text_version = text.get_latest_version() embed_code = embed_html(key, 'id="text_view_frame" name="text_view_frame"', None, request.META.get('QUERY_STRING')) template_dict = { 'embed_code':embed_code, 'text' : text, 'text_version' : text_version, 'title' : text_version.title, 'content' : text_version.get_content()} return render_to_response('site/text_view.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_delete_text') def text_delete(request, key): text = Text.objects.get(key=key) if request.method != 'POST': raise UnauthorizedException('Unauthorized') display_message(request, _(u'Text %(text_title)s deleted') %{'text_title':text.title}) register_activity(request, "text_removed", text=text) text.delete() return HttpResponse('') # no redirect because this is called by js @has_perm_on_text('can_delete_text') def text_version_delete(request, key, text_version_key): text_version = TextVersion.objects.get(key=text_version_key) text=text_version.text if request.method != 'POST': raise UnauthorizedException('Unauthorized') display_message(request, _(u'Text version %(text_version_title)s deleted') %{'text_version_title':text_version.title}) register_activity(request, "text_version_removed", text=text) text_version.delete() return HttpResponse('') # no redirect because this is called by js @has_perm_on_text('can_view_text') # only protected by text_view / comment filtering done in view def text_view_comments(request, key, version_key=None, adminkey=None): text = get_text_by_keys_or_404(key) read_only = False if version_key : text_version = get_textversion_by_keys_or_404(version_key, adminkey, key) if settings.ALLOW_CLIENT_MODIF_ON_LAST_VERSION_ONLY : read_only = (text.last_text_version_id != text_version.id) else : text_version = text.get_latest_version() comments = get_viewable_comments(request, text_version.comment_set.filter(reply_to__isnull=True),text) filter_datas = get_filter_datas(request, text_version, text) get_params = simplejson.dumps(request.GET) wrapped_text_version, _ , _ = spannify(text_version.get_content()) template_dict = {'text' : text, 'text_version' : text_version, 'title' : text_version.title, # TODO use it ... 'get_params' : get_params, 'json_comments':jsonize(comments, request), 'json_filter_datas':jsonize(filter_datas, request), 'content' : wrapped_text_version, 'client_date_fmt' : settings.CLIENT_DATE_FMT, 'read_only' : read_only, } return render_to_response('site/text_view_comments.html', template_dict, context_instance=RequestContext(request)) def client_exchange(request): ret = None if request.method == 'POST' : function_name = request.POST['fun']# function called from client user = request.user if function_name == 'experiment' : ret = experiment() elif function_name == 'warn' : # TODO: (RBE to RBA) send mail withinfos ret = "warn test" #print request.POST else : key = request.POST['key'] version_key = request.POST['version_key'] text = Text.objects.get(key=key) ; #TODO: stupid why restrict to latest ? text_version = text.get_latest_version() if (text != None) : if function_name == 'ownNotify' : ret = own_notify(request=request, key=key) if function_name in ('editComment', 'addComment', 'removeComment',) : if function_name == 'editComment' : ret = edit_comment(request=request, key=key, comment_key=request.POST['comment_key']) elif function_name == 'addComment' : ret = add_comment(request=request, key=key, version_key=version_key) elif function_name == 'removeComment' : ret = remove_comment(request=request, key=key, comment_key=request.POST['comment_key']) ret['filterData'] = get_filter_datas(request, text_version, text) #ret['tagCloud'] = get_tagcloud(key) if ret : if type(ret) != HttpResponseRedirect and type(ret) != HttpResponse: ret = HttpResponse(simplejson.dumps(ret, cls=RequestComplexEncoder, request=request)) else : ret = HttpResponse() ret.status_code = 403 return ret def from_html_links_to_abs_links(content): """ Replaces (html) links to attachs with real file path on server """ attach_re = r'/text/(?P<key>\w*)/attach/(?P<attach_key>\w*)/' attach_str = r'/text/%s/attach/%s/' for match in re.findall(attach_re, content): link = attach_str %match attach = Attachment.objects.get(key=match[1], text_version__text__key=match[0]) content = content.replace(link, attach.data.path) return content #NOTE : some arguments like : withcolor = "yes" + format = "markdown" are incompatible #http://localhost:8000/text/text_key_1/export/pdf/1/all/1 def text_export(request, key, format, download, whichcomments, withcolor, adminkey=None): text, admin = get_text_and_admin(key, adminkey) text_version = text.get_latest_version() original_content = text_version.content original_format = text_version.format # BD : html or markdown for now ... download_response = download == "1" with_color = withcolor == "1" comments = [] # whichcomments=="none" if whichcomments == "filtered" or whichcomments == "all": #comments = text_version.comment_set.filter(reply_to__isnull=True)# whichcomments=="all" #comments = get_viewable_comments(request, text_version.comment_set.filter(reply_to__isnull=True), text, order_by=('start_wrapper','start_offset','end_wrapper','end_offset'))# whichcomments=="all" _comments = text_version.comment_set.all() if whichcomments == "filtered" : filteredIds = [] if request.method == 'POST' : ll = request.POST.get('filteredIds',[]).split(",") filteredIds = [ int(l) for l in ll if l] _comments = text_version.comment_set.filter(id__in=filteredIds) # security ! TODO CROSS PERMISSIONS WITH POST CONTENT comments = get_viewable_comments(request, _comments, text, order_by=('start_wrapper','start_offset','end_wrapper','end_offset'))# whichcomments=="all" # decide to use pandoc or not if with_color : use_pandoc = False # pandoc wouldn't preserve comments scope background colors else : if format in ('markdown', 'latex') : use_pandoc = True elif format in ('pdf', 'odt') : use_pandoc = (original_format == "markdown") elif format in ('doc', 'html') : use_pandoc = False # correct attach path => real path if format in ('pdf','odt') : original_content = from_html_links_to_abs_links(original_content) if len(comments) == 0 : #want to bypass html conversion in this case return content_export2(request, original_content, text_version.title, original_format, format, use_pandoc, download_response) else : # case comments to be added #comments = comments.order_by('start_wrapper','start_offset','end_wrapper','end_offset') html = pandoc_convert(original_content, original_format, 'html') wrapped_text_version, _ , _ = spannify(html) with_markers = True marked_content = insert_comment_markers(wrapped_text_version, comments, with_markers, with_color) viewable_comments = comments_thread(request, text_version, text) # viewable_commentsnoreply = get_viewable_comments(request, commentsnoreply, text, order_by = ('start_wrapper','start_offset','end_wrapper','end_offset')) # viewable_comments = [] # for cc in viewable_commentsnoreply : # viewable_comments += list_viewable_comments(request, [cc], text) # numerotation{ id --> numbered as a child} extended_comments = {} nb_children = {} for cc in viewable_comments : id = 0 #<-- all top comments are children of comment with id 0 if cc.is_reply() : id = cc.reply_to_id nb_children[id] = nb_children.get(id, 0) + 1 cc.num = "%d"%nb_children[id] extended_comments[cc.id] = cc if cc.is_reply() : cc.num = "%s.%s"%(extended_comments[cc.reply_to_id].num, cc.num) # viewable_comments += list_viewable_comments(request, viewable_commentsnoreply, text) html_comments=render_to_string('site/macros/text_comments.html',{'comments':viewable_comments }, context_instance=RequestContext(request)) content = "%s%s"%(marked_content, html_comments) content_format = "html" # impossible to satisfy because of color then no colors instead: if with_color and format in ('markdown', 'tex') : #TODO : add S5 with_color = False return content_export2(request, content, text_version.title, content_format, format, use_pandoc, download_response) def text_print(request, key, adminkey=None): text, admin = get_text_and_admin(key, adminkey) text_version = text.get_latest_version() # chosen default url behaviour is export all comments + bckcolor + pdf comments = Comment.objects.filter(text_version=text_version, reply_to__isnull=True) with_markers = True with_colors = True download_requested = True action = 'export' # client origine dialog requested_format = 'pdf' # requested output format if request.method == 'POST': # colors or not ? with_colors = (u'yes' == request.POST.get('p_color', u'no')) # restrict comments to ones that should be exported / printed p_comments = request.POST.get('p_comments') if p_comments == "filtered" or p_comments == "none" : filteredIds = [] # "none" case if p_comments == "filtered" : ll = request.POST.get('filteredIds').split(",") filteredIds = [ int(l) for l in ll if l] comments = comments.filter(id__in=filteredIds) # print or export ? action = request.POST.get('print_export_action') requested_format = request.POST.get('p_method') comments = comments.order_by('start_wrapper','start_offset','end_wrapper','end_offset') download_requested = (action == 'export') or (action == 'print' and requested_format != 'html') ori_format = text_version.format # BD : html or markdown for now ... src_format = ori_format # as expected by convert functions ... src = text_version.content if len(comments) > 0 and (with_markers or with_colors) : html = text_version.get_content() wrapped_text_version, _ , _ = spannify(html) marked_text_version = insert_comment_markers(wrapped_text_version, comments, with_markers, with_colors) src_format = 'html' src = marked_text_version html_comments=render_to_string('site/macros/text_comments.html',{'comments':comments}, context_instance=RequestContext(request)) src += html_comments if download_requested : use_pandoc = (requested_format == 'html' or requested_format == 'markdown') return content_export(request, src, text_version.title, src_format, requested_format, use_pandoc) else : # action == 'print' and requested_format == 'html' (no colors) template_dict = {'text' : text, 'text_version' : text_version, 'title' : text_version.title, # TODO use it ... 'comments': comments, 'content' : marked_text_version, 'client_date_fmt' : settings.CLIENT_DATE_FMT } if admin: template_dict['adminkey'] = text.adminkey template_dict['admin'] = True return render_to_response('site/text_print.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_view_text') def text_view_frame(request, key, version_key=None, adminkey=None): text = get_text_by_keys_or_404(key) if version_key : text_version = get_textversion_by_keys_or_404(version_key, adminkey, key) else : text_version = text.get_latest_version() template_dict = {'text' : text, 'text_version' : text_version} return render_to_response('site/text_view_frame.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_view_text') def text_history_version(request, key, version_key): text = get_text_by_keys_or_404(key) text_version = get_textversion_by_keys_or_404(version_key, key=key) template_dict = {'text' : text, 'text_version' : text_version, 'embed_code' : embed_html(key, 'id="text_view_frame" name="text_view_frame"', version_key), } return render_to_response('site/text_history_version.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_view_text') def text_history_compare(request, key, v1_version_key, v2_version_key, mode=''): text = get_text_by_keys_or_404(key) v1 = get_textversion_by_keys_or_404(v1_version_key, key=key) v2 = get_textversion_by_keys_or_404(v2_version_key, key=key) content = get_uniffied_inner_diff_table(v1.title, v2.title, _("by %(author)s") %{'author' : v1.get_name()}, _("by %(author)s") %{'author' : v2.get_name()}, v1.content, v2.content) if mode=='1': # alternate diff from cm.utils.diff import text_diff content = text_diff(v1.get_content(), v2.get_content()) template_dict = { 'text' : text, 'v1': v1, 'v2': v2, 'content' : content.strip(), 'empty' : '<table class="diff"><tbody></tbody></table>'==content, } return render_to_response('site/text_history_compare.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_view_text') def text_history(request, key): text = get_text_by_keys_or_404(key) if request.method == 'POST': v1_key = request.POST.get('newkey',None) v2_key = request.POST.get('oldkey',None) if v1_key and v2_key: return redirect(request, 'text-history-compare', args=[text.key, v2_key, v1_key ]) text_versions = text.get_versions() paginate_by = get_int(request.GET,'paginate',TEXT_PAGINATION) last_last_version = text_versions[1] if len(text_versions)>1 else None context = {'text':text, 'last_version':text.last_text_version, 'last_last_version':last_last_version} return object_list(request, text_versions, template_name = 'site/text_history.html', paginate_by = paginate_by, extra_context=context, ) # taken from trac def _get_change_extent(str1, str2): """ Determines the extent of differences between two strings. Returns a tuple containing the offset at which the changes start, and the negative offset at which the changes end. If the two strings have neither a common prefix nor a common suffix, (0, 0) is returned. """ start = 0 limit = min(len(str1), len(str2)) while start < limit and str1[start] == str2[start]: start += 1 end = -1 limit = limit - start while - end <= limit and str1[end] == str2[end]: end -= 1 return (start, end + 1) def diff_decorate(minus, plus): return minus, plus def get_uniffied_inner_diff_table(title1, title2, author1, author2, text1, text2): """ Return the inner of the html table for text1 vs text2 diff """ gen = unified_diff(text1.split('\n'), text2.split('\n'), n=3) index = 0 res = ['<table class="diff"><tbody>'] res.append('<tr><td></td><td class="diff-title">%s</td><td></td><td></td><td class="diff-title">%s</td></tr>' %(title1, title2)) res.append('<tr><td></td><td class="diff-author">%s</td><td></td><td></td><td class="diff-author">%s</td></tr>' %(author1, author2)) res.append('<tr><td colspan="5"></td></tr>') #res.append('<tr><td width="50%" colspan="2"></td><td width="50%" colspan="2"></td></tr>') for g in gen: if index > 1: col_in = None if g.startswith('@@'): line_number = g.split(' ')[1][1:].split(',')[0] if index != 2: res.append('<tr><td></td>&nbsp;<td></td><td></td><td>&nbsp;</td></tr>') res.append('<tr><td class="diff-lineno" colspan="2">Line %s</td><td class="diff-separator"></td><td class="diff-lineno" colspan="2">Line %s</td></tr>' % (line_number, line_number)) if g.startswith(' '): res.append('<tr><td class="diff-marker"></td><td class="diff-context">%s</td><td class="diff-separator"></td><td class="diff-marker"></td><td class="diff-context">%s</td></tr>' % (g, g)) if g.startswith('-') or g.startswith('+'): plus = [] minus = [] while g.startswith('-') or g.startswith('+'): if g.startswith('-'): minus.append(g[1:]) else: plus.append(g[1:]) try: g = gen.next() except StopIteration: break minus, plus = diff_decorate(minus, plus) res.append('<tr><td class="diff-marker">-</td><td class="diff-deletedline">%s</td><td class="diff-separator"></td><td class="diff-marker">+</td><td class="diff-addedline">%s</td></tr>' % ('<br />'.join(minus), '<br />'.join(plus))) index += 1 res.append('</tbody></table>') return ''.join(res) #def text_history_version(request, key): # text = get_text_by_keys_or_404(key=key) # return _text_history_version(request, text) # #def text_history_version_admin(request, key, adminkey): # text = get_text_by_keys_or_404(key=key, adminkey=adminkey) # return _text_history_version(request, text, True) # if admin: # template_dict['adminkey'] = text.adminkey # template_dict['admin'] = True # return render_to_response('site/text_history.html', template_dict, context_instance=RequestContext(request)) # class TextVersionForm(ModelForm): class Meta: model = TextVersion fields = ('title', 'content', 'format') class EditTextForm(ModelForm): title = forms.CharField(label=ugettext_lazy("Title"), widget=forms.TextInput) #format = forms.CharField(label=_("Format")) #content = forms.TextField(label=_("Content")) note = forms.CharField(label=ugettext_lazy("Note (optional)"), widget=forms.TextInput, required=False, help_text=ugettext_lazy("Add a note to explain the modifications made to the text") ) #tags = forms.CharField(label=_("Tags (optional)"), # widget=forms.TextInput, # required=False, # #help_text=_("Add a note to explain the modifications made to the text") # ) new_version = forms.BooleanField(label=ugettext_lazy("New version (optional)"), required=False, initial=True, help_text=ugettext_lazy("Create a new version of this text (recommended)") ) keep_comments = forms.BooleanField(label=ugettext_lazy("Keep comments (optional)"), required=False, initial=True, help_text=ugettext_lazy("Keep comments (if not affected by the edit)") ) class Meta: model = TextVersion fields = ('title', 'format', 'content', 'new_version', 'tags', 'note') def save_into_text(self, text, request): new_content = request.POST.get('content') new_title = request.POST.get('title') new_format = request.POST.get('format', text.last_text_version.format) new_note = request.POST.get('note',None) new_tags = request.POST.get('tags',None) cancel_modified_scopes = (request.POST.get('cancel_modified_scopes',u'1') == u'1') version = text.get_latest_version() version.edit(new_title, new_format, new_content, new_tags, new_note, True, cancel_modified_scopes) return version def save_new_version(self, text, request): new_content = request.POST.get('content') new_title = request.POST.get('title') new_format = request.POST.get('format', text.last_text_version.format) new_note = request.POST.get('note',None) new_tags = request.POST.get('tags',None) cancel_modified_scopes = (request.POST.get('cancel_modified_scopes',u'1') == u'1') new_text_version = text.edit(new_title, new_format, new_content, new_tags, new_note, keep_comments=True, cancel_modified_scopes=cancel_modified_scopes, new_version=True) new_text_version.edit(new_title, new_format, new_content, new_tags, new_note, True, cancel_modified_scopes) new_text_version.user = request.user if request.user.is_authenticated() else None new_text_version.note = request.POST.get('note','') new_text_version.email = request.POST.get('email','') new_text_version.name = request.POST.get('name','') new_text_version.save() return new_text_version def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False, instance=None): ModelForm.__init__(self, data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # override manually to disabled format_field = self.fields['format'] format_field.widget.attrs = {'disabled':'disabled'} format_field.required = False self.fields['format'] = format_field @has_perm_on_text('can_edit_text') def text_pre_edit(request, key, adminkey=None): text = get_text_by_keys_or_404(key) text_version = text.get_latest_version() comments = text_version.get_comments() ; new_format = request.POST['new_format'] new_content = on_content_receive(request.POST['new_content'], new_format) # TODO: RBE : si commentaire mal forme : (position non existante : boom par key error) _tomodify_comments, toremove_comments = compute_new_comment_positions(text_version.content, text_version.format, new_content, new_format, comments) return HttpResponse(simplejson.dumps({'nb_removed' : len(toremove_comments) })) class EditTextFormAnon(EditTextForm): name = forms.CharField(label=ugettext_lazy("Name (optional)"), widget=forms.TextInput, required=False) email = forms.EmailField(label=ugettext_lazy("Email (optional)"), required=False) content = forms.CharField(label=ugettext_lazy("Content"), required=True, widget=forms.Textarea(attrs={'rows':'30', 'cols': '70'})) class Meta: model = TextVersion fields = ('title', 'format', 'content', 'tags', 'note', 'name', 'email') @has_perm_on_text('can_edit_text') def text_edit(request, key, adminkey=None): text = get_text_by_keys_or_404(key) text_version = text.get_latest_version() if request.method == 'POST': if request.user.is_authenticated(): form = EditTextForm(request.POST) else: form = EditTextFormAnon(request.POST) if form.is_valid(): if request.POST.get('new_version'): new_version = form.save_new_version(text, request) register_activity(request, "text_edited_new_version", text=text, text_version=new_version) else: form.save_into_text(text, request) register_activity(request, "text_edited", text=text) return redirect(request, 'text-view', args=[text.key]) else: default_data = { 'content': text_version.content, 'title': text_version.title, 'format': text_version.format, 'tags': text_version.tags, 'new_version': NEW_TEXT_VERSION_ON_EDIT, 'note' : text_version.note, 'keep_comments' : True, } if request.user.is_authenticated(): form = EditTextForm(default_data) else: form = EditTextFormAnon(default_data) template_dict = {'text' : text, 'form' : form} return render_to_response('site/text_edit.html', template_dict , context_instance=RequestContext(request)) @has_perm_on_text('can_edit_text') def text_revert(request, key, text_version_key): if request.method != 'POST': raise UnauthorizedException('Unauthorized') text = get_text_by_keys_or_404(key) text_version = text.revert_to_version(text_version_key) display_message(request, _(u'A new version (copied from version %(version_title)s) has been created') % {'version_title':text_version.title}) return HttpResponse('') # no redirect because this is called by js @has_perm_on_text('can_view_text') def text_attach(request, key, attach_key): attach = Attachment.objects.get(key=attach_key, text_version__text__key=key) content = file(attach.data.path).read() mimetype, _encoding = mimetypes.guess_type(attach.data.path) response = HttpResponse(content, mimetype) return response def fix_anon_in_formset(formset): # fix role choice in formset for anon (not all role are allowed) role_field = [f.fields['role'] for f in formset.forms if f.instance.user == None][0] role_field.choices = [(u'', u'---------')] + [(r.id, str(r)) for r in Role.objects.filter(anon = True)] # limit anon choices class BaseUserRoleFormSet(BaseModelFormSet): def clean(self): """Checks that anon users are given roles with anon=True.""" for i in range(0, self.total_form_count()): form = self.forms[i] print form.cleaned_data user_role = form.cleaned_data['id'] if user_role.user == None: role = form.cleaned_data['role'] if not role.anon: # nasty stuff: cannot happen so not dealt with in tempate logging.warn('Cannot give such role to anon user.') raise forms.ValidationError, "Cannot give such role to anon user." #@has_perm_on_text('can_manage_text') #def xtext_share(request, key): # text = get_text_by_keys_or_404(key) # order_by = get_among(request.GET,'order',('user__username','-user__username','role__name','-role__name'),'user__username') # # UserRole.objects.create_userroles_text(text) # UserRoleFormSet = modelformset_factory(UserRole, fields=('role', ), extra=0, formset = BaseUserRoleFormSet) # # # put anon users on top no matter what the order says (TODO: ?) # userrole_queryset = UserRole.objects.filter(text=text).extra(select={'anon':'"cm_userrole"."user_id">-1'}).order_by('-anon',order_by) # if request.method == 'POST': # formset = UserRoleFormSet(request.POST, queryset = userrole_queryset) # # if formset.is_valid(): # formset.save() # display_message(request, "Sharing updated.") # return HttpResponseRedirect(reverse('text-share',args=[text.key])) # # else: # formset = UserRoleFormSet(queryset = userrole_queryset) # fix_anon_in_formset(formset) # # global_anon_userrole = UserRole.objects.get(text=None, user=None) # return render_to_response('site/text_share.html', {'text' : text, # 'formset' : formset, # 'global_anon_userrole' : global_anon_userrole, # } , context_instance=RequestContext(request)) # TODO: permission protection ? format value check ? def text_wysiwyg_preview(request, format): html_content = "" if request.POST : # if satisfied in the no html case, in html case : no POST (cf. markitup) previewTemplatePath and previewParserPath html_content = pandoc_convert(request.POST['data'], format, "html", full=False) return render_to_response('site/wysiwyg_preview.html', {'content':html_content} , context_instance=RequestContext(request)) #return HttpResponse(pandoc_convert(content, format, "html", full=False)) USER_PAGINATION = 10 @has_perm_on_text('can_manage_text') def text_share(request, key): display_suspended_users = get_int(request.GET, 'display', 0) tag_selected = request.GET.get('tag_selected', 0) paginate_by = get_int(request.GET, 'paginate', USER_PAGINATION) text = get_text_by_keys_or_404(key) order_by = get_among(request.GET,'order',('user__username', 'user__email', '-user__username', '-user__email', 'role__name', '-role__name', ), 'user__username') UserRole.objects.create_userroles_text(text) if request.method == 'POST': if 'save' in request.POST: user_profile_keys_roles = get_keys_from_dict(request.POST, 'user-role-') count = 0 for user_profile_key in user_profile_keys_roles: role_id = user_profile_keys_roles[user_profile_key] if not user_profile_key: user_role = UserRole.objects.get(user = None, text = text) else: user_role = UserRole.objects.get(user__userprofile__key = user_profile_key, text = text) if (role_id != u'' or user_role.role_id!=None) and role_id!=unicode(user_role.role_id): if role_id: user_role.role_id = int(role_id) else: user_role.role_id = None user_role.save() count += 1 display_message(request, _(u'%(count)i user(s) role modified') %{'count':count}) return HttpResponseRedirect(reverse('text-share', args=[text.key])) anon_role = UserRole.objects.get(user = None, text = text).role global_anon_role = UserRole.objects.get(user = None, text = None).role context = { 'anon_role' : anon_role, 'global_anon_role' : global_anon_role, 'all_roles' : Role.objects.all(), 'anon_roles' : Role.objects.filter(anon = True), 'text' : text, 'display_suspended_users' : display_suspended_users, 'tag_list' : Tag.objects.usage_for_model(UserProfile), 'tag_selected': tag_selected, } query = UserRole.objects.filter(text=text).filter(~Q(user=None)).order_by(order_by) if not display_suspended_users: query = query.exclude(Q(user__userprofile__is_suspended=True) & Q(user__is_active=True)) else: # trick to include userprofile table anyway (to filter by tags) query = query.filter(Q(user__userprofile__is_suspended=True) | Q(user__userprofile__is_suspended=False)) if tag_selected: tag_ids = Tag.objects.filter(name=tag_selected) if tag_ids: content_type_id = ContentType.objects.get_for_model(UserProfile).pk query = query.extra(where=['tagging_taggeditem.object_id = cm_userprofile.id', 'tagging_taggeditem.content_type_id = %i' %content_type_id, 'tagging_taggeditem.tag_id = %i' %tag_ids[0].id], tables=['tagging_taggeditem'], ) return object_list(request, query, template_name = 'site/text_share.html', paginate_by = paginate_by, extra_context = context, ) class SettingsTextForm(ModelForm): # example name = forms.CharField(label=_("Name (optional)"), widget=forms.TextInput, required=False) class Meta: model = TextVersion fields = ('mod_posteriori',) @has_perm_on_text('can_manage_text') def text_settings(request, key): text = get_text_by_keys_or_404(key) text_version = text.get_latest_version() if request.method == 'POST': form = SettingsTextForm(request.POST, instance = text_version) if form.is_valid(): form.save() display_message(request, _(u'Text settings updated')) return redirect(request, 'text-view', args=[text.key]) else: form = SettingsTextForm(instance = text_version) template_dict = {'text' : text, 'form' : form} return render_to_response('site/text_settings.html', template_dict , context_instance=RequestContext(request)) note should not beeing passed to new version (fixes #12) from cm.utils.embed import embed_html from cm.activity import register_activity from cm.client import jsonize, get_filter_datas, edit_comment, remove_comment, \ add_comment, RequestComplexEncoder, comments_thread, own_notify from cm.cm_settings import NEW_TEXT_VERSION_ON_EDIT from cm.exception import UnauthorizedException from cm.message import * from cm.models import * from django.forms.util import ErrorList from cm.models_base import generate_key from cm.security import get_texts_with_perm, has_perm, get_viewable_comments, \ has_perm_on_text from cm.utils import get_among, get_among, get_int from cm.utils.html import on_content_receive from cm.utils.comment_positioning import compute_new_comment_positions, \ insert_comment_markers from cm.utils.spannifier import spannify from cm.views import get_keys_from_dict, get_textversion_by_keys_or_404, get_text_by_keys_or_404, redirect from cm.views.export import content_export2, content_export from cm.views.user import AnonUserRoleForm, cm_login from difflib import unified_diff from django import forms from django.conf import settings from django.contrib.auth import login as django_login from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db.models import Q from django.forms import ModelForm from django.forms.models import BaseModelFormSet, modelformset_factory from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.template.loader import render_to_string from django.utils.translation import ugettext as _, ugettext_lazy from django.views.generic.list_detail import object_list from tagging.models import Tag import difflib import logging import mimetypes import simplejson import sys import re from django.db.models.sql.datastructures import EmptyResultSet def get_text_and_admin(key, adminkey, assert_admin = False): """ assert_admin => redirect to unauthorized if not admin """ admin = False if adminkey: text = Text.objects.get(key = key, adminkey = adminkey) if text: admin = True else: text = Text.objects.get(key=key) if assert_admin and not admin: raise UnauthorizedException('Is not admin') return text, admin ACTIVITY_PAGINATION = 10 RECENT_TEXT_NB = 5 RECENT_COMMENT_NB = RECENT_TEXT_NB MODERATE_NB = 5 def dashboard(request): request.session.set_test_cookie() if request.user.is_authenticated(): act_view = { 'view_texts' : get_int(request.GET,'view_texts',1), 'view_comments' : get_int(request.GET,'view_comments',1), 'view_users' : get_int(request.GET,'view_users',1), } paginate_by = get_int(request.GET,'paginate',ACTIVITY_PAGINATION) # texts with can_view_unapproved_comment perms moderator_texts = get_texts_with_perm(request, 'can_view_unapproved_comment') viewer_texts = get_texts_with_perm(request, 'can_view_approved_comment') all_texts_ids = [t.id for t in moderator_texts] + [t.id for t in viewer_texts] span = get_among(request.GET,'span',('day','month','week',),'week') template_dict = { 'span' : span, 'last_texts' : get_texts_with_perm(request, 'can_view_text').order_by('-modified')[:RECENT_TEXT_NB], 'last_comments' : Comment.objects.filter(text_version__text__in=all_texts_ids).order_by('-created')[:RECENT_COMMENT_NB],# TODO: useful? #'last_users' : User.objects.all().order_by('-date_joined')[:5], } template_dict.update(act_view) all_activities = { 'view_comments' : ['comment_created','comment_removed'], 'view_users' : ['user_created', 'user_activated', 'user_suspended','user_enabled',], 'view_texts' : ['text_created','text_removed', 'text_edited', 'text_edited_new_version'], } selected_activities = [] [selected_activities.extend(all_activities[k]) for k in act_view.keys() if act_view[k]] activities = Activity.objects.filter(type__in = selected_activities) if not has_perm(request,'can_manage_workspace'): texts = get_texts_with_perm(request, 'can_view_text') activities = activities.filter(Q(text__in=texts)) comments = [] [comments.extend(get_viewable_comments(request, t.last_text_version.comment_set.all(), t)) for t in texts] activities = activities.filter(Q(comment__in=comments) | Q(comment=None) ) template_dict['to_mod_profiles'] = [] else: template_dict['to_mod_profiles'] = UserProfile.objects.filter(user__is_active=False).filter(is_suspended=True).order_by('-user__date_joined')[:MODERATE_NB] template_dict['to_mod_comments'] = Comment.objects.filter(state='pending').filter(text_version__text__in=moderator_texts).order_by('-modified')[:MODERATE_NB-len(template_dict['to_mod_profiles'])] activities = activities.order_by('-created') return object_list(request, activities, template_name = 'site/dashboard.html', paginate_by = paginate_by, extra_context = template_dict, ) else: if request.method == 'POST': form = AuthenticationForm(request, request.POST) if form.is_valid(): user = form.get_user() user.backend = 'django.contrib.auth.backends.ModelBackend' cm_login(request, user) display_message(request, _(u"You're logged in!")) return HttpResponseRedirect(reverse('index')) else: form = AuthenticationForm() public_texts = get_texts_with_perm(request, 'can_view_text').order_by('-modified') template_dict = { 'form' : form, 'texts' : public_texts, } return render_to_response('site/non_authenticated_index.html', template_dict, context_instance=RequestContext(request)) TEXT_PAGINATION = 10 # security check inside view # TODO: set global access perm def text_list(request): paginate_by = get_int(request.GET,'paginate',TEXT_PAGINATION) tag_selected = request.GET.get('tag_selected', 0) order_by = get_among(request.GET,'order',('title','author','modified','-title','-author','-modified'),'-modified') if request.method == 'POST': action = request.POST.get('action',None) text_keys = get_keys_from_dict(request.POST, 'check-').keys() if action == 'delete': for text_key in text_keys: text = Text.objects.get(key=text_key) if has_perm(request, 'can_delete_text', text=text): text.delete() else: raise UnauthorizedException('No perm can_delete_text on comment') display_message(request, _(u'%(nb_texts)i text(s) deleted') %{'nb_texts':len(text_keys)}) return HttpResponseRedirect(reverse('text')) texts = get_texts_with_perm(request, 'can_view_text').order_by(order_by) try: tag_list = Tag.objects.usage_for_queryset(TextVersion.objects.filter(id__in = [t.last_text_version_id for t in get_texts_with_perm(request, 'can_view_text')])) except EmptyResultSet: tag_list = [] context = { 'tag_list' : tag_list, 'tag_selected': tag_selected, } if tag_selected: tag_ids = Tag.objects.filter(name=tag_selected) if tag_ids: content_type_id = ContentType.objects.get_for_model(TextVersion).pk # table cm_userprofile is not present if display_suspended_users: fix this texts = texts.extra(where=['tagging_taggeditem.object_id = cm_text.last_text_version_id', 'tagging_taggeditem.content_type_id = %i' %content_type_id, 'tagging_taggeditem.tag_id = %i' %tag_ids[0].id], tables=['tagging_taggeditem'], ) return object_list(request, texts, template_name = 'site/text_list.html', paginate_by = paginate_by, extra_context=context, ) @has_perm_on_text('can_view_text') def text_view(request, key, adminkey=None): text = get_text_by_keys_or_404(key) register_activity(request, "text_view", text=text) text_version = text.get_latest_version() embed_code = embed_html(key, 'id="text_view_frame" name="text_view_frame"', None, request.META.get('QUERY_STRING')) template_dict = { 'embed_code':embed_code, 'text' : text, 'text_version' : text_version, 'title' : text_version.title, 'content' : text_version.get_content()} return render_to_response('site/text_view.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_delete_text') def text_delete(request, key): text = Text.objects.get(key=key) if request.method != 'POST': raise UnauthorizedException('Unauthorized') display_message(request, _(u'Text %(text_title)s deleted') %{'text_title':text.title}) register_activity(request, "text_removed", text=text) text.delete() return HttpResponse('') # no redirect because this is called by js @has_perm_on_text('can_delete_text') def text_version_delete(request, key, text_version_key): text_version = TextVersion.objects.get(key=text_version_key) text=text_version.text if request.method != 'POST': raise UnauthorizedException('Unauthorized') display_message(request, _(u'Text version %(text_version_title)s deleted') %{'text_version_title':text_version.title}) register_activity(request, "text_version_removed", text=text) text_version.delete() return HttpResponse('') # no redirect because this is called by js @has_perm_on_text('can_view_text') # only protected by text_view / comment filtering done in view def text_view_comments(request, key, version_key=None, adminkey=None): text = get_text_by_keys_or_404(key) read_only = False if version_key : text_version = get_textversion_by_keys_or_404(version_key, adminkey, key) if settings.ALLOW_CLIENT_MODIF_ON_LAST_VERSION_ONLY : read_only = (text.last_text_version_id != text_version.id) else : text_version = text.get_latest_version() comments = get_viewable_comments(request, text_version.comment_set.filter(reply_to__isnull=True),text) filter_datas = get_filter_datas(request, text_version, text) get_params = simplejson.dumps(request.GET) wrapped_text_version, _ , _ = spannify(text_version.get_content()) template_dict = {'text' : text, 'text_version' : text_version, 'title' : text_version.title, # TODO use it ... 'get_params' : get_params, 'json_comments':jsonize(comments, request), 'json_filter_datas':jsonize(filter_datas, request), 'content' : wrapped_text_version, 'client_date_fmt' : settings.CLIENT_DATE_FMT, 'read_only' : read_only, } return render_to_response('site/text_view_comments.html', template_dict, context_instance=RequestContext(request)) def client_exchange(request): ret = None if request.method == 'POST' : function_name = request.POST['fun']# function called from client user = request.user if function_name == 'experiment' : ret = experiment() elif function_name == 'warn' : # TODO: (RBE to RBA) send mail withinfos ret = "warn test" #print request.POST else : key = request.POST['key'] version_key = request.POST['version_key'] text = Text.objects.get(key=key) ; #TODO: stupid why restrict to latest ? text_version = text.get_latest_version() if (text != None) : if function_name == 'ownNotify' : ret = own_notify(request=request, key=key) if function_name in ('editComment', 'addComment', 'removeComment',) : if function_name == 'editComment' : ret = edit_comment(request=request, key=key, comment_key=request.POST['comment_key']) elif function_name == 'addComment' : ret = add_comment(request=request, key=key, version_key=version_key) elif function_name == 'removeComment' : ret = remove_comment(request=request, key=key, comment_key=request.POST['comment_key']) ret['filterData'] = get_filter_datas(request, text_version, text) #ret['tagCloud'] = get_tagcloud(key) if ret : if type(ret) != HttpResponseRedirect and type(ret) != HttpResponse: ret = HttpResponse(simplejson.dumps(ret, cls=RequestComplexEncoder, request=request)) else : ret = HttpResponse() ret.status_code = 403 return ret def from_html_links_to_abs_links(content): """ Replaces (html) links to attachs with real file path on server """ attach_re = r'/text/(?P<key>\w*)/attach/(?P<attach_key>\w*)/' attach_str = r'/text/%s/attach/%s/' for match in re.findall(attach_re, content): link = attach_str %match attach = Attachment.objects.get(key=match[1], text_version__text__key=match[0]) content = content.replace(link, attach.data.path) return content #NOTE : some arguments like : withcolor = "yes" + format = "markdown" are incompatible #http://localhost:8000/text/text_key_1/export/pdf/1/all/1 def text_export(request, key, format, download, whichcomments, withcolor, adminkey=None): text, admin = get_text_and_admin(key, adminkey) text_version = text.get_latest_version() original_content = text_version.content original_format = text_version.format # BD : html or markdown for now ... download_response = download == "1" with_color = withcolor == "1" comments = [] # whichcomments=="none" if whichcomments == "filtered" or whichcomments == "all": #comments = text_version.comment_set.filter(reply_to__isnull=True)# whichcomments=="all" #comments = get_viewable_comments(request, text_version.comment_set.filter(reply_to__isnull=True), text, order_by=('start_wrapper','start_offset','end_wrapper','end_offset'))# whichcomments=="all" _comments = text_version.comment_set.all() if whichcomments == "filtered" : filteredIds = [] if request.method == 'POST' : ll = request.POST.get('filteredIds',[]).split(",") filteredIds = [ int(l) for l in ll if l] _comments = text_version.comment_set.filter(id__in=filteredIds) # security ! TODO CROSS PERMISSIONS WITH POST CONTENT comments = get_viewable_comments(request, _comments, text, order_by=('start_wrapper','start_offset','end_wrapper','end_offset'))# whichcomments=="all" # decide to use pandoc or not if with_color : use_pandoc = False # pandoc wouldn't preserve comments scope background colors else : if format in ('markdown', 'latex') : use_pandoc = True elif format in ('pdf', 'odt') : use_pandoc = (original_format == "markdown") elif format in ('doc', 'html') : use_pandoc = False # correct attach path => real path if format in ('pdf','odt') : original_content = from_html_links_to_abs_links(original_content) if len(comments) == 0 : #want to bypass html conversion in this case return content_export2(request, original_content, text_version.title, original_format, format, use_pandoc, download_response) else : # case comments to be added #comments = comments.order_by('start_wrapper','start_offset','end_wrapper','end_offset') html = pandoc_convert(original_content, original_format, 'html') wrapped_text_version, _ , _ = spannify(html) with_markers = True marked_content = insert_comment_markers(wrapped_text_version, comments, with_markers, with_color) viewable_comments = comments_thread(request, text_version, text) # viewable_commentsnoreply = get_viewable_comments(request, commentsnoreply, text, order_by = ('start_wrapper','start_offset','end_wrapper','end_offset')) # viewable_comments = [] # for cc in viewable_commentsnoreply : # viewable_comments += list_viewable_comments(request, [cc], text) # numerotation{ id --> numbered as a child} extended_comments = {} nb_children = {} for cc in viewable_comments : id = 0 #<-- all top comments are children of comment with id 0 if cc.is_reply() : id = cc.reply_to_id nb_children[id] = nb_children.get(id, 0) + 1 cc.num = "%d"%nb_children[id] extended_comments[cc.id] = cc if cc.is_reply() : cc.num = "%s.%s"%(extended_comments[cc.reply_to_id].num, cc.num) # viewable_comments += list_viewable_comments(request, viewable_commentsnoreply, text) html_comments=render_to_string('site/macros/text_comments.html',{'comments':viewable_comments }, context_instance=RequestContext(request)) content = "%s%s"%(marked_content, html_comments) content_format = "html" # impossible to satisfy because of color then no colors instead: if with_color and format in ('markdown', 'tex') : #TODO : add S5 with_color = False return content_export2(request, content, text_version.title, content_format, format, use_pandoc, download_response) def text_print(request, key, adminkey=None): text, admin = get_text_and_admin(key, adminkey) text_version = text.get_latest_version() # chosen default url behaviour is export all comments + bckcolor + pdf comments = Comment.objects.filter(text_version=text_version, reply_to__isnull=True) with_markers = True with_colors = True download_requested = True action = 'export' # client origine dialog requested_format = 'pdf' # requested output format if request.method == 'POST': # colors or not ? with_colors = (u'yes' == request.POST.get('p_color', u'no')) # restrict comments to ones that should be exported / printed p_comments = request.POST.get('p_comments') if p_comments == "filtered" or p_comments == "none" : filteredIds = [] # "none" case if p_comments == "filtered" : ll = request.POST.get('filteredIds').split(",") filteredIds = [ int(l) for l in ll if l] comments = comments.filter(id__in=filteredIds) # print or export ? action = request.POST.get('print_export_action') requested_format = request.POST.get('p_method') comments = comments.order_by('start_wrapper','start_offset','end_wrapper','end_offset') download_requested = (action == 'export') or (action == 'print' and requested_format != 'html') ori_format = text_version.format # BD : html or markdown for now ... src_format = ori_format # as expected by convert functions ... src = text_version.content if len(comments) > 0 and (with_markers or with_colors) : html = text_version.get_content() wrapped_text_version, _ , _ = spannify(html) marked_text_version = insert_comment_markers(wrapped_text_version, comments, with_markers, with_colors) src_format = 'html' src = marked_text_version html_comments=render_to_string('site/macros/text_comments.html',{'comments':comments}, context_instance=RequestContext(request)) src += html_comments if download_requested : use_pandoc = (requested_format == 'html' or requested_format == 'markdown') return content_export(request, src, text_version.title, src_format, requested_format, use_pandoc) else : # action == 'print' and requested_format == 'html' (no colors) template_dict = {'text' : text, 'text_version' : text_version, 'title' : text_version.title, # TODO use it ... 'comments': comments, 'content' : marked_text_version, 'client_date_fmt' : settings.CLIENT_DATE_FMT } if admin: template_dict['adminkey'] = text.adminkey template_dict['admin'] = True return render_to_response('site/text_print.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_view_text') def text_view_frame(request, key, version_key=None, adminkey=None): text = get_text_by_keys_or_404(key) if version_key : text_version = get_textversion_by_keys_or_404(version_key, adminkey, key) else : text_version = text.get_latest_version() template_dict = {'text' : text, 'text_version' : text_version} return render_to_response('site/text_view_frame.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_view_text') def text_history_version(request, key, version_key): text = get_text_by_keys_or_404(key) text_version = get_textversion_by_keys_or_404(version_key, key=key) template_dict = {'text' : text, 'text_version' : text_version, 'embed_code' : embed_html(key, 'id="text_view_frame" name="text_view_frame"', version_key), } return render_to_response('site/text_history_version.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_view_text') def text_history_compare(request, key, v1_version_key, v2_version_key, mode=''): text = get_text_by_keys_or_404(key) v1 = get_textversion_by_keys_or_404(v1_version_key, key=key) v2 = get_textversion_by_keys_or_404(v2_version_key, key=key) content = get_uniffied_inner_diff_table(v1.title, v2.title, _("by %(author)s") %{'author' : v1.get_name()}, _("by %(author)s") %{'author' : v2.get_name()}, v1.content, v2.content) if mode=='1': # alternate diff from cm.utils.diff import text_diff content = text_diff(v1.get_content(), v2.get_content()) template_dict = { 'text' : text, 'v1': v1, 'v2': v2, 'content' : content.strip(), 'empty' : '<table class="diff"><tbody></tbody></table>'==content, } return render_to_response('site/text_history_compare.html', template_dict, context_instance=RequestContext(request)) @has_perm_on_text('can_view_text') def text_history(request, key): text = get_text_by_keys_or_404(key) if request.method == 'POST': v1_key = request.POST.get('newkey',None) v2_key = request.POST.get('oldkey',None) if v1_key and v2_key: return redirect(request, 'text-history-compare', args=[text.key, v2_key, v1_key ]) text_versions = text.get_versions() paginate_by = get_int(request.GET,'paginate',TEXT_PAGINATION) last_last_version = text_versions[1] if len(text_versions)>1 else None context = {'text':text, 'last_version':text.last_text_version, 'last_last_version':last_last_version} return object_list(request, text_versions, template_name = 'site/text_history.html', paginate_by = paginate_by, extra_context=context, ) # taken from trac def _get_change_extent(str1, str2): """ Determines the extent of differences between two strings. Returns a tuple containing the offset at which the changes start, and the negative offset at which the changes end. If the two strings have neither a common prefix nor a common suffix, (0, 0) is returned. """ start = 0 limit = min(len(str1), len(str2)) while start < limit and str1[start] == str2[start]: start += 1 end = -1 limit = limit - start while - end <= limit and str1[end] == str2[end]: end -= 1 return (start, end + 1) def diff_decorate(minus, plus): return minus, plus def get_uniffied_inner_diff_table(title1, title2, author1, author2, text1, text2): """ Return the inner of the html table for text1 vs text2 diff """ gen = unified_diff(text1.split('\n'), text2.split('\n'), n=3) index = 0 res = ['<table class="diff"><tbody>'] res.append('<tr><td></td><td class="diff-title">%s</td><td></td><td></td><td class="diff-title">%s</td></tr>' %(title1, title2)) res.append('<tr><td></td><td class="diff-author">%s</td><td></td><td></td><td class="diff-author">%s</td></tr>' %(author1, author2)) res.append('<tr><td colspan="5"></td></tr>') #res.append('<tr><td width="50%" colspan="2"></td><td width="50%" colspan="2"></td></tr>') for g in gen: if index > 1: col_in = None if g.startswith('@@'): line_number = g.split(' ')[1][1:].split(',')[0] if index != 2: res.append('<tr><td></td>&nbsp;<td></td><td></td><td>&nbsp;</td></tr>') res.append('<tr><td class="diff-lineno" colspan="2">Line %s</td><td class="diff-separator"></td><td class="diff-lineno" colspan="2">Line %s</td></tr>' % (line_number, line_number)) if g.startswith(' '): res.append('<tr><td class="diff-marker"></td><td class="diff-context">%s</td><td class="diff-separator"></td><td class="diff-marker"></td><td class="diff-context">%s</td></tr>' % (g, g)) if g.startswith('-') or g.startswith('+'): plus = [] minus = [] while g.startswith('-') or g.startswith('+'): if g.startswith('-'): minus.append(g[1:]) else: plus.append(g[1:]) try: g = gen.next() except StopIteration: break minus, plus = diff_decorate(minus, plus) res.append('<tr><td class="diff-marker">-</td><td class="diff-deletedline">%s</td><td class="diff-separator"></td><td class="diff-marker">+</td><td class="diff-addedline">%s</td></tr>' % ('<br />'.join(minus), '<br />'.join(plus))) index += 1 res.append('</tbody></table>') return ''.join(res) #def text_history_version(request, key): # text = get_text_by_keys_or_404(key=key) # return _text_history_version(request, text) # #def text_history_version_admin(request, key, adminkey): # text = get_text_by_keys_or_404(key=key, adminkey=adminkey) # return _text_history_version(request, text, True) # if admin: # template_dict['adminkey'] = text.adminkey # template_dict['admin'] = True # return render_to_response('site/text_history.html', template_dict, context_instance=RequestContext(request)) # class TextVersionForm(ModelForm): class Meta: model = TextVersion fields = ('title', 'content', 'format') class EditTextForm(ModelForm): title = forms.CharField(label=ugettext_lazy("Title"), widget=forms.TextInput) #format = forms.CharField(label=_("Format")) #content = forms.TextField(label=_("Content")) note = forms.CharField(label=ugettext_lazy("Note (optional)"), widget=forms.TextInput, required=False, help_text=ugettext_lazy("Add a note to explain the modifications made to the text") ) #tags = forms.CharField(label=_("Tags (optional)"), # widget=forms.TextInput, # required=False, # #help_text=_("Add a note to explain the modifications made to the text") # ) new_version = forms.BooleanField(label=ugettext_lazy("New version (optional)"), required=False, initial=True, help_text=ugettext_lazy("Create a new version of this text (recommended)") ) keep_comments = forms.BooleanField(label=ugettext_lazy("Keep comments (optional)"), required=False, initial=True, help_text=ugettext_lazy("Keep comments (if not affected by the edit)") ) class Meta: model = TextVersion fields = ('title', 'format', 'content', 'new_version', 'tags', 'note') def save_into_text(self, text, request): new_content = request.POST.get('content') new_title = request.POST.get('title') new_format = request.POST.get('format', text.last_text_version.format) new_note = request.POST.get('note',None) new_tags = request.POST.get('tags',None) cancel_modified_scopes = (request.POST.get('cancel_modified_scopes',u'1') == u'1') version = text.get_latest_version() version.edit(new_title, new_format, new_content, new_tags, new_note, True, cancel_modified_scopes) return version def save_new_version(self, text, request): new_content = request.POST.get('content') new_title = request.POST.get('title') new_format = request.POST.get('format', text.last_text_version.format) new_note = request.POST.get('note',None) new_tags = request.POST.get('tags',None) cancel_modified_scopes = (request.POST.get('cancel_modified_scopes',u'1') == u'1') new_text_version = text.edit(new_title, new_format, new_content, new_tags, new_note, keep_comments=True, cancel_modified_scopes=cancel_modified_scopes, new_version=True) new_text_version.edit(new_title, new_format, new_content, new_tags, new_note, True, cancel_modified_scopes) new_text_version.user = request.user if request.user.is_authenticated() else None new_text_version.note = request.POST.get('note','') new_text_version.email = request.POST.get('email','') new_text_version.name = request.POST.get('name','') new_text_version.save() return new_text_version def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False, instance=None): ModelForm.__init__(self, data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # override manually to disabled format_field = self.fields['format'] format_field.widget.attrs = {'disabled':'disabled'} format_field.required = False self.fields['format'] = format_field @has_perm_on_text('can_edit_text') def text_pre_edit(request, key, adminkey=None): text = get_text_by_keys_or_404(key) text_version = text.get_latest_version() comments = text_version.get_comments() ; new_format = request.POST['new_format'] new_content = on_content_receive(request.POST['new_content'], new_format) # TODO: RBE : si commentaire mal forme : (position non existante : boom par key error) _tomodify_comments, toremove_comments = compute_new_comment_positions(text_version.content, text_version.format, new_content, new_format, comments) return HttpResponse(simplejson.dumps({'nb_removed' : len(toremove_comments) })) class EditTextFormAnon(EditTextForm): name = forms.CharField(label=ugettext_lazy("Name (optional)"), widget=forms.TextInput, required=False) email = forms.EmailField(label=ugettext_lazy("Email (optional)"), required=False) content = forms.CharField(label=ugettext_lazy("Content"), required=True, widget=forms.Textarea(attrs={'rows':'30', 'cols': '70'})) class Meta: model = TextVersion fields = ('title', 'format', 'content', 'tags', 'note', 'name', 'email') @has_perm_on_text('can_edit_text') def text_edit(request, key, adminkey=None): text = get_text_by_keys_or_404(key) text_version = text.get_latest_version() if request.method == 'POST': if request.user.is_authenticated(): form = EditTextForm(request.POST) else: form = EditTextFormAnon(request.POST) if form.is_valid(): if request.POST.get('new_version'): new_version = form.save_new_version(text, request) register_activity(request, "text_edited_new_version", text=text, text_version=new_version) else: form.save_into_text(text, request) register_activity(request, "text_edited", text=text) return redirect(request, 'text-view', args=[text.key]) else: default_data = { 'content': text_version.content, 'title': text_version.title, 'format': text_version.format, 'tags': text_version.tags, 'new_version': NEW_TEXT_VERSION_ON_EDIT, 'note' : '', 'keep_comments' : True, } if request.user.is_authenticated(): form = EditTextForm(default_data) else: form = EditTextFormAnon(default_data) template_dict = {'text' : text, 'form' : form} return render_to_response('site/text_edit.html', template_dict , context_instance=RequestContext(request)) @has_perm_on_text('can_edit_text') def text_revert(request, key, text_version_key): if request.method != 'POST': raise UnauthorizedException('Unauthorized') text = get_text_by_keys_or_404(key) text_version = text.revert_to_version(text_version_key) display_message(request, _(u'A new version (copied from version %(version_title)s) has been created') % {'version_title':text_version.title}) return HttpResponse('') # no redirect because this is called by js @has_perm_on_text('can_view_text') def text_attach(request, key, attach_key): attach = Attachment.objects.get(key=attach_key, text_version__text__key=key) content = file(attach.data.path).read() mimetype, _encoding = mimetypes.guess_type(attach.data.path) response = HttpResponse(content, mimetype) return response def fix_anon_in_formset(formset): # fix role choice in formset for anon (not all role are allowed) role_field = [f.fields['role'] for f in formset.forms if f.instance.user == None][0] role_field.choices = [(u'', u'---------')] + [(r.id, str(r)) for r in Role.objects.filter(anon = True)] # limit anon choices class BaseUserRoleFormSet(BaseModelFormSet): def clean(self): """Checks that anon users are given roles with anon=True.""" for i in range(0, self.total_form_count()): form = self.forms[i] print form.cleaned_data user_role = form.cleaned_data['id'] if user_role.user == None: role = form.cleaned_data['role'] if not role.anon: # nasty stuff: cannot happen so not dealt with in tempate logging.warn('Cannot give such role to anon user.') raise forms.ValidationError, "Cannot give such role to anon user." #@has_perm_on_text('can_manage_text') #def xtext_share(request, key): # text = get_text_by_keys_or_404(key) # order_by = get_among(request.GET,'order',('user__username','-user__username','role__name','-role__name'),'user__username') # # UserRole.objects.create_userroles_text(text) # UserRoleFormSet = modelformset_factory(UserRole, fields=('role', ), extra=0, formset = BaseUserRoleFormSet) # # # put anon users on top no matter what the order says (TODO: ?) # userrole_queryset = UserRole.objects.filter(text=text).extra(select={'anon':'"cm_userrole"."user_id">-1'}).order_by('-anon',order_by) # if request.method == 'POST': # formset = UserRoleFormSet(request.POST, queryset = userrole_queryset) # # if formset.is_valid(): # formset.save() # display_message(request, "Sharing updated.") # return HttpResponseRedirect(reverse('text-share',args=[text.key])) # # else: # formset = UserRoleFormSet(queryset = userrole_queryset) # fix_anon_in_formset(formset) # # global_anon_userrole = UserRole.objects.get(text=None, user=None) # return render_to_response('site/text_share.html', {'text' : text, # 'formset' : formset, # 'global_anon_userrole' : global_anon_userrole, # } , context_instance=RequestContext(request)) # TODO: permission protection ? format value check ? def text_wysiwyg_preview(request, format): html_content = "" if request.POST : # if satisfied in the no html case, in html case : no POST (cf. markitup) previewTemplatePath and previewParserPath html_content = pandoc_convert(request.POST['data'], format, "html", full=False) return render_to_response('site/wysiwyg_preview.html', {'content':html_content} , context_instance=RequestContext(request)) #return HttpResponse(pandoc_convert(content, format, "html", full=False)) USER_PAGINATION = 10 @has_perm_on_text('can_manage_text') def text_share(request, key): display_suspended_users = get_int(request.GET, 'display', 0) tag_selected = request.GET.get('tag_selected', 0) paginate_by = get_int(request.GET, 'paginate', USER_PAGINATION) text = get_text_by_keys_or_404(key) order_by = get_among(request.GET,'order',('user__username', 'user__email', '-user__username', '-user__email', 'role__name', '-role__name', ), 'user__username') UserRole.objects.create_userroles_text(text) if request.method == 'POST': if 'save' in request.POST: user_profile_keys_roles = get_keys_from_dict(request.POST, 'user-role-') count = 0 for user_profile_key in user_profile_keys_roles: role_id = user_profile_keys_roles[user_profile_key] if not user_profile_key: user_role = UserRole.objects.get(user = None, text = text) else: user_role = UserRole.objects.get(user__userprofile__key = user_profile_key, text = text) if (role_id != u'' or user_role.role_id!=None) and role_id!=unicode(user_role.role_id): if role_id: user_role.role_id = int(role_id) else: user_role.role_id = None user_role.save() count += 1 display_message(request, _(u'%(count)i user(s) role modified') %{'count':count}) return HttpResponseRedirect(reverse('text-share', args=[text.key])) anon_role = UserRole.objects.get(user = None, text = text).role global_anon_role = UserRole.objects.get(user = None, text = None).role context = { 'anon_role' : anon_role, 'global_anon_role' : global_anon_role, 'all_roles' : Role.objects.all(), 'anon_roles' : Role.objects.filter(anon = True), 'text' : text, 'display_suspended_users' : display_suspended_users, 'tag_list' : Tag.objects.usage_for_model(UserProfile), 'tag_selected': tag_selected, } query = UserRole.objects.filter(text=text).filter(~Q(user=None)).order_by(order_by) if not display_suspended_users: query = query.exclude(Q(user__userprofile__is_suspended=True) & Q(user__is_active=True)) else: # trick to include userprofile table anyway (to filter by tags) query = query.filter(Q(user__userprofile__is_suspended=True) | Q(user__userprofile__is_suspended=False)) if tag_selected: tag_ids = Tag.objects.filter(name=tag_selected) if tag_ids: content_type_id = ContentType.objects.get_for_model(UserProfile).pk query = query.extra(where=['tagging_taggeditem.object_id = cm_userprofile.id', 'tagging_taggeditem.content_type_id = %i' %content_type_id, 'tagging_taggeditem.tag_id = %i' %tag_ids[0].id], tables=['tagging_taggeditem'], ) return object_list(request, query, template_name = 'site/text_share.html', paginate_by = paginate_by, extra_context = context, ) class SettingsTextForm(ModelForm): # example name = forms.CharField(label=_("Name (optional)"), widget=forms.TextInput, required=False) class Meta: model = TextVersion fields = ('mod_posteriori',) @has_perm_on_text('can_manage_text') def text_settings(request, key): text = get_text_by_keys_or_404(key) text_version = text.get_latest_version() if request.method == 'POST': form = SettingsTextForm(request.POST, instance = text_version) if form.is_valid(): form.save() display_message(request, _(u'Text settings updated')) return redirect(request, 'text-view', args=[text.key]) else: form = SettingsTextForm(instance = text_version) template_dict = {'text' : text, 'form' : form} return render_to_response('site/text_settings.html', template_dict , context_instance=RequestContext(request))
#!/usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import time import tensorflow as tf from lib.models import nn from vocab import Vocab from lib.models.parsers.base_parser import BaseParser #*************************************************************** class Parser(BaseParser): """""" def print_once(self, *args, **kwargs): if self.print_stuff: print(*args, **kwargs) #============================================================= def __call__(self, dataset, moving_params=None): """""" self.print_stuff = dataset.name == "Trainset" self.multi_penalties = {k: float(v) for k, v in map(lambda s: s.split(':'), self.multitask_penalties.split(';'))} if self.multitask_penalties else {} self.multi_layers = {k: set(map(int, v.split(','))) for k, v in map(lambda s: s.split(':'), self.multitask_layers.split(';'))} if self.multitask_layers else {} # todo use variables for vocabs this indexing is stupid vocabs = dataset.vocabs inputs = dataset.inputs targets = dataset.targets step = dataset.step num_pos_classes = len(vocabs[1]) num_rel_classes = len(vocabs[2]) num_srl_classes = len(vocabs[3]) num_pred_classes = len(vocabs[4]) # need to add batch dim for batch size 1 # inputs = tf.Print(inputs, [tf.shape(inputs), tf.shape(targets)], summarize=10) reuse = (moving_params is not None) self.tokens_to_keep3D = tf.expand_dims(tf.to_float(tf.greater(inputs[:,:,0], vocabs[0].ROOT)), 2) self.sequence_lengths = tf.reshape(tf.reduce_sum(self.tokens_to_keep3D, [1, 2]), [-1,1]) self.n_tokens = tf.reduce_sum(self.sequence_lengths) self.moving_params = moving_params word_inputs, pret_inputs = vocabs[0].embedding_lookup(inputs[:,:,0], inputs[:,:,1], moving_params=self.moving_params) if self.add_to_pretrained: word_inputs += pret_inputs if self.word_l2_reg > 0: unk_mask = tf.expand_dims(tf.to_float(tf.greater(inputs[:,:,1], vocabs[0].UNK)), 2) word_loss = self.word_l2_reg*tf.nn.l2_loss((word_inputs - pret_inputs) * unk_mask) inputs_to_embed = [word_inputs] if self.add_pos_to_input: pos_inputs = vocabs[1].embedding_lookup(inputs[:, :, 2], moving_params=self.moving_params) inputs_to_embed.append(pos_inputs) embed_inputs = self.embed_concat(*inputs_to_embed) if self.add_predicates_to_input: predicate_embed_inputs = vocabs[4].embedding_lookup(inputs[:, :, 3], moving_params=self.moving_params) embed_inputs = tf.concat([embed_inputs, predicate_embed_inputs], axis=2) top_recur = embed_inputs attn_weights_by_layer = {} kernel = 3 hidden_size = self.num_heads * self.head_size self.print_once("n_recur: ", self.n_recur) self.print_once("num heads: ", self.num_heads) self.print_once("cnn dim: ", self.cnn_dim) self.print_once("relu hidden size: ", self.relu_hidden_size) self.print_once("head size: ", self.head_size) self.print_once("cnn2d_layers: ", self.cnn2d_layers) self.print_once("cnn_dim_2d: ", self.cnn_dim_2d) self.print_once("multitask penalties: ", self.multi_penalties) self.print_once("multitask layers: ", self.multi_layers) self.print_once("sampling schedule: ", self.sampling_schedule) # maps joint predicate/pos indices to pos indices preds_to_pos_map = np.zeros([num_pred_classes, 1], dtype=np.int32) if self.joint_pos_predicates: for pred_label, pred_idx in vocabs[4].iteritems(): if pred_label in vocabs[4].SPECIAL_TOKENS: postag = pred_label else: _, postag = pred_label.split('/') pos_idx = vocabs[1][postag] preds_to_pos_map[pred_idx] = pos_idx # todo these are actually wrong because of nesting bilou_constraints = np.zeros((num_srl_classes, num_srl_classes)) if self.transition_statistics: with open(self.transition_statistics, 'r') as f: for line in f: tag1, tag2, prob = line.split("\t") bilou_constraints[vocabs[3][tag1], vocabs[3][tag2]] = float(prob) ###### stuff for multitask attention ###### multitask_targets = {} mask2d = self.tokens_to_keep3D * tf.transpose(self.tokens_to_keep3D, [0, 2, 1]) # compute targets adj matrix shape = tf.shape(targets[:, :, 1]) batch_size = shape[0] bucket_size = shape[1] i1, i2 = tf.meshgrid(tf.range(batch_size), tf.range(bucket_size), indexing="ij") idx = tf.stack([i1, i2, targets[:, :, 1]], axis=-1) adj = tf.scatter_nd(idx, tf.ones([batch_size, bucket_size]), [batch_size, bucket_size, bucket_size]) adj = adj * mask2d # roots_mask = 1. - tf.expand_dims(tf.eye(bucket_size), 0) # create parents targets parents = targets[:, :, 1] multitask_targets['parents'] = parents # create children targets multitask_targets['children'] = parents # create grandparents targets i1, i2 = tf.meshgrid(tf.range(batch_size), tf.range(bucket_size), indexing="ij") idx = tf.reshape(tf.stack([i1, tf.nn.relu(parents)], axis=-1), [-1, 2]) grandparents = tf.reshape(tf.gather_nd(parents, idx), [batch_size, bucket_size]) multitask_targets['grandparents'] = grandparents grand_idx = tf.stack([i1, i2, grandparents], axis=-1) grand_adj = tf.scatter_nd(grand_idx, tf.ones([batch_size, bucket_size]), [batch_size, bucket_size, bucket_size]) grand_adj = grand_adj * mask2d # whether to condition on gold or predicted parse use_gold_parse = self.inject_manual_attn and not ((moving_params is not None) and self.gold_attn_at_train) sample_prob = self.get_sample_prob(step) if use_gold_parse and (moving_params is None): use_gold_parse_tensor = tf.less(tf.random_uniform([]), sample_prob) else: use_gold_parse_tensor = tf.equal(int(use_gold_parse), 1) ##### Functions for predicting parse, Dozat-style ##### def get_parse_logits(parse_inputs): ######## do parse-specific stuff (arcs) ######## with tf.variable_scope('MLP', reuse=reuse): dep_mlp, head_mlp = self.MLP(parse_inputs, self.class_mlp_size + self.attn_mlp_size, n_splits=2) dep_arc_mlp, dep_rel_mlp = dep_mlp[:, :, :self.attn_mlp_size], dep_mlp[:, :, self.attn_mlp_size:] head_arc_mlp, head_rel_mlp = head_mlp[:, :, :self.attn_mlp_size], head_mlp[:, :, self.attn_mlp_size:] with tf.variable_scope('Arcs', reuse=reuse): arc_logits = self.bilinear_classifier(dep_arc_mlp, head_arc_mlp) arc_logits = tf.cond(tf.less_equal(tf.shape(tf.shape(arc_logits))[0], 2), lambda: tf.reshape(arc_logits, [batch_size, 1, 1]), lambda: arc_logits) # arc_logits = tf.Print(arc_logits, [tf.shape(arc_logits), tf.shape(tf.shape(arc_logits))]) return arc_logits, dep_rel_mlp, head_rel_mlp def dummy_parse_logits(): dummy_rel_mlp = tf.zeros([batch_size, bucket_size, self.class_mlp_size]) return tf.zeros([batch_size, bucket_size, bucket_size]), dummy_rel_mlp, dummy_rel_mlp arc_logits, dep_rel_mlp, head_rel_mlp = dummy_parse_logits() ########################################### with tf.variable_scope("crf", reuse=reuse): # to share parameters, change scope here if self.viterbi_train: transition_params = tf.get_variable("transitions", [num_srl_classes, num_srl_classes], initializer=tf.constant_initializer(bilou_constraints)) elif self.viterbi_decode: transition_params = tf.get_variable("transitions", [num_srl_classes, num_srl_classes], initializer=tf.constant_initializer(bilou_constraints), trainable=False) else: transition_params = None self.print_once("using transition params: ", transition_params) assert (self.cnn_layers != 0 and self.n_recur != 0) or self.num_blocks == 1, "num_blocks should be 1 if cnn_layers or n_recur is 0" assert self.dist_model == 'bilstm' or self.dist_model == 'transformer', 'Model must be either "transformer" or "bilstm"' for b in range(self.num_blocks): with tf.variable_scope("block%d" % b, reuse=reuse): # to share parameters, change scope here # Project for CNN input if self.cnn_layers > 0: with tf.variable_scope('proj0', reuse=reuse): top_recur = self.MLP(top_recur, self.cnn_dim, n_splits=1) ####### 1D CNN ######## with tf.variable_scope('CNN', reuse=reuse): for i in xrange(self.cnn_layers): with tf.variable_scope('layer%d' % i, reuse=reuse): if self.cnn_residual: top_recur += self.CNN(top_recur, 1, kernel, self.cnn_dim, self.recur_keep_prob, self.info_func) top_recur = nn.layer_norm(top_recur, reuse) else: top_recur = self.CNN(top_recur, 1, kernel, self.cnn_dim, self.recur_keep_prob, self.info_func) if self.cnn_residual and self.n_recur > 0: top_recur = nn.layer_norm(top_recur, reuse) # if layer is set to -2, these are used pos_pred_inputs = top_recur self.print_once("Setting pos_pred_inputs to: %s" % top_recur.name) predicate_inputs = top_recur self.print_once("Setting predicate_inputs to: %s" % top_recur.name) # Project for Tranformer / residual LSTM input if self.n_recur > 0: if self.dist_model == "transformer": with tf.variable_scope('proj1', reuse=reuse): top_recur = self.MLP(top_recur, hidden_size, n_splits=1) if self.lstm_residual and self.dist_model == "bilstm": with tf.variable_scope('proj1', reuse=reuse): top_recur = self.MLP(top_recur, (2 if self.recur_bidir else 1) * self.recur_size, n_splits=1) # if layer is set to -1, these are used if self.pos_layer == -1: pos_pred_inputs = top_recur self.print_once("Setting pos_pred_inputs to: %s" % top_recur.name) if self.predicate_layer == -1: predicate_inputs = top_recur self.print_once("Setting predicate_inputs to: %s" % top_recur.name) ##### Transformer ####### if self.dist_model == 'transformer': with tf.variable_scope('Transformer', reuse=reuse): top_recur = nn.add_timing_signal_1d(top_recur) for i in range(self.n_recur): with tf.variable_scope('layer%d' % i, reuse=reuse): manual_attn = None hard_attn = False # todo make this into gold_at_train and gold_at_test flags... + scheduled sampling if 'parents' in self.multi_layers.keys() and i in self.multi_layers['parents'] and (use_gold_parse or self.full_parse): # if use_gold_parse: # manual_attn = adj # # manual_attn = tf.Print(manual_attn, [tf.shape(manual_attn), manual_attn], "gold attn", summarize=100) # if self.full_parse: arc_logits, dep_rel_mlp, head_rel_mlp = get_parse_logits(top_recur) # # arc_logits = tf.Print(arc_logits, [tf.shape(arc_logits), arc_logits], "arc_logits", summarize=100) # # if not use_gold_parse: # # # compute full parse and set it here manual_attn = tf.cond(use_gold_parse_tensor, lambda: adj, lambda: tf.nn.softmax(arc_logits)) this_layer_capsule_heads = self.num_capsule_heads if i > 0 else 0 if 'children' in self.multi_layers.keys() and i in self.multi_layers['children']: this_layer_capsule_heads = 1 if use_gold_parse: manual_attn = tf.transpose(adj, [0, 2, 1]) self.print_once("Layer %d capsule heads: %d" % (i, this_layer_capsule_heads)) # if use_gold_parse: # if 'parents' in self.multi_layers.keys() and i in self.multi_layers['parents']: # manual_attn = adj # elif 'grandparents' in self.multi_layers.keys() and i in self.multi_layers['grandparents']: # manual_attn = grand_adj # elif 'children' in self.multi_layers.keys() and i in self.multi_layers['children']: # manual_attn = tf.transpose(adj, [0, 2, 1]) # only at test time if moving_params is not None and self.hard_attn: hard_attn = True # if 'children' in self.multi_layers.keys() and i in self.multi_layers['children'] and \ # self.multi_penalties['children'] != 0.: # this_layer_capsule_heads = 1 # else: top_recur, attn_weights = self.transformer(top_recur, hidden_size, self.num_heads, self.attn_dropout, self.relu_dropout, self.prepost_dropout, self.relu_hidden_size, self.info_func, self.ff_kernel, reuse, this_layer_capsule_heads, manual_attn, hard_attn) # head x batch x seq_len x seq_len attn_weights_by_layer[i] = tf.transpose(attn_weights, [1, 0, 2, 3]) if i == self.pos_layer: pos_pred_inputs = top_recur self.print_once("Setting pos_pred_inputs to: %s" % top_recur.name) if i == self.predicate_layer: predicate_inputs = top_recur self.print_once("Setting predicate_inputs to: %s" % top_recur.name) if i == self.parse_layer: parse_pred_inputs = top_recur self.print_once("Setting parse_pred_inputs to: %s" % top_recur.name) # if normalization is done in layer_preprocess, then it should also be done # on the output, since the output can grow very large, being the sum of # a whole stack of unnormalized layer outputs. if self.n_recur > 0: top_recur = nn.layer_norm(top_recur, reuse) ##### BiLSTM ####### if self.dist_model == 'bilstm': with tf.variable_scope("BiLSTM", reuse=reuse): for i in range(self.n_recur): with tf.variable_scope('layer%d' % i, reuse=reuse): if self.lstm_residual: top_recur_curr, _ = self.RNN(top_recur) top_recur += top_recur_curr # top_recur = nn.layer_norm(top_recur, reuse) else: top_recur, _ = self.RNN(top_recur) # if self.lstm_residual and self.n_recur > 0: # top_recur = nn.layer_norm(top_recur, reuse) if self.num_blocks > 1: top_recur = nn.layer_norm(top_recur, reuse) if self.pos_layer == self.n_recur - 1: pos_pred_inputs = top_recur self.print_once("Setting pos_pred_inputs to: %s" % top_recur.name) if self.predicate_layer == self.n_recur - 1: predicate_inputs = top_recur self.print_once("Setting predicate_inputs to: %s" % top_recur.name) if self.parse_layer == self.n_recur - 1: parse_pred_inputs = top_recur self.print_once("Setting parse_pred_inputs to: %s" % top_recur.name) ####### 2D CNN ######## # if self.cnn2d_layers > 0: # with tf.variable_scope('proj2', reuse=reuse): # top_recur_rows, top_recur_cols = self.MLP(top_recur, self.cnn_dim_2d//2, n_splits=2) # # top_recur_rows, top_recur_cols = self.MLP(top_recur, self.cnn_dim // 4, n_splits=2) # # top_recur_rows = nn.add_timing_signal_1d(top_recur_rows) # top_recur_cols = nn.add_timing_signal_1d(top_recur_cols) # # with tf.variable_scope('2d', reuse=reuse): # # set up input (split -> 2d) # input_shape = tf.shape(embed_inputs) # bucket_size = input_shape[1] # top_recur_rows = tf.tile(tf.expand_dims(top_recur_rows, 1), [1, bucket_size, 1, 1]) # top_recur_cols = tf.tile(tf.expand_dims(top_recur_cols, 2), [1, 1, bucket_size, 1]) # top_recur_2d = tf.concat([top_recur_cols, top_recur_rows], axis=-1) # # # apply num_convs 2d conv layers (residual) # for i in xrange(self.cnn2d_layers): # todo pass this in # with tf.variable_scope('CNN%d' % i, reuse=reuse): # top_recur_2d += self.CNN(top_recur_2d, kernel, kernel, self.cnn_dim_2d, # todo pass this in # self.recur_keep_prob if i < self.cnn2d_layers - 1 else 1.0, # self.info_func if i < self.cnn2d_layers - 1 else tf.identity) # top_recur_2d = nn.layer_norm(top_recur_2d, reuse) # # with tf.variable_scope('Arcs', reuse=reuse): # arc_logits = self.MLP(top_recur_2d, 1, n_splits=1) # arc_logits = tf.squeeze(arc_logits, axis=-1) # arc_output = self.output_svd(arc_logits, targets[:, :, 1]) # if moving_params is None: # predictions = targets[:, :, 1] # else: # predictions = arc_output['predictions'] # # # Project each predicted (or gold) edge into head and dep rel representations # with tf.variable_scope('MLP', reuse=reuse): # # flat_labels = tf.reshape(predictions, [-1]) # original_shape = tf.shape(arc_logits) # batch_size = original_shape[0] # bucket_size = original_shape[1] # # num_classes = len(vocabs[2]) # i1, i2 = tf.meshgrid(tf.range(batch_size), tf.range(bucket_size), indexing="ij") # targ = i1 * bucket_size * bucket_size + i2 * bucket_size + predictions # idx = tf.reshape(targ, [-1]) # conditioned = tf.gather(tf.reshape(top_recur_2d, [-1, self.cnn_dim_2d]), idx) # conditioned = tf.reshape(conditioned, [batch_size, bucket_size, self.cnn_dim_2d]) # dep_rel_mlp, head_rel_mlp = self.MLP(conditioned, self.class_mlp_size + self.attn_mlp_size, n_splits=2) # else: # if arc_logits already computed, return them. else if arc_loss_penalty != 0, compute them, else dummy # arc_logits, dep_rel_mlp, head_rel_mlp = tf.cond(tf.greater(self.arc_loss_penalty, 0.0), # lambda: tf.cond(tf.equal(int(self.full_parse), 1), # lambda: (arc_logits, dep_rel_mlp, head_rel_mlp), # lambda: get_parse_logits(parse_pred_inputs)), # lambda: dummy_parse_logits()) if not self.full_parse and self.role_loss_penalty == 0. and self.predicate_loss_penalty == 0.0: arc_logits, dep_rel_mlp, head_rel_mlp = get_parse_logits(parse_pred_inputs) arc_output = self.output_svd(arc_logits, targets[:,:,1]) if moving_params is None: predictions = targets[:,:,1] else: predictions = arc_output['predictions'] parse_probs = arc_output['probabilities'] ######## do parse-specific stuff (rels) ######## def get_parse_rel_logits(): with tf.variable_scope('Rels', reuse=reuse): rel_logits, rel_logits_cond = self.conditional_bilinear_classifier(dep_rel_mlp, head_rel_mlp, num_rel_classes, predictions) return rel_logits, rel_logits_cond rel_logits, rel_logits_cond = tf.cond(tf.not_equal(self.rel_loss_penalty, 0.0), lambda: get_parse_rel_logits(), lambda: (tf.constant(0.), tf.constant(0.))) rel_output = self.output(rel_logits, targets[:, :, 2], num_rel_classes) rel_output['probabilities'] = tf.cond(tf.not_equal(self.rel_loss_penalty, 0.0), lambda: self.conditional_probabilities(rel_logits_cond), lambda: rel_output['probabilities']) # def compute_rels_output(): # with tf.variable_scope('Rels', reuse=reuse): # rel_logits, rel_logits_cond = self.conditional_bilinear_classifier(dep_rel_mlp, head_rel_mlp, len(vocabs[2]), predictions) # rel_output = self.output(rel_logits, targets[:, :, 2]) # rel_output['probabilities'] = self.conditional_probabilities(rel_logits_cond) # return rel_output # def dummy_compute_rels_output(): multitask_losses = {} multitask_correct = {} multitask_loss_sum = 0 # multitask_parents_preds = arc_logits ##### MULTITASK ATTN LOSS ###### if not self.full_parse: for l, attn_weights in attn_weights_by_layer.iteritems(): # attn_weights is: head x batch x seq_len x seq_len # idx into attention heads attn_idx = self.num_capsule_heads cap_attn_idx = 0 if 'parents' in self.multi_layers.keys() and l in self.multi_layers['parents']: outputs = self.output(attn_weights[attn_idx], multitask_targets['parents']) parse_probs = tf.nn.softmax(attn_weights[attn_idx]) # todo this is a bit of a hack attn_idx += 1 loss = self.multi_penalties['parents'] * outputs['loss'] multitask_losses['parents%s' % l] = loss multitask_correct['parents%s' % l] = outputs['n_correct'] multitask_loss_sum += loss if 'grandparents' in self.multi_layers.keys() and l in self.multi_layers['grandparents']: outputs = self.output(attn_weights[attn_idx], multitask_targets['grandparents']) attn_idx += 1 loss = self.multi_penalties['grandparents'] * outputs['loss'] multitask_losses['grandparents%s' % l] = loss multitask_loss_sum += loss if 'children' in self.multi_layers.keys() and l in self.multi_layers['children']: outputs = self.output_transpose(attn_weights[cap_attn_idx], multitask_targets['children']) cap_attn_idx += 1 loss = self.multi_penalties['children'] * outputs['loss'] multitask_losses['children%s' % l] = loss multitask_loss_sum += loss ######## Predicate detection ######## # predicate_targets = tf.where(tf.greater(targets[:, :, 3], self.predicate_true_start_idx), tf.ones([batch_size, bucket_size], dtype=tf.int32), # tf.zeros([batch_size, bucket_size], dtype=tf.int32)) predicate_targets = inputs[:, :, 3] def compute_predicates(predicate_input, name): with tf.variable_scope(name, reuse=reuse): predicate_classifier_mlp = self.MLP(predicate_input, self.predicate_pred_mlp_size, n_splits=1) with tf.variable_scope('SRL-Predicates-Classifier', reuse=reuse): predicate_classifier = self.MLP(predicate_classifier_mlp, num_pred_classes, n_splits=1) output = self.output_predicates(predicate_classifier, predicate_targets, vocabs[4].predicate_true_start_idx) return output # aux_trigger_loss = tf.constant(0.) # if self.train_aux_trigger_layer: # aux_trigger_output = compute_predicates(aux_trigger_inputs, 'SRL-Triggers-Aux', False) # aux_trigger_loss = self.aux_trigger_penalty * aux_trigger_output['loss'] predicate_targets_binary = tf.where(tf.greater(predicate_targets, vocabs[4].predicate_true_start_idx), tf.ones_like(predicate_targets), tf.zeros_like(predicate_targets)) # predicate_targets_binary = tf.Print(predicate_targets_binary, [predicate_targets], "predicate targets", summarize=200) def dummy_predicate_output(): return { 'loss': 0.0, 'predicate_predictions': predicate_targets_binary, 'predictions': predicate_targets, 'logits': 0.0, # 'gold_trigger_predictions': tf.transpose(predictions, [0, 2, 1]), 'count': 0., 'correct': 0., 'targets': 0, } predicate_output = tf.cond(tf.greater(self.predicate_loss_penalty, 0.0), lambda: compute_predicates(predicate_inputs, 'SRL-Predicates'), dummy_predicate_output) if moving_params is None or self.add_predicates_to_input or self.predicate_loss_penalty == 0.0: # gold predicate_predictions = predicate_targets_binary else: # predicted predicate_predictions = predicate_output['predicate_predictions'] # predicate_predictions = tf.Print(predicate_predictions, [predicate_targets], "predicate_targets", summarize=50) # predicate_predictions = tf.Print(predicate_predictions, [predicate_predictions], "predicate_predictions", summarize=50) ######## POS tags ######## def compute_pos(pos_input, pos_target): with tf.variable_scope('POS-Classifier', reuse=reuse): pos_classifier = self.MLP(pos_input, num_pos_classes, n_splits=1) output = self.output(pos_classifier, pos_target) return output pos_target = targets[:,:,0] pos_loss = tf.constant(0.) pos_correct = tf.constant(0.) pos_preds = pos_target if self.train_pos: pos_output = compute_pos(pos_pred_inputs, pos_target) pos_loss = self.pos_penalty * pos_output['loss'] pos_correct = pos_output['n_correct'] pos_preds = pos_output['predictions'] elif self.joint_pos_predicates: pos_preds = tf.squeeze(tf.nn.embedding_lookup(preds_to_pos_map, predicate_output['predictions']), -1) pos_correct = tf.reduce_sum(tf.cast(tf.equal(pos_preds, pos_target), tf.float32) * tf.squeeze(self.tokens_to_keep3D, -1)) elif self.add_pos_to_input: pos_correct = tf.reduce_sum(tf.cast(tf.equal(inputs[:,:,2], pos_target), tf.float32) * tf.squeeze(self.tokens_to_keep3D, -1)) pos_preds = inputs[:,:,2] ######## do SRL-specific stuff (rels) ######## def compute_srl(srl_target): with tf.variable_scope('SRL-MLP', reuse=reuse): predicate_role_mlp = self.MLP(top_recur, self.predicate_mlp_size + self.role_mlp_size, n_splits=1) predicate_mlp, role_mlp = predicate_role_mlp[:,:,:self.predicate_mlp_size], predicate_role_mlp[:, :, self.predicate_mlp_size:] with tf.variable_scope('SRL-Arcs', reuse=reuse): # gather just the triggers # predicate_predictions: batch x seq_len # gathered_predicates: num_triggers_in_batch x 1 x self.trigger_mlp_size # role mlp: batch x seq_len x self.role_mlp_size # gathered roles: need a (bucket_size x self.role_mlp_size) role representation for each trigger, # i.e. a (num_triggers_in_batch x bucket_size x self.role_mlp_size) tensor predicate_gather_indices = tf.where(tf.equal(predicate_predictions, 1)) # predicate_gather_indices = tf.Print(predicate_gather_indices, [predicate_predictions, tf.shape(predicate_gather_indices), tf.shape(predicate_predictions)], "predicate gather shape", summarize=200) gathered_predicates = tf.expand_dims(tf.gather_nd(predicate_mlp, predicate_gather_indices), 1) tiled_roles = tf.reshape(tf.tile(role_mlp, [1, bucket_size, 1]), [batch_size, bucket_size, bucket_size, self.role_mlp_size]) gathered_roles = tf.gather_nd(tiled_roles, predicate_gather_indices) # now multiply them together to get (num_triggers_in_batch x bucket_size x num_srl_classes) tensor of scores srl_logits = self.bilinear_classifier_nary(gathered_predicates, gathered_roles, num_srl_classes) srl_logits_transpose = tf.transpose(srl_logits, [0, 2, 1]) srl_output = self.output_srl_gather(srl_logits_transpose, srl_target, predicate_predictions, transition_params if self.viterbi_train else None) return srl_output def compute_srl_simple(srl_target): with tf.variable_scope('SRL-MLP', reuse=reuse): # srl_logits are batch x seq_len x num_classes srl_logits = self.MLP(top_recur, num_srl_classes, n_splits=1) # srl_target is targets[:, :, 3:]: batch x seq_len x targets output = self.output(srl_logits, srl_target) srl_output = {f: output[f] for f in ['loss', 'probabilities', 'predictions', 'correct', 'count']} srl_output['logits'] = srl_logits srl_output['transition_params'] = tf.constant(0.) srl_output['correct'] = output['n_correct'] return srl_output srl_targets = targets[:, :, 3:] if self.role_loss_penalty == 0: # num_triggers = tf.reduce_sum(tf.cast(tf.where(tf.equal(predicate_targets_binary, 1)), tf.int32)) srl_output = { 'loss': tf.constant(0.), 'probabilities': tf.constant(0.), # tf.zeros([num_triggers, bucket_size, num_srl_classes]), 'predictions': tf.reshape(tf.transpose(srl_targets, [0, 2, 1]), [-1, bucket_size]), # tf.zeros([num_triggers, bucket_size]), 'logits': tf.constant(0.), # tf.zeros([num_triggers, bucket_size, num_srl_classes]), 'correct': tf.constant(0.), 'count': tf.constant(0.) } elif self.srl_simple_tagging: srl_output = compute_srl_simple(srl_targets) else: srl_output = compute_srl(srl_targets) predicate_loss = self.predicate_loss_penalty * predicate_output['loss'] srl_loss = self.role_loss_penalty * srl_output['loss'] arc_loss = self.arc_loss_penalty * arc_output['loss'] rel_loss = self.rel_loss_penalty * rel_output['loss'] # if this is a parse update, then actual parse loss equal to sum of rel loss and arc loss # actual_parse_loss = tf.cond(tf.equal(int(self.full_parse), 1), lambda: tf.add(rel_loss, arc_loss), lambda: tf.constant(0.)) # actual_parse_loss = tf.cond(do_parse_update, lambda: tf.add(rel_loss, arc_loss), lambda: tf.constant(0.)) parse_combined_loss = rel_loss + arc_loss # if this is a parse update and the parse proportion is not one, then no srl update. otherwise, # srl update equal to sum of srl_loss, predicate_loss srl_combined_loss = srl_loss + predicate_loss # actual_srl_loss = tf.cond(tf.logical_and(do_parse_update, tf.not_equal(self.parse_update_proportion, 1.0)), lambda: tf.constant(0.), lambda: srl_combined_loss) output = {} output['multitask_losses'] = multitask_losses output['probabilities'] = tf.tuple([parse_probs, rel_output['probabilities']]) output['predictions'] = tf.stack([arc_output['predictions'], rel_output['predictions']]) output['correct'] = arc_output['correct'] * rel_output['correct'] output['tokens'] = arc_output['tokens'] output['n_correct'] = tf.reduce_sum(output['correct']) output['n_tokens'] = self.n_tokens output['accuracy'] = output['n_correct'] / output['n_tokens'] output['loss'] = srl_combined_loss + parse_combined_loss + multitask_loss_sum + pos_loss # output['loss'] = srl_loss + predicate_loss + actual_parse_loss # output['loss'] = actual_srl_loss + arc_loss + rel_loss if self.word_l2_reg > 0: output['loss'] += word_loss output['embed'] = embed_inputs output['recur'] = top_recur # output['dep_arc'] = dep_arc_mlp # output['head_dep'] = head_arc_mlp output['dep_rel'] = dep_rel_mlp output['head_rel'] = head_rel_mlp output['arc_logits'] = arc_logits output['rel_logits'] = rel_logits output['rel_loss'] = rel_loss # rel_output['loss'] output['log_loss'] = arc_loss # arc_output['log_loss'] output['2cycle_loss'] = arc_output['2cycle_loss'] output['roots_loss'] = arc_output['roots_loss'] output['svd_loss'] = arc_output['svd_loss'] output['n_cycles'] = arc_output['n_cycles'] output['len_2_cycles'] = arc_output['len_2_cycles'] output['srl_loss'] = srl_loss output['srl_preds'] = srl_output['predictions'] output['srl_probs'] = srl_output['probabilities'] output['srl_logits'] = srl_output['logits'] output['srl_correct'] = srl_output['correct'] output['srl_count'] = srl_output['count'] output['transition_params'] = transition_params if transition_params is not None else tf.constant(bilou_constraints) output['srl_predicates'] = predicate_predictions output['srl_predicate_targets'] = predicate_targets_binary output['predicate_loss'] = predicate_loss output['predicate_count'] = predicate_output['count'] output['predicate_correct'] = predicate_output['correct'] output['predicate_preds'] = predicate_output['predictions'] output['sample_prob'] = sample_prob output['pos_loss'] = pos_loss output['pos_correct'] = pos_correct output['pos_preds'] = pos_preds # transpose and softmax attn weights attn_weights_by_layer_softmaxed = {k: tf.transpose(tf.nn.softmax(v), [1, 0, 2, 3]) for k, v in attn_weights_by_layer.iteritems()} output['attn_weights'] = attn_weights_by_layer_softmaxed output['attn_correct'] = multitask_correct return output #============================================================= def prob_argmax(self, parse_probs, rel_probs, tokens_to_keep, n_cycles=-1, len_2_cycles=-1): """""" start_time = time.time() parse_preds, roots_lt, roots_gt = self.parse_argmax(parse_probs, tokens_to_keep, n_cycles, len_2_cycles) rel_probs = rel_probs[np.arange(len(parse_preds)), parse_preds] rel_preds = self.rel_argmax(rel_probs, tokens_to_keep) total_time = time.time() - start_time return parse_preds, rel_preds, total_time, roots_lt, roots_gt actually use pretrained #!/usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import time import tensorflow as tf from lib.models import nn from vocab import Vocab from lib.models.parsers.base_parser import BaseParser #*************************************************************** class Parser(BaseParser): """""" def print_once(self, *args, **kwargs): if self.print_stuff: print(*args, **kwargs) #============================================================= def __call__(self, dataset, moving_params=None): """""" self.print_stuff = dataset.name == "Trainset" self.multi_penalties = {k: float(v) for k, v in map(lambda s: s.split(':'), self.multitask_penalties.split(';'))} if self.multitask_penalties else {} self.multi_layers = {k: set(map(int, v.split(','))) for k, v in map(lambda s: s.split(':'), self.multitask_layers.split(';'))} if self.multitask_layers else {} # todo use variables for vocabs this indexing is stupid vocabs = dataset.vocabs inputs = dataset.inputs targets = dataset.targets step = dataset.step num_pos_classes = len(vocabs[1]) num_rel_classes = len(vocabs[2]) num_srl_classes = len(vocabs[3]) num_pred_classes = len(vocabs[4]) # need to add batch dim for batch size 1 # inputs = tf.Print(inputs, [tf.shape(inputs), tf.shape(targets)], summarize=10) reuse = (moving_params is not None) self.tokens_to_keep3D = tf.expand_dims(tf.to_float(tf.greater(inputs[:,:,0], vocabs[0].ROOT)), 2) self.sequence_lengths = tf.reshape(tf.reduce_sum(self.tokens_to_keep3D, [1, 2]), [-1,1]) self.n_tokens = tf.reduce_sum(self.sequence_lengths) self.moving_params = moving_params word_inputs, pret_inputs = vocabs[0].embedding_lookup(inputs[:,:,0], inputs[:,:,1], moving_params=self.moving_params) if self.add_to_pretrained: word_inputs += pret_inputs else: word_inputs = pret_inputs if self.word_l2_reg > 0: unk_mask = tf.expand_dims(tf.to_float(tf.greater(inputs[:,:,1], vocabs[0].UNK)), 2) word_loss = self.word_l2_reg*tf.nn.l2_loss((word_inputs - pret_inputs) * unk_mask) inputs_to_embed = [word_inputs] if self.add_pos_to_input: pos_inputs = vocabs[1].embedding_lookup(inputs[:, :, 2], moving_params=self.moving_params) inputs_to_embed.append(pos_inputs) embed_inputs = self.embed_concat(*inputs_to_embed) if self.add_predicates_to_input: predicate_embed_inputs = vocabs[4].embedding_lookup(inputs[:, :, 3], moving_params=self.moving_params) embed_inputs = tf.concat([embed_inputs, predicate_embed_inputs], axis=2) top_recur = embed_inputs attn_weights_by_layer = {} kernel = 3 hidden_size = self.num_heads * self.head_size self.print_once("n_recur: ", self.n_recur) self.print_once("num heads: ", self.num_heads) self.print_once("cnn dim: ", self.cnn_dim) self.print_once("relu hidden size: ", self.relu_hidden_size) self.print_once("head size: ", self.head_size) self.print_once("cnn2d_layers: ", self.cnn2d_layers) self.print_once("cnn_dim_2d: ", self.cnn_dim_2d) self.print_once("multitask penalties: ", self.multi_penalties) self.print_once("multitask layers: ", self.multi_layers) self.print_once("sampling schedule: ", self.sampling_schedule) # maps joint predicate/pos indices to pos indices preds_to_pos_map = np.zeros([num_pred_classes, 1], dtype=np.int32) if self.joint_pos_predicates: for pred_label, pred_idx in vocabs[4].iteritems(): if pred_label in vocabs[4].SPECIAL_TOKENS: postag = pred_label else: _, postag = pred_label.split('/') pos_idx = vocabs[1][postag] preds_to_pos_map[pred_idx] = pos_idx # todo these are actually wrong because of nesting bilou_constraints = np.zeros((num_srl_classes, num_srl_classes)) if self.transition_statistics: with open(self.transition_statistics, 'r') as f: for line in f: tag1, tag2, prob = line.split("\t") bilou_constraints[vocabs[3][tag1], vocabs[3][tag2]] = float(prob) ###### stuff for multitask attention ###### multitask_targets = {} mask2d = self.tokens_to_keep3D * tf.transpose(self.tokens_to_keep3D, [0, 2, 1]) # compute targets adj matrix shape = tf.shape(targets[:, :, 1]) batch_size = shape[0] bucket_size = shape[1] i1, i2 = tf.meshgrid(tf.range(batch_size), tf.range(bucket_size), indexing="ij") idx = tf.stack([i1, i2, targets[:, :, 1]], axis=-1) adj = tf.scatter_nd(idx, tf.ones([batch_size, bucket_size]), [batch_size, bucket_size, bucket_size]) adj = adj * mask2d # roots_mask = 1. - tf.expand_dims(tf.eye(bucket_size), 0) # create parents targets parents = targets[:, :, 1] multitask_targets['parents'] = parents # create children targets multitask_targets['children'] = parents # create grandparents targets i1, i2 = tf.meshgrid(tf.range(batch_size), tf.range(bucket_size), indexing="ij") idx = tf.reshape(tf.stack([i1, tf.nn.relu(parents)], axis=-1), [-1, 2]) grandparents = tf.reshape(tf.gather_nd(parents, idx), [batch_size, bucket_size]) multitask_targets['grandparents'] = grandparents grand_idx = tf.stack([i1, i2, grandparents], axis=-1) grand_adj = tf.scatter_nd(grand_idx, tf.ones([batch_size, bucket_size]), [batch_size, bucket_size, bucket_size]) grand_adj = grand_adj * mask2d # whether to condition on gold or predicted parse use_gold_parse = self.inject_manual_attn and not ((moving_params is not None) and self.gold_attn_at_train) sample_prob = self.get_sample_prob(step) if use_gold_parse and (moving_params is None): use_gold_parse_tensor = tf.less(tf.random_uniform([]), sample_prob) else: use_gold_parse_tensor = tf.equal(int(use_gold_parse), 1) ##### Functions for predicting parse, Dozat-style ##### def get_parse_logits(parse_inputs): ######## do parse-specific stuff (arcs) ######## with tf.variable_scope('MLP', reuse=reuse): dep_mlp, head_mlp = self.MLP(parse_inputs, self.class_mlp_size + self.attn_mlp_size, n_splits=2) dep_arc_mlp, dep_rel_mlp = dep_mlp[:, :, :self.attn_mlp_size], dep_mlp[:, :, self.attn_mlp_size:] head_arc_mlp, head_rel_mlp = head_mlp[:, :, :self.attn_mlp_size], head_mlp[:, :, self.attn_mlp_size:] with tf.variable_scope('Arcs', reuse=reuse): arc_logits = self.bilinear_classifier(dep_arc_mlp, head_arc_mlp) arc_logits = tf.cond(tf.less_equal(tf.shape(tf.shape(arc_logits))[0], 2), lambda: tf.reshape(arc_logits, [batch_size, 1, 1]), lambda: arc_logits) # arc_logits = tf.Print(arc_logits, [tf.shape(arc_logits), tf.shape(tf.shape(arc_logits))]) return arc_logits, dep_rel_mlp, head_rel_mlp def dummy_parse_logits(): dummy_rel_mlp = tf.zeros([batch_size, bucket_size, self.class_mlp_size]) return tf.zeros([batch_size, bucket_size, bucket_size]), dummy_rel_mlp, dummy_rel_mlp arc_logits, dep_rel_mlp, head_rel_mlp = dummy_parse_logits() ########################################### with tf.variable_scope("crf", reuse=reuse): # to share parameters, change scope here if self.viterbi_train: transition_params = tf.get_variable("transitions", [num_srl_classes, num_srl_classes], initializer=tf.constant_initializer(bilou_constraints)) elif self.viterbi_decode: transition_params = tf.get_variable("transitions", [num_srl_classes, num_srl_classes], initializer=tf.constant_initializer(bilou_constraints), trainable=False) else: transition_params = None self.print_once("using transition params: ", transition_params) assert (self.cnn_layers != 0 and self.n_recur != 0) or self.num_blocks == 1, "num_blocks should be 1 if cnn_layers or n_recur is 0" assert self.dist_model == 'bilstm' or self.dist_model == 'transformer', 'Model must be either "transformer" or "bilstm"' for b in range(self.num_blocks): with tf.variable_scope("block%d" % b, reuse=reuse): # to share parameters, change scope here # Project for CNN input if self.cnn_layers > 0: with tf.variable_scope('proj0', reuse=reuse): top_recur = self.MLP(top_recur, self.cnn_dim, n_splits=1) ####### 1D CNN ######## with tf.variable_scope('CNN', reuse=reuse): for i in xrange(self.cnn_layers): with tf.variable_scope('layer%d' % i, reuse=reuse): if self.cnn_residual: top_recur += self.CNN(top_recur, 1, kernel, self.cnn_dim, self.recur_keep_prob, self.info_func) top_recur = nn.layer_norm(top_recur, reuse) else: top_recur = self.CNN(top_recur, 1, kernel, self.cnn_dim, self.recur_keep_prob, self.info_func) if self.cnn_residual and self.n_recur > 0: top_recur = nn.layer_norm(top_recur, reuse) # if layer is set to -2, these are used pos_pred_inputs = top_recur self.print_once("Setting pos_pred_inputs to: %s" % top_recur.name) predicate_inputs = top_recur self.print_once("Setting predicate_inputs to: %s" % top_recur.name) # Project for Tranformer / residual LSTM input if self.n_recur > 0: if self.dist_model == "transformer": with tf.variable_scope('proj1', reuse=reuse): top_recur = self.MLP(top_recur, hidden_size, n_splits=1) if self.lstm_residual and self.dist_model == "bilstm": with tf.variable_scope('proj1', reuse=reuse): top_recur = self.MLP(top_recur, (2 if self.recur_bidir else 1) * self.recur_size, n_splits=1) # if layer is set to -1, these are used if self.pos_layer == -1: pos_pred_inputs = top_recur self.print_once("Setting pos_pred_inputs to: %s" % top_recur.name) if self.predicate_layer == -1: predicate_inputs = top_recur self.print_once("Setting predicate_inputs to: %s" % top_recur.name) ##### Transformer ####### if self.dist_model == 'transformer': with tf.variable_scope('Transformer', reuse=reuse): top_recur = nn.add_timing_signal_1d(top_recur) for i in range(self.n_recur): with tf.variable_scope('layer%d' % i, reuse=reuse): manual_attn = None hard_attn = False # todo make this into gold_at_train and gold_at_test flags... + scheduled sampling if 'parents' in self.multi_layers.keys() and i in self.multi_layers['parents'] and (use_gold_parse or self.full_parse): # if use_gold_parse: # manual_attn = adj # # manual_attn = tf.Print(manual_attn, [tf.shape(manual_attn), manual_attn], "gold attn", summarize=100) # if self.full_parse: arc_logits, dep_rel_mlp, head_rel_mlp = get_parse_logits(top_recur) # # arc_logits = tf.Print(arc_logits, [tf.shape(arc_logits), arc_logits], "arc_logits", summarize=100) # # if not use_gold_parse: # # # compute full parse and set it here manual_attn = tf.cond(use_gold_parse_tensor, lambda: adj, lambda: tf.nn.softmax(arc_logits)) this_layer_capsule_heads = self.num_capsule_heads if i > 0 else 0 if 'children' in self.multi_layers.keys() and i in self.multi_layers['children']: this_layer_capsule_heads = 1 if use_gold_parse: manual_attn = tf.transpose(adj, [0, 2, 1]) self.print_once("Layer %d capsule heads: %d" % (i, this_layer_capsule_heads)) # if use_gold_parse: # if 'parents' in self.multi_layers.keys() and i in self.multi_layers['parents']: # manual_attn = adj # elif 'grandparents' in self.multi_layers.keys() and i in self.multi_layers['grandparents']: # manual_attn = grand_adj # elif 'children' in self.multi_layers.keys() and i in self.multi_layers['children']: # manual_attn = tf.transpose(adj, [0, 2, 1]) # only at test time if moving_params is not None and self.hard_attn: hard_attn = True # if 'children' in self.multi_layers.keys() and i in self.multi_layers['children'] and \ # self.multi_penalties['children'] != 0.: # this_layer_capsule_heads = 1 # else: top_recur, attn_weights = self.transformer(top_recur, hidden_size, self.num_heads, self.attn_dropout, self.relu_dropout, self.prepost_dropout, self.relu_hidden_size, self.info_func, self.ff_kernel, reuse, this_layer_capsule_heads, manual_attn, hard_attn) # head x batch x seq_len x seq_len attn_weights_by_layer[i] = tf.transpose(attn_weights, [1, 0, 2, 3]) if i == self.pos_layer: pos_pred_inputs = top_recur self.print_once("Setting pos_pred_inputs to: %s" % top_recur.name) if i == self.predicate_layer: predicate_inputs = top_recur self.print_once("Setting predicate_inputs to: %s" % top_recur.name) if i == self.parse_layer: parse_pred_inputs = top_recur self.print_once("Setting parse_pred_inputs to: %s" % top_recur.name) # if normalization is done in layer_preprocess, then it should also be done # on the output, since the output can grow very large, being the sum of # a whole stack of unnormalized layer outputs. if self.n_recur > 0: top_recur = nn.layer_norm(top_recur, reuse) ##### BiLSTM ####### if self.dist_model == 'bilstm': with tf.variable_scope("BiLSTM", reuse=reuse): for i in range(self.n_recur): with tf.variable_scope('layer%d' % i, reuse=reuse): if self.lstm_residual: top_recur_curr, _ = self.RNN(top_recur) top_recur += top_recur_curr # top_recur = nn.layer_norm(top_recur, reuse) else: top_recur, _ = self.RNN(top_recur) # if self.lstm_residual and self.n_recur > 0: # top_recur = nn.layer_norm(top_recur, reuse) if self.num_blocks > 1: top_recur = nn.layer_norm(top_recur, reuse) if self.pos_layer == self.n_recur - 1: pos_pred_inputs = top_recur self.print_once("Setting pos_pred_inputs to: %s" % top_recur.name) if self.predicate_layer == self.n_recur - 1: predicate_inputs = top_recur self.print_once("Setting predicate_inputs to: %s" % top_recur.name) if self.parse_layer == self.n_recur - 1: parse_pred_inputs = top_recur self.print_once("Setting parse_pred_inputs to: %s" % top_recur.name) ####### 2D CNN ######## # if self.cnn2d_layers > 0: # with tf.variable_scope('proj2', reuse=reuse): # top_recur_rows, top_recur_cols = self.MLP(top_recur, self.cnn_dim_2d//2, n_splits=2) # # top_recur_rows, top_recur_cols = self.MLP(top_recur, self.cnn_dim // 4, n_splits=2) # # top_recur_rows = nn.add_timing_signal_1d(top_recur_rows) # top_recur_cols = nn.add_timing_signal_1d(top_recur_cols) # # with tf.variable_scope('2d', reuse=reuse): # # set up input (split -> 2d) # input_shape = tf.shape(embed_inputs) # bucket_size = input_shape[1] # top_recur_rows = tf.tile(tf.expand_dims(top_recur_rows, 1), [1, bucket_size, 1, 1]) # top_recur_cols = tf.tile(tf.expand_dims(top_recur_cols, 2), [1, 1, bucket_size, 1]) # top_recur_2d = tf.concat([top_recur_cols, top_recur_rows], axis=-1) # # # apply num_convs 2d conv layers (residual) # for i in xrange(self.cnn2d_layers): # todo pass this in # with tf.variable_scope('CNN%d' % i, reuse=reuse): # top_recur_2d += self.CNN(top_recur_2d, kernel, kernel, self.cnn_dim_2d, # todo pass this in # self.recur_keep_prob if i < self.cnn2d_layers - 1 else 1.0, # self.info_func if i < self.cnn2d_layers - 1 else tf.identity) # top_recur_2d = nn.layer_norm(top_recur_2d, reuse) # # with tf.variable_scope('Arcs', reuse=reuse): # arc_logits = self.MLP(top_recur_2d, 1, n_splits=1) # arc_logits = tf.squeeze(arc_logits, axis=-1) # arc_output = self.output_svd(arc_logits, targets[:, :, 1]) # if moving_params is None: # predictions = targets[:, :, 1] # else: # predictions = arc_output['predictions'] # # # Project each predicted (or gold) edge into head and dep rel representations # with tf.variable_scope('MLP', reuse=reuse): # # flat_labels = tf.reshape(predictions, [-1]) # original_shape = tf.shape(arc_logits) # batch_size = original_shape[0] # bucket_size = original_shape[1] # # num_classes = len(vocabs[2]) # i1, i2 = tf.meshgrid(tf.range(batch_size), tf.range(bucket_size), indexing="ij") # targ = i1 * bucket_size * bucket_size + i2 * bucket_size + predictions # idx = tf.reshape(targ, [-1]) # conditioned = tf.gather(tf.reshape(top_recur_2d, [-1, self.cnn_dim_2d]), idx) # conditioned = tf.reshape(conditioned, [batch_size, bucket_size, self.cnn_dim_2d]) # dep_rel_mlp, head_rel_mlp = self.MLP(conditioned, self.class_mlp_size + self.attn_mlp_size, n_splits=2) # else: # if arc_logits already computed, return them. else if arc_loss_penalty != 0, compute them, else dummy # arc_logits, dep_rel_mlp, head_rel_mlp = tf.cond(tf.greater(self.arc_loss_penalty, 0.0), # lambda: tf.cond(tf.equal(int(self.full_parse), 1), # lambda: (arc_logits, dep_rel_mlp, head_rel_mlp), # lambda: get_parse_logits(parse_pred_inputs)), # lambda: dummy_parse_logits()) if not self.full_parse and self.role_loss_penalty == 0. and self.predicate_loss_penalty == 0.0: arc_logits, dep_rel_mlp, head_rel_mlp = get_parse_logits(parse_pred_inputs) arc_output = self.output_svd(arc_logits, targets[:,:,1]) if moving_params is None: predictions = targets[:,:,1] else: predictions = arc_output['predictions'] parse_probs = arc_output['probabilities'] ######## do parse-specific stuff (rels) ######## def get_parse_rel_logits(): with tf.variable_scope('Rels', reuse=reuse): rel_logits, rel_logits_cond = self.conditional_bilinear_classifier(dep_rel_mlp, head_rel_mlp, num_rel_classes, predictions) return rel_logits, rel_logits_cond rel_logits, rel_logits_cond = tf.cond(tf.not_equal(self.rel_loss_penalty, 0.0), lambda: get_parse_rel_logits(), lambda: (tf.constant(0.), tf.constant(0.))) rel_output = self.output(rel_logits, targets[:, :, 2], num_rel_classes) rel_output['probabilities'] = tf.cond(tf.not_equal(self.rel_loss_penalty, 0.0), lambda: self.conditional_probabilities(rel_logits_cond), lambda: rel_output['probabilities']) # def compute_rels_output(): # with tf.variable_scope('Rels', reuse=reuse): # rel_logits, rel_logits_cond = self.conditional_bilinear_classifier(dep_rel_mlp, head_rel_mlp, len(vocabs[2]), predictions) # rel_output = self.output(rel_logits, targets[:, :, 2]) # rel_output['probabilities'] = self.conditional_probabilities(rel_logits_cond) # return rel_output # def dummy_compute_rels_output(): multitask_losses = {} multitask_correct = {} multitask_loss_sum = 0 # multitask_parents_preds = arc_logits ##### MULTITASK ATTN LOSS ###### if not self.full_parse: for l, attn_weights in attn_weights_by_layer.iteritems(): # attn_weights is: head x batch x seq_len x seq_len # idx into attention heads attn_idx = self.num_capsule_heads cap_attn_idx = 0 if 'parents' in self.multi_layers.keys() and l in self.multi_layers['parents']: outputs = self.output(attn_weights[attn_idx], multitask_targets['parents']) parse_probs = tf.nn.softmax(attn_weights[attn_idx]) # todo this is a bit of a hack attn_idx += 1 loss = self.multi_penalties['parents'] * outputs['loss'] multitask_losses['parents%s' % l] = loss multitask_correct['parents%s' % l] = outputs['n_correct'] multitask_loss_sum += loss if 'grandparents' in self.multi_layers.keys() and l in self.multi_layers['grandparents']: outputs = self.output(attn_weights[attn_idx], multitask_targets['grandparents']) attn_idx += 1 loss = self.multi_penalties['grandparents'] * outputs['loss'] multitask_losses['grandparents%s' % l] = loss multitask_loss_sum += loss if 'children' in self.multi_layers.keys() and l in self.multi_layers['children']: outputs = self.output_transpose(attn_weights[cap_attn_idx], multitask_targets['children']) cap_attn_idx += 1 loss = self.multi_penalties['children'] * outputs['loss'] multitask_losses['children%s' % l] = loss multitask_loss_sum += loss ######## Predicate detection ######## # predicate_targets = tf.where(tf.greater(targets[:, :, 3], self.predicate_true_start_idx), tf.ones([batch_size, bucket_size], dtype=tf.int32), # tf.zeros([batch_size, bucket_size], dtype=tf.int32)) predicate_targets = inputs[:, :, 3] def compute_predicates(predicate_input, name): with tf.variable_scope(name, reuse=reuse): predicate_classifier_mlp = self.MLP(predicate_input, self.predicate_pred_mlp_size, n_splits=1) with tf.variable_scope('SRL-Predicates-Classifier', reuse=reuse): predicate_classifier = self.MLP(predicate_classifier_mlp, num_pred_classes, n_splits=1) output = self.output_predicates(predicate_classifier, predicate_targets, vocabs[4].predicate_true_start_idx) return output # aux_trigger_loss = tf.constant(0.) # if self.train_aux_trigger_layer: # aux_trigger_output = compute_predicates(aux_trigger_inputs, 'SRL-Triggers-Aux', False) # aux_trigger_loss = self.aux_trigger_penalty * aux_trigger_output['loss'] predicate_targets_binary = tf.where(tf.greater(predicate_targets, vocabs[4].predicate_true_start_idx), tf.ones_like(predicate_targets), tf.zeros_like(predicate_targets)) # predicate_targets_binary = tf.Print(predicate_targets_binary, [predicate_targets], "predicate targets", summarize=200) def dummy_predicate_output(): return { 'loss': 0.0, 'predicate_predictions': predicate_targets_binary, 'predictions': predicate_targets, 'logits': 0.0, # 'gold_trigger_predictions': tf.transpose(predictions, [0, 2, 1]), 'count': 0., 'correct': 0., 'targets': 0, } predicate_output = tf.cond(tf.greater(self.predicate_loss_penalty, 0.0), lambda: compute_predicates(predicate_inputs, 'SRL-Predicates'), dummy_predicate_output) if moving_params is None or self.add_predicates_to_input or self.predicate_loss_penalty == 0.0: # gold predicate_predictions = predicate_targets_binary else: # predicted predicate_predictions = predicate_output['predicate_predictions'] # predicate_predictions = tf.Print(predicate_predictions, [predicate_targets], "predicate_targets", summarize=50) # predicate_predictions = tf.Print(predicate_predictions, [predicate_predictions], "predicate_predictions", summarize=50) ######## POS tags ######## def compute_pos(pos_input, pos_target): with tf.variable_scope('POS-Classifier', reuse=reuse): pos_classifier = self.MLP(pos_input, num_pos_classes, n_splits=1) output = self.output(pos_classifier, pos_target) return output pos_target = targets[:,:,0] pos_loss = tf.constant(0.) pos_correct = tf.constant(0.) pos_preds = pos_target if self.train_pos: pos_output = compute_pos(pos_pred_inputs, pos_target) pos_loss = self.pos_penalty * pos_output['loss'] pos_correct = pos_output['n_correct'] pos_preds = pos_output['predictions'] elif self.joint_pos_predicates: pos_preds = tf.squeeze(tf.nn.embedding_lookup(preds_to_pos_map, predicate_output['predictions']), -1) pos_correct = tf.reduce_sum(tf.cast(tf.equal(pos_preds, pos_target), tf.float32) * tf.squeeze(self.tokens_to_keep3D, -1)) elif self.add_pos_to_input: pos_correct = tf.reduce_sum(tf.cast(tf.equal(inputs[:,:,2], pos_target), tf.float32) * tf.squeeze(self.tokens_to_keep3D, -1)) pos_preds = inputs[:,:,2] ######## do SRL-specific stuff (rels) ######## def compute_srl(srl_target): with tf.variable_scope('SRL-MLP', reuse=reuse): predicate_role_mlp = self.MLP(top_recur, self.predicate_mlp_size + self.role_mlp_size, n_splits=1) predicate_mlp, role_mlp = predicate_role_mlp[:,:,:self.predicate_mlp_size], predicate_role_mlp[:, :, self.predicate_mlp_size:] with tf.variable_scope('SRL-Arcs', reuse=reuse): # gather just the triggers # predicate_predictions: batch x seq_len # gathered_predicates: num_triggers_in_batch x 1 x self.trigger_mlp_size # role mlp: batch x seq_len x self.role_mlp_size # gathered roles: need a (bucket_size x self.role_mlp_size) role representation for each trigger, # i.e. a (num_triggers_in_batch x bucket_size x self.role_mlp_size) tensor predicate_gather_indices = tf.where(tf.equal(predicate_predictions, 1)) # predicate_gather_indices = tf.Print(predicate_gather_indices, [predicate_predictions, tf.shape(predicate_gather_indices), tf.shape(predicate_predictions)], "predicate gather shape", summarize=200) gathered_predicates = tf.expand_dims(tf.gather_nd(predicate_mlp, predicate_gather_indices), 1) tiled_roles = tf.reshape(tf.tile(role_mlp, [1, bucket_size, 1]), [batch_size, bucket_size, bucket_size, self.role_mlp_size]) gathered_roles = tf.gather_nd(tiled_roles, predicate_gather_indices) # now multiply them together to get (num_triggers_in_batch x bucket_size x num_srl_classes) tensor of scores srl_logits = self.bilinear_classifier_nary(gathered_predicates, gathered_roles, num_srl_classes) srl_logits_transpose = tf.transpose(srl_logits, [0, 2, 1]) srl_output = self.output_srl_gather(srl_logits_transpose, srl_target, predicate_predictions, transition_params if self.viterbi_train else None) return srl_output def compute_srl_simple(srl_target): with tf.variable_scope('SRL-MLP', reuse=reuse): # srl_logits are batch x seq_len x num_classes srl_logits = self.MLP(top_recur, num_srl_classes, n_splits=1) # srl_target is targets[:, :, 3:]: batch x seq_len x targets output = self.output(srl_logits, srl_target) srl_output = {f: output[f] for f in ['loss', 'probabilities', 'predictions', 'correct', 'count']} srl_output['logits'] = srl_logits srl_output['transition_params'] = tf.constant(0.) srl_output['correct'] = output['n_correct'] return srl_output srl_targets = targets[:, :, 3:] if self.role_loss_penalty == 0: # num_triggers = tf.reduce_sum(tf.cast(tf.where(tf.equal(predicate_targets_binary, 1)), tf.int32)) srl_output = { 'loss': tf.constant(0.), 'probabilities': tf.constant(0.), # tf.zeros([num_triggers, bucket_size, num_srl_classes]), 'predictions': tf.reshape(tf.transpose(srl_targets, [0, 2, 1]), [-1, bucket_size]), # tf.zeros([num_triggers, bucket_size]), 'logits': tf.constant(0.), # tf.zeros([num_triggers, bucket_size, num_srl_classes]), 'correct': tf.constant(0.), 'count': tf.constant(0.) } elif self.srl_simple_tagging: srl_output = compute_srl_simple(srl_targets) else: srl_output = compute_srl(srl_targets) predicate_loss = self.predicate_loss_penalty * predicate_output['loss'] srl_loss = self.role_loss_penalty * srl_output['loss'] arc_loss = self.arc_loss_penalty * arc_output['loss'] rel_loss = self.rel_loss_penalty * rel_output['loss'] # if this is a parse update, then actual parse loss equal to sum of rel loss and arc loss # actual_parse_loss = tf.cond(tf.equal(int(self.full_parse), 1), lambda: tf.add(rel_loss, arc_loss), lambda: tf.constant(0.)) # actual_parse_loss = tf.cond(do_parse_update, lambda: tf.add(rel_loss, arc_loss), lambda: tf.constant(0.)) parse_combined_loss = rel_loss + arc_loss # if this is a parse update and the parse proportion is not one, then no srl update. otherwise, # srl update equal to sum of srl_loss, predicate_loss srl_combined_loss = srl_loss + predicate_loss # actual_srl_loss = tf.cond(tf.logical_and(do_parse_update, tf.not_equal(self.parse_update_proportion, 1.0)), lambda: tf.constant(0.), lambda: srl_combined_loss) output = {} output['multitask_losses'] = multitask_losses output['probabilities'] = tf.tuple([parse_probs, rel_output['probabilities']]) output['predictions'] = tf.stack([arc_output['predictions'], rel_output['predictions']]) output['correct'] = arc_output['correct'] * rel_output['correct'] output['tokens'] = arc_output['tokens'] output['n_correct'] = tf.reduce_sum(output['correct']) output['n_tokens'] = self.n_tokens output['accuracy'] = output['n_correct'] / output['n_tokens'] output['loss'] = srl_combined_loss + parse_combined_loss + multitask_loss_sum + pos_loss # output['loss'] = srl_loss + predicate_loss + actual_parse_loss # output['loss'] = actual_srl_loss + arc_loss + rel_loss if self.word_l2_reg > 0: output['loss'] += word_loss output['embed'] = embed_inputs output['recur'] = top_recur # output['dep_arc'] = dep_arc_mlp # output['head_dep'] = head_arc_mlp output['dep_rel'] = dep_rel_mlp output['head_rel'] = head_rel_mlp output['arc_logits'] = arc_logits output['rel_logits'] = rel_logits output['rel_loss'] = rel_loss # rel_output['loss'] output['log_loss'] = arc_loss # arc_output['log_loss'] output['2cycle_loss'] = arc_output['2cycle_loss'] output['roots_loss'] = arc_output['roots_loss'] output['svd_loss'] = arc_output['svd_loss'] output['n_cycles'] = arc_output['n_cycles'] output['len_2_cycles'] = arc_output['len_2_cycles'] output['srl_loss'] = srl_loss output['srl_preds'] = srl_output['predictions'] output['srl_probs'] = srl_output['probabilities'] output['srl_logits'] = srl_output['logits'] output['srl_correct'] = srl_output['correct'] output['srl_count'] = srl_output['count'] output['transition_params'] = transition_params if transition_params is not None else tf.constant(bilou_constraints) output['srl_predicates'] = predicate_predictions output['srl_predicate_targets'] = predicate_targets_binary output['predicate_loss'] = predicate_loss output['predicate_count'] = predicate_output['count'] output['predicate_correct'] = predicate_output['correct'] output['predicate_preds'] = predicate_output['predictions'] output['sample_prob'] = sample_prob output['pos_loss'] = pos_loss output['pos_correct'] = pos_correct output['pos_preds'] = pos_preds # transpose and softmax attn weights attn_weights_by_layer_softmaxed = {k: tf.transpose(tf.nn.softmax(v), [1, 0, 2, 3]) for k, v in attn_weights_by_layer.iteritems()} output['attn_weights'] = attn_weights_by_layer_softmaxed output['attn_correct'] = multitask_correct return output #============================================================= def prob_argmax(self, parse_probs, rel_probs, tokens_to_keep, n_cycles=-1, len_2_cycles=-1): """""" start_time = time.time() parse_preds, roots_lt, roots_gt = self.parse_argmax(parse_probs, tokens_to_keep, n_cycles, len_2_cycles) rel_probs = rel_probs[np.arange(len(parse_preds)), parse_preds] rel_preds = self.rel_argmax(rel_probs, tokens_to_keep) total_time = time.time() - start_time return parse_preds, rel_preds, total_time, roots_lt, roots_gt
# Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved. # # This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA. # # SIPPY 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. # # For a license to use the SIPPY software under conditions # other than those described here, or to purchase support for this # software, please contact Sippy Software, Inc. by e-mail at the # following addresses: sales@sippysoft.com. # # SIPPY 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. # # $Id: UacStateUpdating.py,v 1.4 2008/09/24 09:25:38 sobomax Exp $ from UaStateGeneric import UaStateGeneric from CCEvents import CCEventDisconnect, CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect class UacStateUpdating(UaStateGeneric): sname = 'Updating(UAC)' triedauth = False connected = True def recvRequest(self, req): if req.getMethod() == 'INVITE': self.ua.global_config['sip_tm'].sendResponse(req.genResponse(491, 'Request Pending')) return None elif req.getMethod() == 'BYE': self.ua.global_config['sip_tm'].cancelTransaction(self.ua.tr) self.ua.global_config['sip_tm'].sendResponse(req.genResponse(200, 'OK')) #print 'BYE received in the Updating state, going to the Disconnected state' self.ua.equeue.append(CCEventDisconnect(rtime = req.rtime)) if self.ua.credit_timer != None: self.ua.credit_timer.cancel() self.ua.credit_timer = None if self.ua.warn_timer != None: self.ua.warn_timer.cancel() self.ua.warn_timer = None return (UaStateDisconnected, self.ua.disc_cbs, req.rtime) #print 'wrong request %s in the state Updating' % req.getMethod() return None def recvResponse(self, resp): body = resp.getBody() code, reason = resp.getSCode() scode = (code, reason, body) if code < 200: self.ua.equeue.append(CCEventRing(scode, rtime = resp.rtime)) return None if code >= 200 and code < 300: event = CCEventConnect(scode, rtime = resp.rtime) if body != None: if self.ua.on_remote_sdp_change != None: self.ua.on_remote_sdp_change(body, lambda x: self.ua.delayed_remote_sdp_update(event, x)) return (UaStateConnected,) else: self.ua.rSDP = body.getCopy() else: self.ua.rSDP = None self.ua.equeue.append(event) return (UaStateConnected,) if code in (301, 302) and resp.countHFs('contact') > 0: scode = (code, reason, body, resp.getHFBody('contact').getUrl().getCopy()) self.ua.equeqe.append(CCEventRedirect(scode, rtime = resp.rtime)) else: self.ua.equeue.append(CCEventFail(scode, rtime = resp.rtime)) return (UaStateConnected,) def recvEvent(self, event): if isinstance(event, CCEventDisconnect) or isinstance(event, CCEventFail) or isinstance(event, CCEventRedirect): self.ua.global_config['sip_tm'].cancelTransaction(self.ua.tr) req = self.ua.genRequest('BYE') self.ua.lCSeq += 1 self.ua.global_config['sip_tm'].newTransaction(req) if self.ua.credit_timer != None: self.ua.credit_timer.cancel() self.ua.credit_timer = None if self.ua.warn_timer != None: self.ua.warn_timer.cancel() self.ua.warn_timer = None return (UaStateDisconnected, self.ua.disc_cbs, event.rtime) #print 'wrong event %s in the Updating state' % event return None if not globals().has_key('UaStateConnected'): from UaStateConnected import UaStateConnected if not globals().has_key('UaStateDisconnected'): from UaStateDisconnected import UaStateDisconnected To quote RFC3261: If the response for a request within a dialog is a 481 (Call/Transaction Does Not Exist) or a 408 (Request Timeout), the UAC SHOULD terminate the dialog. A UAC SHOULD also terminate a dialog if no response at all is received for the request (the client transaction would inform the TU about the timeout.) Instead of relying on originating UA to DTRT, tear down session by ourselves upon receiving 408 or 481 in response to re-INVITE. # Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved. # # This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA. # # SIPPY 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. # # For a license to use the SIPPY software under conditions # other than those described here, or to purchase support for this # software, please contact Sippy Software, Inc. by e-mail at the # following addresses: sales@sippysoft.com. # # SIPPY 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. # # $Id: UacStateUpdating.py,v 1.5 2008/11/14 06:36:23 sobomax Exp $ from UaStateGeneric import UaStateGeneric from CCEvents import CCEventDisconnect, CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect class UacStateUpdating(UaStateGeneric): sname = 'Updating(UAC)' triedauth = False connected = True def recvRequest(self, req): if req.getMethod() == 'INVITE': self.ua.global_config['sip_tm'].sendResponse(req.genResponse(491, 'Request Pending')) return None elif req.getMethod() == 'BYE': self.ua.global_config['sip_tm'].cancelTransaction(self.ua.tr) self.ua.global_config['sip_tm'].sendResponse(req.genResponse(200, 'OK')) #print 'BYE received in the Updating state, going to the Disconnected state' self.ua.equeue.append(CCEventDisconnect(rtime = req.rtime)) if self.ua.credit_timer != None: self.ua.credit_timer.cancel() self.ua.credit_timer = None if self.ua.warn_timer != None: self.ua.warn_timer.cancel() self.ua.warn_timer = None return (UaStateDisconnected, self.ua.disc_cbs, req.rtime) #print 'wrong request %s in the state Updating' % req.getMethod() return None def recvResponse(self, resp): body = resp.getBody() code, reason = resp.getSCode() scode = (code, reason, body) if code < 200: self.ua.equeue.append(CCEventRing(scode, rtime = resp.rtime)) return None if code >= 200 and code < 300: event = CCEventConnect(scode, rtime = resp.rtime) if body != None: if self.ua.on_remote_sdp_change != None: self.ua.on_remote_sdp_change(body, lambda x: self.ua.delayed_remote_sdp_update(event, x)) return (UaStateConnected,) else: self.ua.rSDP = body.getCopy() else: self.ua.rSDP = None self.ua.equeue.append(event) return (UaStateConnected,) if code in (301, 302) and resp.countHFs('contact') > 0: scode = (code, reason, body, resp.getHFBody('contact').getUrl().getCopy()) self.ua.equeqe.append(CCEventRedirect(scode, rtime = resp.rtime)) elif code in (408, 481): # If the response for a request within a dialog is a 481 # (Call/Transaction Does Not Exist) or a 408 (Request Timeout), the UAC # SHOULD terminate the dialog. A UAC SHOULD also terminate a dialog if # no response at all is received for the request (the client # transaction would inform the TU about the timeout.) self.ua.equeue.append(CCEventDisconnect(rtime = resp.rtime)) self.ua.cancelCreditTimer() self.ua.disconnect_ts_assert() self.ua.disconnect_ts = resp.rtime return (UaStateDisconnected, self.ua.disc_cbs, resp.rtime) else: self.ua.equeue.append(CCEventFail(scode, rtime = resp.rtime)) return (UaStateConnected,) def recvEvent(self, event): if isinstance(event, CCEventDisconnect) or isinstance(event, CCEventFail) or isinstance(event, CCEventRedirect): self.ua.global_config['sip_tm'].cancelTransaction(self.ua.tr) req = self.ua.genRequest('BYE') self.ua.lCSeq += 1 self.ua.global_config['sip_tm'].newTransaction(req) if self.ua.credit_timer != None: self.ua.credit_timer.cancel() self.ua.credit_timer = None if self.ua.warn_timer != None: self.ua.warn_timer.cancel() self.ua.warn_timer = None return (UaStateDisconnected, self.ua.disc_cbs, event.rtime) #print 'wrong event %s in the Updating state' % event return None if not globals().has_key('UaStateConnected'): from UaStateConnected import UaStateConnected if not globals().has_key('UaStateDisconnected'): from UaStateDisconnected import UaStateDisconnected
# Copyright 2015-2018 Capital One Services, LLC # # 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 __future__ import absolute_import, division, print_function, unicode_literals from .azure_common import BaseTest, arm_template from mock import patch from azure.mgmt.resource.policy.models import PolicyDefinition class PolicyCompliance(BaseTest): def test_policy_compliance_schema_validate(self): with self.sign_out_patch(): p = self.load_policy({ 'name': 'test-policy-compliance', 'resource': 'azure.vm', 'filters': [ {'type': 'policy-compliant', 'compliant': True} ] }, validate=True) self.assertTrue(p) @arm_template('vm.json') @patch("azure.mgmt.policyinsights.operations.policy_states_operations.PolicyStatesOperations." "list_query_results_for_subscription") def test_find_by_name(self, policy_mock): policy_mock.return_value.value = [] p = self.load_policy({ 'name': 'test-azure-vm', 'resource': 'azure.vm', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'cctestvm'}, {'type': 'policy-compliant', 'compliant': True}] }) resources = p.run() self.assertEqual(len(resources), 1) p = self.load_policy({ 'name': 'test-azure-vm', 'resource': 'azure.vm', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'cctestvm'}, {'type': 'policy-compliant', 'compliant': False}] }) resources = p.run() self.assertEqual(len(resources), 0) @arm_template('emptyrg.json') @patch("azure.mgmt.policyinsights.operations.policy_states_operations.PolicyStatesOperations." "list_query_results_for_subscription") @patch("azure.mgmt.resource.policy.PolicyClient") def test_find_by_name_definition(self, client_mock, policy_mock): policy_mock.return_value.value = [] client_mock.policy_definitions.list.return_value = [PolicyDefinition(display_name='TEST')] p = self.load_policy({ 'name': 'test-azure-vm', 'resource': 'azure.vm', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'cctestvm'}, {'type': 'policy-compliant', 'definitions': ['TEST'], 'compliant': True}] }) resources = p.run() self.assertEqual(len(resources), 1) p = self.load_policy({ 'name': 'test-azure-vm', 'resource': 'azure.vm', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'cctestvm'}, {'type': 'policy-compliant', 'definitions': ['TEST'], 'compliant': False}] }) resources = p.run() self.assertEqual(len(resources), 0) ci - azure fix tests to work around sdk breaking change (#5195) # Copyright 2015-2018 Capital One Services, LLC # # 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 __future__ import absolute_import, division, print_function, unicode_literals from .azure_common import BaseTest, arm_template from mock import patch from azure.mgmt.resource.policy.models import PolicyDefinition class PolicyCompliance(BaseTest): def test_policy_compliance_schema_validate(self): with self.sign_out_patch(): p = self.load_policy({ 'name': 'test-policy-compliance', 'resource': 'azure.vm', 'filters': [ {'type': 'policy-compliant', 'compliant': True} ] }, validate=True) self.assertTrue(p) @arm_template('vm.json') @patch("azure.mgmt.policyinsights.operations.PolicyStatesOperations." "list_query_results_for_subscription") def test_find_by_name(self, policy_mock): policy_mock.return_value.value = [] p = self.load_policy({ 'name': 'test-azure-vm', 'resource': 'azure.vm', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'cctestvm'}, {'type': 'policy-compliant', 'compliant': True}] }) resources = p.run() self.assertEqual(len(resources), 1) p = self.load_policy({ 'name': 'test-azure-vm', 'resource': 'azure.vm', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'cctestvm'}, {'type': 'policy-compliant', 'compliant': False}] }) resources = p.run() self.assertEqual(len(resources), 0) @arm_template('emptyrg.json') @patch("azure.mgmt.policyinsights.operations.PolicyStatesOperations." "list_query_results_for_subscription") @patch("azure.mgmt.resource.policy.PolicyClient") def test_find_by_name_definition(self, client_mock, policy_mock): policy_mock.return_value.value = [] client_mock.policy_definitions.list.return_value = [PolicyDefinition(display_name='TEST')] p = self.load_policy({ 'name': 'test-azure-vm', 'resource': 'azure.vm', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'cctestvm'}, {'type': 'policy-compliant', 'definitions': ['TEST'], 'compliant': True}] }) resources = p.run() self.assertEqual(len(resources), 1) p = self.load_policy({ 'name': 'test-azure-vm', 'resource': 'azure.vm', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'cctestvm'}, {'type': 'policy-compliant', 'definitions': ['TEST'], 'compliant': False}] }) resources = p.run() self.assertEqual(len(resources), 0)
from .base import * # NOQA import sys import logging.config # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATES[0]['OPTIONS'].update({'debug': True}) # Turn off debug while imported by Celery with a workaround # See http://stackoverflow.com/a/4806384 #if "celery" in sys.argv[0]: # DEBUG = False ALLOWED_HOSTS = ['*'] # Django Debug Toolbar INSTALLED_APPS += ( 'debug_toolbar',) # Additional middleware introduced by debug toolbar MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware',) # Show emails to console in DEBUG mode EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Show thumbnail generation errors THUMBNAIL_DEBUG = True # Allow internal IPs for debugging INTERNAL_IPS = ['127.0.0.1'] # Log everything to the logs directory at the top LOGFILE_ROOT = join(dirname(BASE_ROOT), 'logs') # Reset logging # (see http://www.caktusgroup.com/blog/2015/01/27/Django-Logging-Configuration-logging_config-default-settings-logger/) LOGGING_CONFIG = None LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(pathname)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'django_log_file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': join(LOGFILE_ROOT, 'django.log'), 'formatter': 'verbose' }, 'proj_log_file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'encoding': 'utf-8', 'filename': join(LOGFILE_ROOT, 'project.log'), 'formatter': 'verbose' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'loggers': { 'django': { 'handlers': ['django_log_file'], 'propagate': True, 'level': 'DEBUG', }, 'project': { 'handlers': ['proj_log_file'], 'level': 'DEBUG', }, } } logging.config.dictConfig(LOGGING) TEST_RUNNER = 'colegio.settings.testing.UseDBTestRunner' IS_TESTING = True IS_MIGRATE = True #STATIC_ROOT = '/home/ubuntu/colegio/src/' IS_TESTING = False from .base import * # NOQA import sys import logging.config # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATES[0]['OPTIONS'].update({'debug': True}) # Turn off debug while imported by Celery with a workaround # See http://stackoverflow.com/a/4806384 #if "celery" in sys.argv[0]: # DEBUG = False ALLOWED_HOSTS = ['*'] # Django Debug Toolbar INSTALLED_APPS += ( 'debug_toolbar',) # Additional middleware introduced by debug toolbar MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware',) # Show emails to console in DEBUG mode EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Show thumbnail generation errors THUMBNAIL_DEBUG = True # Allow internal IPs for debugging INTERNAL_IPS = ['127.0.0.1'] # Log everything to the logs directory at the top LOGFILE_ROOT = join(dirname(BASE_ROOT), 'logs') # Reset logging # (see http://www.caktusgroup.com/blog/2015/01/27/Django-Logging-Configuration-logging_config-default-settings-logger/) LOGGING_CONFIG = None LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(pathname)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'django_log_file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': join(LOGFILE_ROOT, 'django.log'), 'formatter': 'verbose' }, 'proj_log_file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'encoding': 'utf-8', 'filename': join(LOGFILE_ROOT, 'project.log'), 'formatter': 'verbose' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'loggers': { 'django': { 'handlers': ['django_log_file'], 'propagate': True, 'level': 'DEBUG', }, 'project': { 'handlers': ['proj_log_file'], 'level': 'DEBUG', }, } } logging.config.dictConfig(LOGGING) TEST_RUNNER = 'colegio.settings.testing.UseDBTestRunner' IS_TESTING = False IS_MIGRATE = True STATIC_ROOT = '/home/ubuntu/colegio/src/'
# coding=utf-8 """ This module represents OctoPrint's settings management. Within this module the default settings for the core application are defined and the instance of the :class:`Settings` is held, which offers getter and setter methods for the raw configuration values as well as various convenience methods to access the paths to base folders of various types and the configuration file itself. .. autodata:: default_settings :annotation: = dict(...) .. autodata:: valid_boolean_trues .. autofunction:: settings .. autoclass:: Settings :members: :undoc-members: """ from __future__ import absolute_import __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import sys import os import yaml import logging import re import uuid _APPNAME = "OctoPrint" _instance = None def settings(init=False, basedir=None, configfile=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.settings.Settings` singleton. Arguments: init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not (False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError` will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to False. basedir (str): Path of the base directoy for all of OctoPrint's settings, log files, uploads etc. If not set the default will be used: ``~/.octoprint`` on Linux, ``%APPDATA%/OctoPrint`` on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS. configfile (str): Path of the configuration file (``config.yaml``) to work on. If not set the default will be used: ``<basedir>/config.yaml`` for ``basedir`` as defined above. Returns: Settings: The fully initialized :class:`Settings` instance. Raises: ValueError: ``init`` is True but settings are already initialized or vice versa. """ global _instance if _instance is not None: if init: raise ValueError("Settings Manager already initialized") else: if init: _instance = Settings(configfile=configfile, basedir=basedir) else: raise ValueError("Settings not initialized yet") return _instance default_settings = { "serial": { "port": None, "baudrate": None, "autoconnect": False, "log": False, "timeout": { "detection": 0.5, "connection": 10, "communication": 30, "temperature": 5, "sdStatus": 1 }, "additionalPorts": [], "longRunningCommands": ["G4", "G28", "G29", "G30", "G32"] }, "server": { "host": "0.0.0.0", "port": 5000, "firstRun": True, "secretKey": None, "reverseProxy": { "prefixHeader": "X-Script-Name", "schemeHeader": "X-Scheme", "hostHeader": "X-Forwarded-Host", "prefixFallback": "", "schemeFallback": "", "hostFallback": "" }, "uploads": { "maxSize": 1 * 1024 * 1024 * 1024, # 1GB "nameSuffix": "name", "pathSuffix": "path" }, "maxSize": 100 * 1024, # 100 KB "commands": { "systemShutdownCommand": None, "systemRestartCommand": None, "serverRestartCommand": None } }, "webcam": { "stream": None, "snapshot": None, "ffmpeg": None, "ffmpegThreads": 1, "bitrate": "5000k", "watermark": True, "flipH": False, "flipV": False, "rotate90" : False, "timelapse": { "type": "off", "options": {}, "postRoll": 0, "fps": 25 } }, "gcodeViewer": { "enabled": True, "mobileSizeThreshold": 2 * 1024 * 1024, # 2MB "sizeThreshold": 20 * 1024 * 1024, # 20MB }, "gcodeAnalysis": { "maxExtruders": 10 }, "feature": { "temperatureGraph": True, "waitForStartOnConnect": False, "alwaysSendChecksum": False, "sendChecksumWithUnknownCommands": False, "unknownCommandsNeedAck": False, "sdSupport": True, "sdAlwaysAvailable": False, "swallowOkAfterResend": True, "repetierTargetTemp": False, "externalHeatupDetection": True, "supportWait": True, "keyboardControl": True, "pollWatched": False, "ignoreIdenticalResends": False, "identicalResendsCountdown": 7 }, "folder": { "uploads": None, "timelapse": None, "timelapse_tmp": None, "logs": None, "virtualSd": None, "watched": None, "plugins": None, "slicingProfiles": None, "printerProfiles": None, "scripts": None, "translations": None, "generated": None, "data": None }, "temperature": { "profiles": [ {"name": "ABS", "extruder" : 210, "bed" : 100 }, {"name": "PLA", "extruder" : 180, "bed" : 60 } ], "cutoff": 30 }, "printerProfiles": { "default": None, "defaultProfile": {} }, "printerParameters": { "pauseTriggers": [], "defaultExtrusionLength": 5 }, "appearance": { "name": "", "color": "default", "colorTransparent": False, "defaultLanguage": "_default", "components": { "order": { "navbar": ["settings", "systemmenu", "login"], "sidebar": ["connection", "state", "files"], "tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"], "settings": [ "section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts", "section_features", "features", "webcam", "accesscontrol", "api", "section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate" ], "usersettings": ["access", "interface"], "generic": [] }, "disabled": { "navbar": [], "sidebar": [], "tab": [], "settings": [], "usersettings": [], "generic": [] } } }, "controls": [], "system": { "actions": [] }, "accessControl": { "enabled": True, "salt": None, "userManager": "octoprint.users.FilebasedUserManager", "userfile": None, "autologinLocal": False, "localNetworks": ["127.0.0.0/8"], "autologinAs": None }, "slicing": { "enabled": True, "defaultSlicer": "cura", "defaultProfiles": None }, "events": { "enabled": True, "subscriptions": [] }, "api": { "enabled": True, "key": None, "allowCrossOrigin": False, "apps": {} }, "terminalFilters": [ { "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok (B|T\d*):)" }, { "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" } ], "plugins": { "_disabled": [] }, "scripts": { "gcode": { "afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\nM140 S0\n\n;disable fan\nM106 S0", "snippets": { "disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}" } } }, "devel": { "stylesheet": "css", "cache": { "enabled": True }, "webassets": { "minify": False, "bundle": True, "clean_on_startup": True }, "virtualPrinter": { "enabled": False, "okAfterResend": False, "forceChecksum": False, "okWithLinenumber": False, "numExtruders": 1, "includeCurrentToolInTemps": True, "movementSpeed": { "x": 6000, "y": 6000, "z": 200, "e": 300 }, "hasBed": True, "repetierStyleTargetTemperature": False, "repetierStyleResends": False, "okBeforeCommandOutput": False, "smoothieTemperatureReporting": False, "extendedSdFileList": False, "throttle": 0.01, "waitOnLongMoves": False, "rxBuffer": 64, "txBuffer": 40, "commandBuffer": 4, "sendWait": True, "waitInterval": 1.0 } } } """The default settings of the core application.""" valid_boolean_trues = [True, "true", "yes", "y", "1"] """ Values that are considered to be equivalent to the boolean ``True`` value, used for type conversion in various places.""" class Settings(object): """ The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings directory, loading the configuration from ``config.yaml``, persisting changes to disk etc and provides access methods for getting and setting specific values from the overall settings structure via paths. A general word on the concept of paths, since they play an important role in OctoPrint's settings management. A path is basically a list or tuple consisting of keys to follow down into the settings (which are basically like a ``dict``) in order to set or retrieve a specific value (or more than one). For example, for a settings structure like the following:: serial: port: "/dev/ttyACM0" baudrate: 250000 timeouts: communication: 20.0 temperature: 5.0 sdStatus: 1.0 connection: 10.0 server: host: "0.0.0.0" port: 5000 the following paths could be used: ========================================== ============================================================================ Path Value ========================================== ============================================================================ ``["serial", "port"]`` :: "/dev/ttyACM0" ``["serial", "timeout"]`` :: communication: 20.0 temperature: 5.0 sdStatus: 1.0 connection: 10.0 ``["serial", "timeout", "temperature"]`` :: 5.0 ``["server", "port"]`` :: 5000 ========================================== ============================================================================ However, these would be invalid paths: ``["key"]``, ``["serial", "port", "value"]``, ``["server", "host", 3]``. """ def __init__(self, configfile=None, basedir=None): self._logger = logging.getLogger(__name__) self._basedir = None self._config = None self._dirty = False self._mtime = None self._get_preprocessors = dict( controls=self._process_custom_controls ) self._set_preprocessors = dict() self._init_basedir(basedir) if configfile is not None: self._configfile = configfile else: self._configfile = os.path.join(self._basedir, "config.yaml") self.load(migrate=True) if self.get(["api", "key"]) is None: self.set(["api", "key"], ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)) self.save(force=True) self._script_env = self._init_script_templating() def _init_basedir(self, basedir): if basedir is not None: self._basedir = basedir else: self._basedir = _default_basedir(_APPNAME) if not os.path.isdir(self._basedir): os.makedirs(self._basedir) def _get_default_folder(self, type): folder = default_settings["folder"][type] if folder is None: folder = os.path.join(self._basedir, type.replace("_", os.path.sep)) return folder def _init_script_templating(self): from jinja2 import Environment, BaseLoader, FileSystemLoader, ChoiceLoader, TemplateNotFound from jinja2.nodes import Include, Const from jinja2.ext import Extension class SnippetExtension(Extension): tags = {"snippet"} fields = Include.fields def parse(self, parser): node = parser.parse_include() if not node.template.value.startswith("/"): node.template.value = "snippets/" + node.template.value return node class SettingsScriptLoader(BaseLoader): def __init__(self, s): self._settings = s def get_source(self, environment, template): parts = template.split("/") if not len(parts): raise TemplateNotFound(template) script = self._settings.get(["scripts"], merged=True) for part in parts: if isinstance(script, dict) and part in script: script = script[part] else: raise TemplateNotFound(template) source = script if source is None: raise TemplateNotFound(template) mtime = self._settings._mtime return source, None, lambda: mtime == self._settings.last_modified def list_templates(self): scripts = self._settings.get(["scripts"], merged=True) return self._get_templates(scripts) def _get_templates(self, scripts): templates = [] for key in scripts: if isinstance(scripts[key], dict): templates += map(lambda x: key + "/" + x, self._get_templates(scripts[key])) elif isinstance(scripts[key], basestring): templates.append(key) return templates class SelectLoader(BaseLoader): def __init__(self, default, mapping, sep=":"): self._default = default self._mapping = mapping self._sep = sep def get_source(self, environment, template): if self._sep in template: prefix, name = template.split(self._sep, 1) if not prefix in self._mapping: raise TemplateNotFound(template) return self._mapping[prefix].get_source(environment, name) return self._default.get_source(environment, template) def list_templates(self): return self._default.list_templates() class RelEnvironment(Environment): def __init__(self, prefix_sep=":", *args, **kwargs): Environment.__init__(self, *args, **kwargs) self._prefix_sep = prefix_sep def join_path(self, template, parent): prefix, name = self._split_prefix(template) if name.startswith("/"): return self._join_prefix(prefix, name[1:]) else: _, parent_name = self._split_prefix(parent) parent_base = parent_name.split("/")[:-1] return self._join_prefix(prefix, "/".join(parent_base) + "/" + name) def _split_prefix(self, template): if self._prefix_sep in template: return template.split(self._prefix_sep, 1) else: return "", template def _join_prefix(self, prefix, template): if len(prefix): return prefix + self._prefix_sep + template else: return template file_system_loader = FileSystemLoader(self.getBaseFolder("scripts")) settings_loader = SettingsScriptLoader(self) choice_loader = ChoiceLoader([file_system_loader, settings_loader]) select_loader = SelectLoader(choice_loader, dict(bundled=settings_loader, file=file_system_loader)) return RelEnvironment(loader=select_loader, extensions=[SnippetExtension]) def _get_script_template(self, script_type, name, source=False): from jinja2 import TemplateNotFound template_name = script_type + "/" + name try: if source: template_name, _, _ = self._script_env.loader.get_source(self._script_env, template_name) return template_name else: return self._script_env.get_template(template_name) except TemplateNotFound: return None except: self._logger.exception("Exception while trying to resolve template {template_name}".format(**locals())) return None def _get_scripts(self, script_type): return self._script_env.list_templates(filter_func=lambda x: x.startswith(script_type+"/")) def _process_custom_controls(self, controls): def process_control(c): # shallow copy result = dict(c) if "regex" in result and "template" in result: # if it's a template matcher, we need to add a key to associate with the matcher output import hashlib key_hash = hashlib.md5() key_hash.update(result["regex"]) result["key"] = key_hash.hexdigest() template_key_hash = hashlib.md5() template_key_hash.update(result["template"]) result["template_key"] = template_key_hash.hexdigest() elif "children" in result: # if it has children we need to process them recursively result["children"] = map(process_control, [child for child in result["children"] if child is not None]) return result return map(process_control, controls) @property def effective(self): import octoprint.util return octoprint.util.dict_merge(default_settings, self._config) @property def effective_yaml(self): import yaml return yaml.safe_dump(self.effective) #~~ load and save def load(self, migrate=False): if os.path.exists(self._configfile) and os.path.isfile(self._configfile): with open(self._configfile, "r") as f: self._config = yaml.safe_load(f) self._mtime = self.last_modified # changed from else to handle cases where the file exists, but is empty / 0 bytes if not self._config: self._config = {} if migrate: self._migrate_config() def _migrate_config(self): dirty = False migrators = ( self._migrate_event_config, self._migrate_reverse_proxy_config, self._migrate_printer_parameters, self._migrate_gcode_scripts ) for migrate in migrators: dirty = migrate() or dirty if dirty: self.save(force=True) def _migrate_gcode_scripts(self): """ Migrates an old development version of gcode scripts to the new template based format. """ dirty = False if "scripts" in self._config: if "gcode" in self._config["scripts"]: if "templates" in self._config["scripts"]["gcode"]: del self._config["scripts"]["gcode"]["templates"] replacements = dict( disable_steppers="M84", disable_hotends="{% snippet 'disable_hotends' %}", disable_bed="M140 S0", disable_fan="M106 S0" ) for name, script in self._config["scripts"]["gcode"].items(): self.saveScript("gcode", name, script.format(**replacements)) del self._config["scripts"] dirty = True return dirty def _migrate_printer_parameters(self): """ Migrates the old "printer > parameters" data structure to the new printer profile mechanism. """ default_profile = self._config["printerProfiles"]["defaultProfile"] if "printerProfiles" in self._config and "defaultProfile" in self._config["printerProfiles"] else dict() dirty = False if "printerParameters" in self._config: printer_parameters = self._config["printerParameters"] if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters: default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict()) if "movementSpeed" in printer_parameters: for axis in ("x", "y", "z", "e"): if axis in printer_parameters["movementSpeed"]: default_profile["axes"][axis]["speed"] = printer_parameters["movementSpeed"][axis] del self._config["printerParameters"]["movementSpeed"] if "invertedAxes" in printer_parameters: for axis in ("x", "y", "z", "e"): if axis in printer_parameters["invertedAxes"]: default_profile["axes"][axis]["inverted"] = True del self._config["printerParameters"]["invertedAxes"] if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters: if not "extruder" in default_profile: default_profile["extruder"] = dict() if "numExtruders" in printer_parameters: default_profile["extruder"]["count"] = printer_parameters["numExtruders"] del self._config["printerParameters"]["numExtruders"] if "extruderOffsets" in printer_parameters: extruder_offsets = [] for offset in printer_parameters["extruderOffsets"]: if "x" in offset and "y" in offset: extruder_offsets.append((offset["x"], offset["y"])) default_profile["extruder"]["offsets"] = extruder_offsets del self._config["printerParameters"]["extruderOffsets"] if "bedDimensions" in printer_parameters: bed_dimensions = printer_parameters["bedDimensions"] if not "volume" in default_profile: default_profile["volume"] = dict() if "circular" in bed_dimensions and "r" in bed_dimensions and bed_dimensions["circular"]: default_profile["volume"]["formFactor"] = "circular" default_profile["volume"]["width"] = 2 * bed_dimensions["r"] default_profile["volume"]["depth"] = default_profile["volume"]["width"] elif "x" in bed_dimensions or "y" in bed_dimensions: default_profile["volume"]["formFactor"] = "rectangular" if "x" in bed_dimensions: default_profile["volume"]["width"] = bed_dimensions["x"] if "y" in bed_dimensions: default_profile["volume"]["depth"] = bed_dimensions["y"] del self._config["printerParameters"]["bedDimensions"] dirty = True if dirty: if not "printerProfiles" in self._config: self._config["printerProfiles"] = dict() self._config["printerProfiles"]["defaultProfile"] = default_profile return dirty def _migrate_reverse_proxy_config(self): """ Migrates the old "server > baseUrl" and "server > scheme" configuration entries to "server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback". """ if "server" in self._config.keys() and ("baseUrl" in self._config["server"] or "scheme" in self._config["server"]): prefix = "" if "baseUrl" in self._config["server"]: prefix = self._config["server"]["baseUrl"] del self._config["server"]["baseUrl"] scheme = "" if "scheme" in self._config["server"]: scheme = self._config["server"]["scheme"] del self._config["server"]["scheme"] if not "reverseProxy" in self._config["server"] or not isinstance(self._config["server"]["reverseProxy"], dict): self._config["server"]["reverseProxy"] = dict() if prefix: self._config["server"]["reverseProxy"]["prefixFallback"] = prefix if scheme: self._config["server"]["reverseProxy"]["schemeFallback"] = scheme self._logger.info("Migrated reverse proxy configuration to new structure") return True else: return False def _migrate_event_config(self): """ Migrates the old event configuration format of type "events > gcodeCommandTrigger" and "event > systemCommandTrigger" to the new events format. """ if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]): self._logger.info("Migrating config (event subscriptions)...") # migrate event hooks to new format placeholderRe = re.compile("%\((.*?)\)s") eventNameReplacements = { "ClientOpen": "ClientOpened", "TransferStart": "TransferStarted" } payloadDataReplacements = { "Upload": {"data": "{file}", "filename": "{file}"}, "Connected": {"data": "{port} at {baudrate} baud"}, "FileSelected": {"data": "{file}", "filename": "{file}"}, "TransferStarted": {"data": "{remote}", "filename": "{remote}"}, "TransferDone": {"data": "{remote}", "filename": "{remote}"}, "ZChange": {"data": "{new}"}, "CaptureStart": {"data": "{file}"}, "CaptureDone": {"data": "{file}"}, "MovieDone": {"data": "{movie}", "filename": "{gcode}"}, "Error": {"data": "{error}"}, "PrintStarted": {"data": "{file}", "filename": "{file}"}, "PrintDone": {"data": "{file}", "filename": "{file}"}, } def migrateEventHook(event, command): # migrate placeholders command = placeholderRe.sub("{__\\1}", command) # migrate event names if event in eventNameReplacements: event = eventNameReplacements["event"] # migrate payloads to more specific placeholders if event in payloadDataReplacements: for key in payloadDataReplacements[event]: command = command.replace("{__%s}" % key, payloadDataReplacements[event][key]) # return processed tuple return event, command disableSystemCommands = False if "systemCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["systemCommandTrigger"]: disableSystemCommands = not self._config["events"]["systemCommandTrigger"]["enabled"] disableGcodeCommands = False if "gcodeCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["gcodeCommandTrigger"]: disableGcodeCommands = not self._config["events"]["gcodeCommandTrigger"]["enabled"] disableAllCommands = disableSystemCommands and disableGcodeCommands newEvents = { "enabled": not disableAllCommands, "subscriptions": [] } if "systemCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["systemCommandTrigger"]: for trigger in self._config["events"]["systemCommandTrigger"]["subscriptions"]: if not ("event" in trigger and "command" in trigger): continue newTrigger = {"type": "system"} if disableSystemCommands and not disableAllCommands: newTrigger["enabled"] = False newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"]) newEvents["subscriptions"].append(newTrigger) if "gcodeCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["gcodeCommandTrigger"]: for trigger in self._config["events"]["gcodeCommandTrigger"]["subscriptions"]: if not ("event" in trigger and "command" in trigger): continue newTrigger = {"type": "gcode"} if disableGcodeCommands and not disableAllCommands: newTrigger["enabled"] = False newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"]) newTrigger["command"] = newTrigger["command"].split(",") newEvents["subscriptions"].append(newTrigger) self._config["events"] = newEvents self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"])) return True else: return False def save(self, force=False): if not self._dirty and not force: return False from octoprint.util import atomic_write try: with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml") as configFile: yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True) self._dirty = False except: self._logger.exception("Error while saving config.yaml!") raise else: self.load() return True @property def last_modified(self): """ Returns: int: The last modification time of the configuration file. """ stat = os.stat(self._configfile) return stat.st_mtime #~~ getter def get(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True): import octoprint.util as util if len(path) == 0: return None if config is None: config = self._config if defaults is None: defaults = default_settings if preprocessors is None: preprocessors = self._get_preprocessors while len(path) > 1: key = path.pop(0) if key in config and key in defaults: config = config[key] defaults = defaults[key] elif incl_defaults and key in defaults: config = {} defaults = defaults[key] else: return None if preprocessors and isinstance(preprocessors, dict) and key in preprocessors: preprocessors = preprocessors[key] k = path.pop(0) if not isinstance(k, (list, tuple)): keys = [k] else: keys = k if asdict: results = {} else: results = [] for key in keys: if key in config: value = config[key] if merged and key in defaults: value = util.dict_merge(defaults[key], value) elif incl_defaults and key in defaults: value = defaults[key] else: value = None if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]): value = preprocessors[key](value) if asdict: results[key] = value else: results.append(value) if not isinstance(k, (list, tuple)): if asdict: return results.values().pop() else: return results.pop() else: return results def getInt(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True): value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults) if value is None: return None try: return int(value) except ValueError: self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path)) return None def getFloat(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True): value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults) if value is None: return None try: return float(value) except ValueError: self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path)) return None def getBoolean(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True): value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults) if value is None: return None if isinstance(value, bool): return value if isinstance(value, (int, float)): return value != 0 if isinstance(value, (str, unicode)): return value.lower() in valid_boolean_trues return value is not None def getBaseFolder(self, type, create=True): if type not in default_settings["folder"].keys() + ["base"]: return None if type == "base": return self._basedir folder = self.get(["folder", type]) if folder is None: folder = self._get_default_folder(type) if not os.path.isdir(folder): if create: os.makedirs(folder) else: raise IOError("No such folder: {folder}".format(folder=folder)) return folder def listScripts(self, script_type): return map(lambda x: x[len(script_type + "/"):], filter(lambda x: x.startswith(script_type + "/"), self._get_scripts(script_type))) def loadScript(self, script_type, name, context=None, source=False): if context is None: context = dict() context.update(dict(script=dict(type=script_type, name=name))) template = self._get_script_template(script_type, name, source=source) if template is None: return None if source: script = template else: try: script = template.render(**context) except: self._logger.exception("Exception while trying to render script {script_type}:{name}".format(**locals())) return None return script #~~ setter def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None): if len(path) == 0: return if self._mtime is not None and self.last_modified != self._mtime: self.load() if config is None: config = self._config if defaults is None: defaults = default_settings if preprocessors is None: preprocessors = self._set_preprocessors while len(path) > 1: key = path.pop(0) if key in config.keys() and key in defaults.keys(): config = config[key] defaults = defaults[key] elif key in defaults.keys(): config[key] = {} config = config[key] defaults = defaults[key] else: return if preprocessors and isinstance(preprocessors, dict) and key in preprocessors: preprocessors = preprocessors[key] key = path.pop(0) if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]): value = preprocessors[key](value) if not force and key in defaults and key in config and defaults[key] == value: del config[key] self._dirty = True elif force or (not key in config and defaults[key] != value) or (key in config and config[key] != value): if value is None and key in config: del config[key] else: config[key] = value self._dirty = True def setInt(self, path, value, force=False, defaults=None, config=None, preprocessors=None): if value is None: self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors) return try: intValue = int(value) except ValueError: self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path)) return self.set(path, intValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors) def setFloat(self, path, value, force=False, defaults=None, config=None, preprocessors=None): if value is None: self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors) return try: floatValue = float(value) except ValueError: self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path)) return self.set(path, floatValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors) def setBoolean(self, path, value, force=False, defaults=None, config=None, preprocessors=None): if value is None or isinstance(value, bool): self.set(path, value, config=config, force=force, defaults=defaults, preprocessors=preprocessors) elif value.lower() in valid_boolean_trues: self.set(path, True, config=config, force=force, defaults=defaults, preprocessors=preprocessors) else: self.set(path, False, config=config, force=force, defaults=defaults, preprocessors=preprocessors) def setBaseFolder(self, type, path, force=False): if type not in default_settings["folder"].keys(): return None currentPath = self.getBaseFolder(type) defaultPath = self._get_default_folder(type) if (path is None or path == defaultPath) and "folder" in self._config.keys() and type in self._config["folder"].keys(): del self._config["folder"][type] if not self._config["folder"]: del self._config["folder"] self._dirty = True elif (path != currentPath and path != defaultPath) or force: if not "folder" in self._config.keys(): self._config["folder"] = {} self._config["folder"][type] = path self._dirty = True def saveScript(self, script_type, name, script): script_folder = self.getBaseFolder("scripts") filename = os.path.realpath(os.path.join(script_folder, script_type, name)) if not filename.startswith(script_folder): # oops, jail break, that shouldn't happen raise ValueError("Invalid script path to save to: {filename} (from {script_type}:{name})".format(**locals())) path, _ = os.path.split(filename) if not os.path.exists(path): os.makedirs(path) with open(filename, "w+") as f: f.write(script) def _default_basedir(applicationName): # taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python if sys.platform == "darwin": from AppKit import NSSearchPathForDirectoriesInDomains # http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains # NSApplicationSupportDirectory = 14 # NSUserDomainMask = 1 # True for expanding the tilde into a fully qualified path return os.path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], applicationName) elif sys.platform == "win32": return os.path.join(os.environ["APPDATA"], applicationName) else: return os.path.expanduser(os.path.join("~", "." + applicationName.lower())) Allow deletion of a key from settings that is no longer in defaults (cherry picked from commit b04da70) # coding=utf-8 """ This module represents OctoPrint's settings management. Within this module the default settings for the core application are defined and the instance of the :class:`Settings` is held, which offers getter and setter methods for the raw configuration values as well as various convenience methods to access the paths to base folders of various types and the configuration file itself. .. autodata:: default_settings :annotation: = dict(...) .. autodata:: valid_boolean_trues .. autofunction:: settings .. autoclass:: Settings :members: :undoc-members: """ from __future__ import absolute_import __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import sys import os import yaml import logging import re import uuid _APPNAME = "OctoPrint" _instance = None def settings(init=False, basedir=None, configfile=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.settings.Settings` singleton. Arguments: init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not (False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError` will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to False. basedir (str): Path of the base directoy for all of OctoPrint's settings, log files, uploads etc. If not set the default will be used: ``~/.octoprint`` on Linux, ``%APPDATA%/OctoPrint`` on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS. configfile (str): Path of the configuration file (``config.yaml``) to work on. If not set the default will be used: ``<basedir>/config.yaml`` for ``basedir`` as defined above. Returns: Settings: The fully initialized :class:`Settings` instance. Raises: ValueError: ``init`` is True but settings are already initialized or vice versa. """ global _instance if _instance is not None: if init: raise ValueError("Settings Manager already initialized") else: if init: _instance = Settings(configfile=configfile, basedir=basedir) else: raise ValueError("Settings not initialized yet") return _instance default_settings = { "serial": { "port": None, "baudrate": None, "autoconnect": False, "log": False, "timeout": { "detection": 0.5, "connection": 10, "communication": 30, "temperature": 5, "sdStatus": 1 }, "additionalPorts": [], "longRunningCommands": ["G4", "G28", "G29", "G30", "G32"] }, "server": { "host": "0.0.0.0", "port": 5000, "firstRun": True, "secretKey": None, "reverseProxy": { "prefixHeader": "X-Script-Name", "schemeHeader": "X-Scheme", "hostHeader": "X-Forwarded-Host", "prefixFallback": "", "schemeFallback": "", "hostFallback": "" }, "uploads": { "maxSize": 1 * 1024 * 1024 * 1024, # 1GB "nameSuffix": "name", "pathSuffix": "path" }, "maxSize": 100 * 1024, # 100 KB "commands": { "systemShutdownCommand": None, "systemRestartCommand": None, "serverRestartCommand": None } }, "webcam": { "stream": None, "snapshot": None, "ffmpeg": None, "ffmpegThreads": 1, "bitrate": "5000k", "watermark": True, "flipH": False, "flipV": False, "rotate90" : False, "timelapse": { "type": "off", "options": {}, "postRoll": 0, "fps": 25 } }, "gcodeViewer": { "enabled": True, "mobileSizeThreshold": 2 * 1024 * 1024, # 2MB "sizeThreshold": 20 * 1024 * 1024, # 20MB }, "gcodeAnalysis": { "maxExtruders": 10 }, "feature": { "temperatureGraph": True, "waitForStartOnConnect": False, "alwaysSendChecksum": False, "sendChecksumWithUnknownCommands": False, "unknownCommandsNeedAck": False, "sdSupport": True, "sdAlwaysAvailable": False, "swallowOkAfterResend": True, "repetierTargetTemp": False, "externalHeatupDetection": True, "supportWait": True, "keyboardControl": True, "pollWatched": False, "ignoreIdenticalResends": False, "identicalResendsCountdown": 7 }, "folder": { "uploads": None, "timelapse": None, "timelapse_tmp": None, "logs": None, "virtualSd": None, "watched": None, "plugins": None, "slicingProfiles": None, "printerProfiles": None, "scripts": None, "translations": None, "generated": None, "data": None }, "temperature": { "profiles": [ {"name": "ABS", "extruder" : 210, "bed" : 100 }, {"name": "PLA", "extruder" : 180, "bed" : 60 } ], "cutoff": 30 }, "printerProfiles": { "default": None, "defaultProfile": {} }, "printerParameters": { "pauseTriggers": [], "defaultExtrusionLength": 5 }, "appearance": { "name": "", "color": "default", "colorTransparent": False, "defaultLanguage": "_default", "components": { "order": { "navbar": ["settings", "systemmenu", "login"], "sidebar": ["connection", "state", "files"], "tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"], "settings": [ "section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts", "section_features", "features", "webcam", "accesscontrol", "api", "section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate" ], "usersettings": ["access", "interface"], "generic": [] }, "disabled": { "navbar": [], "sidebar": [], "tab": [], "settings": [], "usersettings": [], "generic": [] } } }, "controls": [], "system": { "actions": [] }, "accessControl": { "enabled": True, "salt": None, "userManager": "octoprint.users.FilebasedUserManager", "userfile": None, "autologinLocal": False, "localNetworks": ["127.0.0.0/8"], "autologinAs": None }, "slicing": { "enabled": True, "defaultSlicer": "cura", "defaultProfiles": None }, "events": { "enabled": True, "subscriptions": [] }, "api": { "enabled": True, "key": None, "allowCrossOrigin": False, "apps": {} }, "terminalFilters": [ { "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok (B|T\d*):)" }, { "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" } ], "plugins": { "_disabled": [] }, "scripts": { "gcode": { "afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\nM140 S0\n\n;disable fan\nM106 S0", "snippets": { "disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}" } } }, "devel": { "stylesheet": "css", "cache": { "enabled": True }, "webassets": { "minify": False, "bundle": True, "clean_on_startup": True }, "virtualPrinter": { "enabled": False, "okAfterResend": False, "forceChecksum": False, "okWithLinenumber": False, "numExtruders": 1, "includeCurrentToolInTemps": True, "movementSpeed": { "x": 6000, "y": 6000, "z": 200, "e": 300 }, "hasBed": True, "repetierStyleTargetTemperature": False, "repetierStyleResends": False, "okBeforeCommandOutput": False, "smoothieTemperatureReporting": False, "extendedSdFileList": False, "throttle": 0.01, "waitOnLongMoves": False, "rxBuffer": 64, "txBuffer": 40, "commandBuffer": 4, "sendWait": True, "waitInterval": 1.0 } } } """The default settings of the core application.""" valid_boolean_trues = [True, "true", "yes", "y", "1"] """ Values that are considered to be equivalent to the boolean ``True`` value, used for type conversion in various places.""" class Settings(object): """ The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings directory, loading the configuration from ``config.yaml``, persisting changes to disk etc and provides access methods for getting and setting specific values from the overall settings structure via paths. A general word on the concept of paths, since they play an important role in OctoPrint's settings management. A path is basically a list or tuple consisting of keys to follow down into the settings (which are basically like a ``dict``) in order to set or retrieve a specific value (or more than one). For example, for a settings structure like the following:: serial: port: "/dev/ttyACM0" baudrate: 250000 timeouts: communication: 20.0 temperature: 5.0 sdStatus: 1.0 connection: 10.0 server: host: "0.0.0.0" port: 5000 the following paths could be used: ========================================== ============================================================================ Path Value ========================================== ============================================================================ ``["serial", "port"]`` :: "/dev/ttyACM0" ``["serial", "timeout"]`` :: communication: 20.0 temperature: 5.0 sdStatus: 1.0 connection: 10.0 ``["serial", "timeout", "temperature"]`` :: 5.0 ``["server", "port"]`` :: 5000 ========================================== ============================================================================ However, these would be invalid paths: ``["key"]``, ``["serial", "port", "value"]``, ``["server", "host", 3]``. """ def __init__(self, configfile=None, basedir=None): self._logger = logging.getLogger(__name__) self._basedir = None self._config = None self._dirty = False self._mtime = None self._get_preprocessors = dict( controls=self._process_custom_controls ) self._set_preprocessors = dict() self._init_basedir(basedir) if configfile is not None: self._configfile = configfile else: self._configfile = os.path.join(self._basedir, "config.yaml") self.load(migrate=True) if self.get(["api", "key"]) is None: self.set(["api", "key"], ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)) self.save(force=True) self._script_env = self._init_script_templating() def _init_basedir(self, basedir): if basedir is not None: self._basedir = basedir else: self._basedir = _default_basedir(_APPNAME) if not os.path.isdir(self._basedir): os.makedirs(self._basedir) def _get_default_folder(self, type): folder = default_settings["folder"][type] if folder is None: folder = os.path.join(self._basedir, type.replace("_", os.path.sep)) return folder def _init_script_templating(self): from jinja2 import Environment, BaseLoader, FileSystemLoader, ChoiceLoader, TemplateNotFound from jinja2.nodes import Include, Const from jinja2.ext import Extension class SnippetExtension(Extension): tags = {"snippet"} fields = Include.fields def parse(self, parser): node = parser.parse_include() if not node.template.value.startswith("/"): node.template.value = "snippets/" + node.template.value return node class SettingsScriptLoader(BaseLoader): def __init__(self, s): self._settings = s def get_source(self, environment, template): parts = template.split("/") if not len(parts): raise TemplateNotFound(template) script = self._settings.get(["scripts"], merged=True) for part in parts: if isinstance(script, dict) and part in script: script = script[part] else: raise TemplateNotFound(template) source = script if source is None: raise TemplateNotFound(template) mtime = self._settings._mtime return source, None, lambda: mtime == self._settings.last_modified def list_templates(self): scripts = self._settings.get(["scripts"], merged=True) return self._get_templates(scripts) def _get_templates(self, scripts): templates = [] for key in scripts: if isinstance(scripts[key], dict): templates += map(lambda x: key + "/" + x, self._get_templates(scripts[key])) elif isinstance(scripts[key], basestring): templates.append(key) return templates class SelectLoader(BaseLoader): def __init__(self, default, mapping, sep=":"): self._default = default self._mapping = mapping self._sep = sep def get_source(self, environment, template): if self._sep in template: prefix, name = template.split(self._sep, 1) if not prefix in self._mapping: raise TemplateNotFound(template) return self._mapping[prefix].get_source(environment, name) return self._default.get_source(environment, template) def list_templates(self): return self._default.list_templates() class RelEnvironment(Environment): def __init__(self, prefix_sep=":", *args, **kwargs): Environment.__init__(self, *args, **kwargs) self._prefix_sep = prefix_sep def join_path(self, template, parent): prefix, name = self._split_prefix(template) if name.startswith("/"): return self._join_prefix(prefix, name[1:]) else: _, parent_name = self._split_prefix(parent) parent_base = parent_name.split("/")[:-1] return self._join_prefix(prefix, "/".join(parent_base) + "/" + name) def _split_prefix(self, template): if self._prefix_sep in template: return template.split(self._prefix_sep, 1) else: return "", template def _join_prefix(self, prefix, template): if len(prefix): return prefix + self._prefix_sep + template else: return template file_system_loader = FileSystemLoader(self.getBaseFolder("scripts")) settings_loader = SettingsScriptLoader(self) choice_loader = ChoiceLoader([file_system_loader, settings_loader]) select_loader = SelectLoader(choice_loader, dict(bundled=settings_loader, file=file_system_loader)) return RelEnvironment(loader=select_loader, extensions=[SnippetExtension]) def _get_script_template(self, script_type, name, source=False): from jinja2 import TemplateNotFound template_name = script_type + "/" + name try: if source: template_name, _, _ = self._script_env.loader.get_source(self._script_env, template_name) return template_name else: return self._script_env.get_template(template_name) except TemplateNotFound: return None except: self._logger.exception("Exception while trying to resolve template {template_name}".format(**locals())) return None def _get_scripts(self, script_type): return self._script_env.list_templates(filter_func=lambda x: x.startswith(script_type+"/")) def _process_custom_controls(self, controls): def process_control(c): # shallow copy result = dict(c) if "regex" in result and "template" in result: # if it's a template matcher, we need to add a key to associate with the matcher output import hashlib key_hash = hashlib.md5() key_hash.update(result["regex"]) result["key"] = key_hash.hexdigest() template_key_hash = hashlib.md5() template_key_hash.update(result["template"]) result["template_key"] = template_key_hash.hexdigest() elif "children" in result: # if it has children we need to process them recursively result["children"] = map(process_control, [child for child in result["children"] if child is not None]) return result return map(process_control, controls) @property def effective(self): import octoprint.util return octoprint.util.dict_merge(default_settings, self._config) @property def effective_yaml(self): import yaml return yaml.safe_dump(self.effective) #~~ load and save def load(self, migrate=False): if os.path.exists(self._configfile) and os.path.isfile(self._configfile): with open(self._configfile, "r") as f: self._config = yaml.safe_load(f) self._mtime = self.last_modified # changed from else to handle cases where the file exists, but is empty / 0 bytes if not self._config: self._config = {} if migrate: self._migrate_config() def _migrate_config(self): dirty = False migrators = ( self._migrate_event_config, self._migrate_reverse_proxy_config, self._migrate_printer_parameters, self._migrate_gcode_scripts ) for migrate in migrators: dirty = migrate() or dirty if dirty: self.save(force=True) def _migrate_gcode_scripts(self): """ Migrates an old development version of gcode scripts to the new template based format. """ dirty = False if "scripts" in self._config: if "gcode" in self._config["scripts"]: if "templates" in self._config["scripts"]["gcode"]: del self._config["scripts"]["gcode"]["templates"] replacements = dict( disable_steppers="M84", disable_hotends="{% snippet 'disable_hotends' %}", disable_bed="M140 S0", disable_fan="M106 S0" ) for name, script in self._config["scripts"]["gcode"].items(): self.saveScript("gcode", name, script.format(**replacements)) del self._config["scripts"] dirty = True return dirty def _migrate_printer_parameters(self): """ Migrates the old "printer > parameters" data structure to the new printer profile mechanism. """ default_profile = self._config["printerProfiles"]["defaultProfile"] if "printerProfiles" in self._config and "defaultProfile" in self._config["printerProfiles"] else dict() dirty = False if "printerParameters" in self._config: printer_parameters = self._config["printerParameters"] if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters: default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict()) if "movementSpeed" in printer_parameters: for axis in ("x", "y", "z", "e"): if axis in printer_parameters["movementSpeed"]: default_profile["axes"][axis]["speed"] = printer_parameters["movementSpeed"][axis] del self._config["printerParameters"]["movementSpeed"] if "invertedAxes" in printer_parameters: for axis in ("x", "y", "z", "e"): if axis in printer_parameters["invertedAxes"]: default_profile["axes"][axis]["inverted"] = True del self._config["printerParameters"]["invertedAxes"] if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters: if not "extruder" in default_profile: default_profile["extruder"] = dict() if "numExtruders" in printer_parameters: default_profile["extruder"]["count"] = printer_parameters["numExtruders"] del self._config["printerParameters"]["numExtruders"] if "extruderOffsets" in printer_parameters: extruder_offsets = [] for offset in printer_parameters["extruderOffsets"]: if "x" in offset and "y" in offset: extruder_offsets.append((offset["x"], offset["y"])) default_profile["extruder"]["offsets"] = extruder_offsets del self._config["printerParameters"]["extruderOffsets"] if "bedDimensions" in printer_parameters: bed_dimensions = printer_parameters["bedDimensions"] if not "volume" in default_profile: default_profile["volume"] = dict() if "circular" in bed_dimensions and "r" in bed_dimensions and bed_dimensions["circular"]: default_profile["volume"]["formFactor"] = "circular" default_profile["volume"]["width"] = 2 * bed_dimensions["r"] default_profile["volume"]["depth"] = default_profile["volume"]["width"] elif "x" in bed_dimensions or "y" in bed_dimensions: default_profile["volume"]["formFactor"] = "rectangular" if "x" in bed_dimensions: default_profile["volume"]["width"] = bed_dimensions["x"] if "y" in bed_dimensions: default_profile["volume"]["depth"] = bed_dimensions["y"] del self._config["printerParameters"]["bedDimensions"] dirty = True if dirty: if not "printerProfiles" in self._config: self._config["printerProfiles"] = dict() self._config["printerProfiles"]["defaultProfile"] = default_profile return dirty def _migrate_reverse_proxy_config(self): """ Migrates the old "server > baseUrl" and "server > scheme" configuration entries to "server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback". """ if "server" in self._config.keys() and ("baseUrl" in self._config["server"] or "scheme" in self._config["server"]): prefix = "" if "baseUrl" in self._config["server"]: prefix = self._config["server"]["baseUrl"] del self._config["server"]["baseUrl"] scheme = "" if "scheme" in self._config["server"]: scheme = self._config["server"]["scheme"] del self._config["server"]["scheme"] if not "reverseProxy" in self._config["server"] or not isinstance(self._config["server"]["reverseProxy"], dict): self._config["server"]["reverseProxy"] = dict() if prefix: self._config["server"]["reverseProxy"]["prefixFallback"] = prefix if scheme: self._config["server"]["reverseProxy"]["schemeFallback"] = scheme self._logger.info("Migrated reverse proxy configuration to new structure") return True else: return False def _migrate_event_config(self): """ Migrates the old event configuration format of type "events > gcodeCommandTrigger" and "event > systemCommandTrigger" to the new events format. """ if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]): self._logger.info("Migrating config (event subscriptions)...") # migrate event hooks to new format placeholderRe = re.compile("%\((.*?)\)s") eventNameReplacements = { "ClientOpen": "ClientOpened", "TransferStart": "TransferStarted" } payloadDataReplacements = { "Upload": {"data": "{file}", "filename": "{file}"}, "Connected": {"data": "{port} at {baudrate} baud"}, "FileSelected": {"data": "{file}", "filename": "{file}"}, "TransferStarted": {"data": "{remote}", "filename": "{remote}"}, "TransferDone": {"data": "{remote}", "filename": "{remote}"}, "ZChange": {"data": "{new}"}, "CaptureStart": {"data": "{file}"}, "CaptureDone": {"data": "{file}"}, "MovieDone": {"data": "{movie}", "filename": "{gcode}"}, "Error": {"data": "{error}"}, "PrintStarted": {"data": "{file}", "filename": "{file}"}, "PrintDone": {"data": "{file}", "filename": "{file}"}, } def migrateEventHook(event, command): # migrate placeholders command = placeholderRe.sub("{__\\1}", command) # migrate event names if event in eventNameReplacements: event = eventNameReplacements["event"] # migrate payloads to more specific placeholders if event in payloadDataReplacements: for key in payloadDataReplacements[event]: command = command.replace("{__%s}" % key, payloadDataReplacements[event][key]) # return processed tuple return event, command disableSystemCommands = False if "systemCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["systemCommandTrigger"]: disableSystemCommands = not self._config["events"]["systemCommandTrigger"]["enabled"] disableGcodeCommands = False if "gcodeCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["gcodeCommandTrigger"]: disableGcodeCommands = not self._config["events"]["gcodeCommandTrigger"]["enabled"] disableAllCommands = disableSystemCommands and disableGcodeCommands newEvents = { "enabled": not disableAllCommands, "subscriptions": [] } if "systemCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["systemCommandTrigger"]: for trigger in self._config["events"]["systemCommandTrigger"]["subscriptions"]: if not ("event" in trigger and "command" in trigger): continue newTrigger = {"type": "system"} if disableSystemCommands and not disableAllCommands: newTrigger["enabled"] = False newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"]) newEvents["subscriptions"].append(newTrigger) if "gcodeCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["gcodeCommandTrigger"]: for trigger in self._config["events"]["gcodeCommandTrigger"]["subscriptions"]: if not ("event" in trigger and "command" in trigger): continue newTrigger = {"type": "gcode"} if disableGcodeCommands and not disableAllCommands: newTrigger["enabled"] = False newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"]) newTrigger["command"] = newTrigger["command"].split(",") newEvents["subscriptions"].append(newTrigger) self._config["events"] = newEvents self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"])) return True else: return False def save(self, force=False): if not self._dirty and not force: return False from octoprint.util import atomic_write try: with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml") as configFile: yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True) self._dirty = False except: self._logger.exception("Error while saving config.yaml!") raise else: self.load() return True @property def last_modified(self): """ Returns: int: The last modification time of the configuration file. """ stat = os.stat(self._configfile) return stat.st_mtime #~~ getter def get(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True): import octoprint.util as util if len(path) == 0: return None if config is None: config = self._config if defaults is None: defaults = default_settings if preprocessors is None: preprocessors = self._get_preprocessors while len(path) > 1: key = path.pop(0) if key in config and key in defaults: config = config[key] defaults = defaults[key] elif incl_defaults and key in defaults: config = {} defaults = defaults[key] else: return None if preprocessors and isinstance(preprocessors, dict) and key in preprocessors: preprocessors = preprocessors[key] k = path.pop(0) if not isinstance(k, (list, tuple)): keys = [k] else: keys = k if asdict: results = {} else: results = [] for key in keys: if key in config: value = config[key] if merged and key in defaults: value = util.dict_merge(defaults[key], value) elif incl_defaults and key in defaults: value = defaults[key] else: value = None if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]): value = preprocessors[key](value) if asdict: results[key] = value else: results.append(value) if not isinstance(k, (list, tuple)): if asdict: return results.values().pop() else: return results.pop() else: return results def getInt(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True): value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults) if value is None: return None try: return int(value) except ValueError: self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path)) return None def getFloat(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True): value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults) if value is None: return None try: return float(value) except ValueError: self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path)) return None def getBoolean(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True): value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults) if value is None: return None if isinstance(value, bool): return value if isinstance(value, (int, float)): return value != 0 if isinstance(value, (str, unicode)): return value.lower() in valid_boolean_trues return value is not None def getBaseFolder(self, type, create=True): if type not in default_settings["folder"].keys() + ["base"]: return None if type == "base": return self._basedir folder = self.get(["folder", type]) if folder is None: folder = self._get_default_folder(type) if not os.path.isdir(folder): if create: os.makedirs(folder) else: raise IOError("No such folder: {folder}".format(folder=folder)) return folder def listScripts(self, script_type): return map(lambda x: x[len(script_type + "/"):], filter(lambda x: x.startswith(script_type + "/"), self._get_scripts(script_type))) def loadScript(self, script_type, name, context=None, source=False): if context is None: context = dict() context.update(dict(script=dict(type=script_type, name=name))) template = self._get_script_template(script_type, name, source=source) if template is None: return None if source: script = template else: try: script = template.render(**context) except: self._logger.exception("Exception while trying to render script {script_type}:{name}".format(**locals())) return None return script #~~ setter def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None): if len(path) == 0: return if self._mtime is not None and self.last_modified != self._mtime: self.load() if config is None: config = self._config if defaults is None: defaults = default_settings if preprocessors is None: preprocessors = self._set_preprocessors while len(path) > 1: key = path.pop(0) if key in config.keys() and key in defaults.keys(): config = config[key] defaults = defaults[key] elif key in defaults.keys(): config[key] = {} config = config[key] defaults = defaults[key] else: return if preprocessors and isinstance(preprocessors, dict) and key in preprocessors: preprocessors = preprocessors[key] key = path.pop(0) if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]): value = preprocessors[key](value) if not force and key in defaults and key in config and defaults[key] == value: del config[key] self._dirty = True elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value): if value is None and key in config: del config[key] else: config[key] = value self._dirty = True def setInt(self, path, value, force=False, defaults=None, config=None, preprocessors=None): if value is None: self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors) return try: intValue = int(value) except ValueError: self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path)) return self.set(path, intValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors) def setFloat(self, path, value, force=False, defaults=None, config=None, preprocessors=None): if value is None: self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors) return try: floatValue = float(value) except ValueError: self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path)) return self.set(path, floatValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors) def setBoolean(self, path, value, force=False, defaults=None, config=None, preprocessors=None): if value is None or isinstance(value, bool): self.set(path, value, config=config, force=force, defaults=defaults, preprocessors=preprocessors) elif value.lower() in valid_boolean_trues: self.set(path, True, config=config, force=force, defaults=defaults, preprocessors=preprocessors) else: self.set(path, False, config=config, force=force, defaults=defaults, preprocessors=preprocessors) def setBaseFolder(self, type, path, force=False): if type not in default_settings["folder"].keys(): return None currentPath = self.getBaseFolder(type) defaultPath = self._get_default_folder(type) if (path is None or path == defaultPath) and "folder" in self._config.keys() and type in self._config["folder"].keys(): del self._config["folder"][type] if not self._config["folder"]: del self._config["folder"] self._dirty = True elif (path != currentPath and path != defaultPath) or force: if not "folder" in self._config.keys(): self._config["folder"] = {} self._config["folder"][type] = path self._dirty = True def saveScript(self, script_type, name, script): script_folder = self.getBaseFolder("scripts") filename = os.path.realpath(os.path.join(script_folder, script_type, name)) if not filename.startswith(script_folder): # oops, jail break, that shouldn't happen raise ValueError("Invalid script path to save to: {filename} (from {script_type}:{name})".format(**locals())) path, _ = os.path.split(filename) if not os.path.exists(path): os.makedirs(path) with open(filename, "w+") as f: f.write(script) def _default_basedir(applicationName): # taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python if sys.platform == "darwin": from AppKit import NSSearchPathForDirectoriesInDomains # http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains # NSApplicationSupportDirectory = 14 # NSUserDomainMask = 1 # True for expanding the tilde into a fully qualified path return os.path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], applicationName) elif sys.platform == "win32": return os.path.join(os.environ["APPDATA"], applicationName) else: return os.path.expanduser(os.path.join("~", "." + applicationName.lower()))
from resources import loading import ast import configparser import os import sys import time from PIL import Image, ImageFilter from resources import customlogger as log from resources import namenum_converter as conv from resources.get_counters import get_counter # naming is hard def format_counter_list(counter_list): formatted_counter = '' for pair_ in counter_list: just_name_ = pair_[0] just_num_ = pair_[1] full_counter = conv.fancify(just_name_) + ': ' + str(just_num_) formatted_counter += (full_counter + ', ') return formatted_counter[:-2] # removes extra comma and space def log_any_uncaught_exception(type_, value, traceback): log.critical("Uncaught exception: {} {} {}".format(type_, value, traceback)) raise SystemError sys.excepthook = log_any_uncaught_exception log.info("START") # defaults refresh_delay = 0.5 process_allies = True max_logs = 10 dev = False try: config = configparser.ConfigParser() # load some settings with open('inah-settings.ini', 'r') as configfile: config.read('inah-settings.ini') refresh_delay = float(config['MAIN']['refresh_delay']) process_allies = ast.literal_eval(config['MAIN']['process_allies']) max_logs = float(config['MAIN']['max_logs']) dev = ast.literal_eval(config['MAIN']['dev']) settings_raw = configfile.readlines() settings_raw = settings_raw[0:13] log.info("Settings: " + str(settings_raw)) except: settings_error = "Couldn't load settings " + str(sys.exc_info()) print(settings_error + ", reverting to default settings") log.error(settings_error) log.cleanup(max_logs) heroes = ['ana', 'bastion', 'dva', 'genji', 'hanzo', 'junkrat', 'lucio', 'mccree', 'mei', 'mercy', 'pharah', 'reaper', 'reinhardt', 'roadhog', 'soldier', 'sombra', 'symmetra', 'torbjorn', 'tracer', 'widowmaker', 'winston', 'zarya', 'zenyatta', 'unknown', 'loading', 'anadead', 'bastiondead', 'dvadead', 'genjidead', 'junkratdead', 'luciodead', 'mccreedead', 'meidead', 'pharahdead', 'reaperdead', 'roadhogdead', 'soldierdead', 'sombradead', 'torbjorndead', 'tracerdead', 'zaryadead', 'zenyattadead', 'hanzodead', 'mercydead', 'orisadead', 'reinhardtdead', 'symmetradead', 'widowmakerdead', 'winstondead', 'orisa', 'doomfist', 'doomfistdead'] heroes_dps = ['bastion', 'genji', 'hanzo', 'junkrat', 'mccree', 'mei', 'pharah', 'reaper', 'soldier', 'sombra', 'symmetra', 'torbjorn', 'tracer', 'widowmaker', 'doomfist'] heroes_tank = ['dva', 'reinhardt', 'roadhog', 'winston', 'zarya', 'orisa'] heroes_heal = ['ana', 'lucio', 'mercy', 'zenyatta'] heroes_normal = [] # a list of heroes, not fancy, without unknown, loading, or dead for i in heroes: hero = conv.strip_dead(i) if ('unknown' not in hero) and ('loading' not in hero): heroes_normal.append(hero) if process_allies: filenames = ['ally1', 'ally2', 'ally3', 'ally4', 'ally5', 'ally6', 'enemy1', 'enemy2', 'enemy3', 'enemy4', 'enemy5', 'enemy6'] else: filenames = ['enemy1', 'enemy2', 'enemy3', 'enemy4', 'enemy5', 'enemy6'] if dev: print('FYI, developer mode is on.') dev_file = 'testing/breaksit2.jpg' log.debug("Developer mode is on, dev_file is " + dev_file) screenshots_path = os.path.expanduser('~\Documents\Overwatch\ScreenShots\Overwatch') log.info("screenshots_path is " + screenshots_path) inputs_before = os.listdir(screenshots_path) # a list of every file in the screenshots folder log.info('The screenshots folder has ' + str(len(inputs_before)) + " images") # builds a cache of learned images learned_images = {} for learned_path in os.listdir('learned'): if 'png' in learned_path: learned = Image.open('learned/' + learned_path).load() learned_images[learned_path[:-4]] = learned log.info("The learned folder has " + str(len(learned_images)) + " images") mask = Image.open('resources/mask.png').convert('RGBA') # used to ignore metal winged BS log.info("Mask opened: " + str(mask)) loading_time = loading.done() log.info("Loaded in " + str(loading_time) + " seconds") loops_done = 0 while True: if not dev: time.sleep(refresh_delay) # to stop high cpu usage while waiting continue_ = False inputs_after = os.listdir(screenshots_path) if len(inputs_after) > len(inputs_before): # if a file is added continue_ = True if len(inputs_after) < len(inputs_before): # if a file is removed continue_ = False inputs_before = os.listdir(screenshots_path) if continue_ or dev: # starting analysis log.info("START LOOP") log.info("Loop number: " + str(loops_done)) loops_done += 1 process_time_start = time.perf_counter() # defaults delete_thresehold = 80 process_threshold = 70 refresh_delay = 0.5 low_precision = False process_allies = True include_allies_in_counters = True highlight_yourself = True show_processing_text = False old_counter_list = False dev = False preview = False try: config = configparser.ConfigParser() # load all settings with open('inah-settings.ini', 'r') as configfile: config.read('inah-settings.ini') delete_thresehold = int(config['MAIN']['delete_thresehold']) process_threshold = int(config['MAIN']['process_threshold']) refresh_delay = float(config['MAIN']['refresh_delay']) low_precision = ast.literal_eval(config['MAIN']['low_precision']) process_allies = ast.literal_eval(config['MAIN']['process_allies']) include_allies_in_counters = ast.literal_eval(config['MAIN']['include_allies_in_counters']) highlight_yourself = ast.literal_eval(config['MAIN']['highlight_yourself']) show_processing_text = ast.literal_eval(config['MAIN']['show_processing_text']) old_counter_list = ast.literal_eval(config['MAIN']['old_counter_list']) dev = ast.literal_eval(config['MAIN']['dev']) preview = ast.literal_eval(config['MAIN']['preview']) settings_raw = configfile.readlines() settings_raw = settings_raw[0:13] log.info("Settings: " + str(settings_raw)) except: settings_error = "Couldn't load settings " + str(sys.exc_info()) print(settings_error + ", reverting to default settings") log.error(settings_error) inputs_diff = list(set(os.listdir(screenshots_path)) - set(inputs_before)) log.info("inputs_diff is " + str(inputs_diff)) current_filename = str(inputs_diff)[2:-2] # removes brackets and quotes if dev: current_filename = dev_file print("\nProcessing " + current_filename + " at " + str(time.strftime('%I:%M:%S %p', time.localtime()))) log.info("Processing " + current_filename) if not dev: try: time.sleep(0.1) # bug "fix" screenshot = Image.open(screenshots_path + '/' + inputs_diff[0]) log.info("Screenshot opened successfully: " + str(screenshot)) except OSError as error: print("This doesn't seem to be an image file.") inputs_before = os.listdir(screenshots_path) # resets screenshot folder list log.error("Couldn't open screenshot file: " + str(error)) continue else: screenshot = Image.open(dev_file) log.debug("Dev screenshot opened successfully: " + str(screenshot)) if preview: screenshot.save('preview.png') log.info("Saved preview") else: try: os.remove("preview.png") log.info("Deleted preview") except FileNotFoundError: log.info("No preview to delete") pass width, height = screenshot.size aspect_ratio = width / height log.info("Aspect ratio is {} ({} / {})".format(aspect_ratio, width, height)) if aspect_ratio > 2: # the aspect ratio the user is running at is 21:9 log.info("Formatted aspect ratio is closest to 21:9, processing accordingly") if not (width == 2579 and height == 1080): screenshot = screenshot.resize((2579, 1080), resample=Image.BICUBIC) screenshot = screenshot.crop((329, 0, 2249, 1080)) elif aspect_ratio < 1.7: # aspect ratio is 16:10 log.info("Formatted aspect ratio is closest to 16:10, processing accordingly") if not (width == 1920 and height == 1200): screenshot = screenshot.resize((1920, 1200), resample=Image.BICUBIC) screenshot = screenshot.crop((0, 60, 1920, 1140)) else: # aspect ratio is 16:9 log.info("Formatted aspect ratio is closest to 16:9, processing accordingly") if not (width == 1920 and height == 1080): screenshot = screenshot.resize((1920, 1080), resample=Image.BICUBIC) if low_precision: step = 2 # skips every other pixel divisor = 64000 # scary magic math else: step = 1 divisor = 256000 ally1 = screenshot.crop((443, 584, 519, 660)) ally2 = screenshot.crop((634, 584, 710, 660)) ally3 = screenshot.crop((826, 584, 902, 660)) ally4 = screenshot.crop((1019, 584, 1095, 660)) ally5 = screenshot.crop((1210, 584, 1286, 660)) ally6 = screenshot.crop((1402, 584, 1478, 660)) enemy1 = screenshot.crop((443, 279, 519, 355)) enemy2 = screenshot.crop((634, 279, 710, 355)) enemy3 = screenshot.crop((826, 279, 902, 355)) enemy4 = screenshot.crop((1019, 279, 1095, 355)) enemy5 = screenshot.crop((1210, 279, 1286, 355)) enemy6 = screenshot.crop((1402, 279, 1478, 355)) filenames_opened = [] if process_allies: filenames_opened.append(ally1) filenames_opened.append(ally2) filenames_opened.append(ally3) filenames_opened.append(ally4) filenames_opened.append(ally5) filenames_opened.append(ally6) filenames_opened.append(enemy1) filenames_opened.append(enemy2) filenames_opened.append(enemy3) filenames_opened.append(enemy4) filenames_opened.append(enemy5) filenames_opened.append(enemy6) allied_team = [] enemy_team = [] total_confidence = [] team_confidences = [] log.info("Starting image recognition") for h in range(0, len(filenames)): # every ally or enemy unknown_unloaded = filenames_opened[h] unknown_unloaded = unknown_unloaded.filter(ImageFilter.GaussianBlur(radius=1)) unknown_unloaded.paste(mask, (0, 0), mask) # ...until I put on the mask unknown = unknown_unloaded.load() confidences = [] for i in heroes: confidences.append(0) # makes a hero-long list of zeroes for j in range(0, len(heroes)): # the image recognition magic learned_image = learned_images[heroes[j]] for x in range(0, 75, step): for y in range(0, 75, step): input_color = unknown[x, y] learned_color = learned_image[x, y] confidences[j] += abs(input_color[0] - learned_color[0]) confidences[j] = 1 - (confidences[j] / divisor) if show_processing_text: print("For " + filenames[h] + ":") likely_name = '' # find the most likely hero likely_num = -1 for i in range(0, len(confidences)): if confidences[i] > likely_num: likely_num = confidences[i] likely_name = heroes[i] print_conf = int(likely_num * 100) if print_conf < 0: print_conf = 0 if show_processing_text: print("Most likely is " + likely_name + ", with a confidence of " + str(print_conf) + "%") total_confidence.append(print_conf) if 'ally' in filenames[h]: allied_team.append(likely_name) # builds the team lists elif 'enemy' in filenames[h]: enemy_team.append(likely_name) print('\n') process_time_elapsed = time.perf_counter() - process_time_start print("Processing finished in " + str(process_time_elapsed)[0:3] + " seconds") log.info("Image recognition finished in " + str(process_time_elapsed) + " seconds") log.info("Enemy team is " + str(enemy_team)) if process_allies: log.info("Allied team is " + str(allied_team)) log.info("Confidences (allied first): " + str(total_confidence)) enemy_team_fancy = '' for i in enemy_team: hero = conv.fancify(i) enemy_team_fancy += (hero + ', ') if process_allies: allied_team_fancy = '' for i in allied_team: hero = conv.fancify(i) allied_team_fancy += (hero + ', ') total_conf_average = int(sum(total_confidence) / float(len(total_confidence))) log.info("Image recognition had a confidence of " + str(total_conf_average)) if total_conf_average > process_threshold: print("Enemy team: " + enemy_team_fancy[:-2]) print("Allied team: " + allied_team_fancy[:-2]) print("Confidence: " + str(total_conf_average) + '%') else: print("This screenshot doesn't seem to be of the tab menu " + "(needs " + str(process_threshold) + "% confidence, got " + str(total_conf_average) + "%)") enemy_is_heroes = True j = 0 for i in enemy_team: if (i == 'loading') or (i == 'unknown'): j += 1 if j == 6: enemy_is_heroes = False # if everyone on the enemy team is loading or unknown log.info("The enemy team IS loading or unknown") else: log.info("The enemy team is NOT loading or unknown") if total_conf_average > process_threshold and process_allies: allied_team_alive = [] for possibly_dead_hero in allied_team: allied_team_alive.append(conv.strip_dead(possibly_dead_hero)) if not any(x in allied_team_alive for x in heroes_dps): print("Your team doesn't have any DPS heroes!") if not any(x in allied_team_alive for x in heroes_tank): print("Your team doesn't have any tank heroes!") if not any(x in allied_team_alive for x in heroes_heal): print("Your team doesn't have any healers!") if total_conf_average > process_threshold and process_allies and enemy_is_heroes: # get overall team counter advantage allied_team_counter = 0 for i in enemy_team: for j in allied_team: cross_team_counter = get_counter(i, j) allied_team_counter -= cross_team_counter log.info("Overall team counter is " + str(allied_team_counter)) if allied_team_counter < 0: print("Your team has an counter advantage of " + str(-allied_team_counter)) elif allied_team_counter > 0: print("The enemy team has an counter advantage of " + str(allied_team_counter)) elif allied_team_counter == 0: print("Neither team has a counter advantage") else: log.error("This should never happen") raise ValueError # sure why not if enemy_is_heroes and (total_conf_average > process_threshold): # is this valid to get counters from # begin getting counters log.info("Getting counters") all_counters = {} for any_hero in heroes_normal: # actually gets counters all_counters[any_hero] = 0 for enemy_hero in enemy_team: enemy_hero = conv.strip_dead(enemy_hero) if ('unknown' not in any_hero) and ('loading' not in any_hero): countered = get_counter(any_hero, enemy_hero) all_counters[any_hero] -= countered sorted_counters = sorted(all_counters.items(), reverse=True, key=lambda z: z[1]) # wtf log.info("Got " + str(len(sorted_counters)) + " counters") if not old_counter_list: dps_counters = [] tank_counters = [] heal_counters = [] for pair in sorted_counters: just_name = pair[0] just_num = pair[1] if just_name not in allied_team or include_allies_in_counters: if just_name in heroes_dps: dps_counters.append(tuple((just_name, just_num))) if just_name in heroes_tank: tank_counters.append(tuple((just_name, just_num))) if just_name in heroes_heal: heal_counters.append(tuple((just_name, just_num))) if just_name == conv.strip_dead(allied_team[0]): yourself = 'You (' + conv.fancify(just_name) + '): ' + str(just_num) # no need to sort these, sorted_counters was already sorted (duh) final_counters_dps = format_counter_list(dps_counters) final_counters_tank = format_counter_list(tank_counters) final_counters_heal = format_counter_list(heal_counters) print('\n') print("Counters (higher is better)") print("DPS - " + final_counters_dps) print("Tanks - " + final_counters_tank) print("Healers - " + final_counters_heal) else: final_counters = format_counter_list(sorted_counters) print('\n') print("Counters (higher is better)") print(final_counters) if highlight_yourself: print(yourself) log.info("Yourself: '" + yourself + "'") # end getting counters elif not enemy_is_heroes: print("\nThe enemy team appears to be all loading or unknown, which counters can't be calculated from.") print('\n') # managing these is hard if total_conf_average > delete_thresehold and not dev: # deletes screenshot once done os.remove(screenshots_path + '/' + inputs_diff[0]) # doesn't recycle, fyi print("Deleted " + current_filename + ' (needed ' + str(delete_thresehold) + '% confidence, got ' + str(total_conf_average) + '%)') log.info("Deleted screenshot") else: print("Didn't delete " + current_filename + ' (needs ' + str(delete_thresehold) + '% confidence, got ' + str(total_conf_average) + '%)') log.info("Didn't delete screenshot") if delete_thresehold >= 100: print("The delete threshold is currently 100%, which means that even tab menu screenshots aren't" " deleted. Be sure to clean the screenshots folder out manually every now and then.") inputs_before = os.listdir(screenshots_path) # resets screenshot folder list log.info("END LOOP") if dev: log.info("Dev mode is on and a full loop has been completed, exiting") raise SystemExit print('\n') print('Analysis complete. Hold tab and press the "print screen" button to get a new set of counters.') Added a progress bar from resources import loading import ast import configparser import os import sys import time from PIL import Image, ImageFilter from tqdm import tqdm from resources import customlogger as log from resources import namenum_converter as conv from resources.get_counters import get_counter # naming is hard def format_counter_list(counter_list): formatted_counter = '' for pair_ in counter_list: just_name_ = pair_[0] just_num_ = pair_[1] full_counter = conv.fancify(just_name_) + ': ' + str(just_num_) formatted_counter += (full_counter + ', ') return formatted_counter[:-2] # removes extra comma and space def log_any_uncaught_exception(type_, value, traceback): log.critical("Uncaught exception: {} {} {}".format(type_, value, traceback)) raise SystemError sys.excepthook = log_any_uncaught_exception log.info("START") # defaults refresh_delay = 0.5 process_allies = True max_logs = 10 dev = False try: config = configparser.ConfigParser() # load some settings with open('inah-settings.ini', 'r') as configfile: config.read('inah-settings.ini') refresh_delay = float(config['MAIN']['refresh_delay']) process_allies = ast.literal_eval(config['MAIN']['process_allies']) max_logs = float(config['MAIN']['max_logs']) dev = ast.literal_eval(config['MAIN']['dev']) settings_raw = configfile.readlines() settings_raw = settings_raw[0:13] log.info("Settings: " + str(settings_raw)) except: settings_error = "Couldn't load settings " + str(sys.exc_info()) print(settings_error + ", reverting to default settings") log.error(settings_error) log.cleanup(max_logs) heroes = ['ana', 'bastion', 'dva', 'genji', 'hanzo', 'junkrat', 'lucio', 'mccree', 'mei', 'mercy', 'pharah', 'reaper', 'reinhardt', 'roadhog', 'soldier', 'sombra', 'symmetra', 'torbjorn', 'tracer', 'widowmaker', 'winston', 'zarya', 'zenyatta', 'unknown', 'loading', 'anadead', 'bastiondead', 'dvadead', 'genjidead', 'junkratdead', 'luciodead', 'mccreedead', 'meidead', 'pharahdead', 'reaperdead', 'roadhogdead', 'soldierdead', 'sombradead', 'torbjorndead', 'tracerdead', 'zaryadead', 'zenyattadead', 'hanzodead', 'mercydead', 'orisadead', 'reinhardtdead', 'symmetradead', 'widowmakerdead', 'winstondead', 'orisa', 'doomfist', 'doomfistdead'] heroes_dps = ['bastion', 'genji', 'hanzo', 'junkrat', 'mccree', 'mei', 'pharah', 'reaper', 'soldier', 'sombra', 'symmetra', 'torbjorn', 'tracer', 'widowmaker', 'doomfist'] heroes_tank = ['dva', 'reinhardt', 'roadhog', 'winston', 'zarya', 'orisa'] heroes_heal = ['ana', 'lucio', 'mercy', 'zenyatta'] heroes_normal = [] # a list of heroes, not fancy, without unknown, loading, or dead for i in heroes: hero = conv.strip_dead(i) if ('unknown' not in hero) and ('loading' not in hero): heroes_normal.append(hero) if process_allies: filenames = ['ally1', 'ally2', 'ally3', 'ally4', 'ally5', 'ally6', 'enemy1', 'enemy2', 'enemy3', 'enemy4', 'enemy5', 'enemy6'] else: filenames = ['enemy1', 'enemy2', 'enemy3', 'enemy4', 'enemy5', 'enemy6'] if dev: print('FYI, developer mode is on.') dev_file = 'testing/breaksit2.jpg' log.debug("Developer mode is on, dev_file is " + dev_file) screenshots_path = os.path.expanduser('~\Documents\Overwatch\ScreenShots\Overwatch') log.info("screenshots_path is " + screenshots_path) inputs_before = os.listdir(screenshots_path) # a list of every file in the screenshots folder log.info('The screenshots folder has ' + str(len(inputs_before)) + " images") # builds a cache of learned images learned_images = {} for learned_path in os.listdir('learned'): if 'png' in learned_path: learned = Image.open('learned/' + learned_path).load() learned_images[learned_path[:-4]] = learned log.info("The learned folder has " + str(len(learned_images)) + " images") mask = Image.open('resources/mask.png').convert('RGBA') # used to ignore metal winged BS log.info("Mask opened: " + str(mask)) loading_time = loading.done() log.info("Loaded in " + str(loading_time) + " seconds") loops_done = 0 while True: if not dev: time.sleep(refresh_delay) # to stop high cpu usage while waiting continue_ = False inputs_after = os.listdir(screenshots_path) if len(inputs_after) > len(inputs_before): # if a file is added continue_ = True if len(inputs_after) < len(inputs_before): # if a file is removed continue_ = False inputs_before = os.listdir(screenshots_path) if continue_ or dev: # starting analysis log.info("START LOOP") log.info("Loop number: " + str(loops_done)) loops_done += 1 process_time_start = time.perf_counter() # defaults delete_thresehold = 80 process_threshold = 70 refresh_delay = 0.5 low_precision = False process_allies = True include_allies_in_counters = True highlight_yourself = True show_processing_text = False old_counter_list = False dev = False preview = False try: config = configparser.ConfigParser() # load all settings with open('inah-settings.ini', 'r') as configfile: config.read('inah-settings.ini') delete_thresehold = int(config['MAIN']['delete_thresehold']) process_threshold = int(config['MAIN']['process_threshold']) refresh_delay = float(config['MAIN']['refresh_delay']) low_precision = ast.literal_eval(config['MAIN']['low_precision']) process_allies = ast.literal_eval(config['MAIN']['process_allies']) include_allies_in_counters = ast.literal_eval(config['MAIN']['include_allies_in_counters']) highlight_yourself = ast.literal_eval(config['MAIN']['highlight_yourself']) show_processing_text = ast.literal_eval(config['MAIN']['show_processing_text']) old_counter_list = ast.literal_eval(config['MAIN']['old_counter_list']) dev = ast.literal_eval(config['MAIN']['dev']) preview = ast.literal_eval(config['MAIN']['preview']) settings_raw = configfile.readlines() settings_raw = settings_raw[0:13] log.info("Settings: " + str(settings_raw)) except: settings_error = "Couldn't load settings " + str(sys.exc_info()) print(settings_error + ", reverting to default settings") log.error(settings_error) inputs_diff = list(set(os.listdir(screenshots_path)) - set(inputs_before)) log.info("inputs_diff is " + str(inputs_diff)) current_filename = str(inputs_diff)[2:-2] # removes brackets and quotes if dev: current_filename = dev_file print("\nProcessing " + current_filename + " at " + str(time.strftime('%I:%M:%S %p', time.localtime()))) log.info("Processing " + current_filename) if not dev: try: time.sleep(0.1) # bug "fix" screenshot = Image.open(screenshots_path + '/' + inputs_diff[0]) log.info("Screenshot opened successfully: " + str(screenshot)) except OSError as error: print("This doesn't seem to be an image file.") inputs_before = os.listdir(screenshots_path) # resets screenshot folder list log.error("Couldn't open screenshot file: " + str(error)) continue else: screenshot = Image.open(dev_file) log.debug("Dev screenshot opened successfully: " + str(screenshot)) if preview: screenshot.save('preview.png') log.info("Saved preview") else: try: os.remove("preview.png") log.info("Deleted preview") except FileNotFoundError: log.info("No preview to delete") pass width, height = screenshot.size aspect_ratio = width / height log.info("Aspect ratio is {} ({} / {})".format(aspect_ratio, width, height)) if aspect_ratio > 2: # the aspect ratio the user is running at is 21:9 log.info("Formatted aspect ratio is closest to 21:9, processing accordingly") if not (width == 2579 and height == 1080): screenshot = screenshot.resize((2579, 1080), resample=Image.BICUBIC) screenshot = screenshot.crop((329, 0, 2249, 1080)) elif aspect_ratio < 1.7: # aspect ratio is 16:10 log.info("Formatted aspect ratio is closest to 16:10, processing accordingly") if not (width == 1920 and height == 1200): screenshot = screenshot.resize((1920, 1200), resample=Image.BICUBIC) screenshot = screenshot.crop((0, 60, 1920, 1140)) else: # aspect ratio is 16:9 log.info("Formatted aspect ratio is closest to 16:9, processing accordingly") if not (width == 1920 and height == 1080): screenshot = screenshot.resize((1920, 1080), resample=Image.BICUBIC) if low_precision: step = 2 # skips every other pixel divisor = 64000 # scary magic math else: step = 1 divisor = 256000 ally1 = screenshot.crop((443, 584, 519, 660)) ally2 = screenshot.crop((634, 584, 710, 660)) ally3 = screenshot.crop((826, 584, 902, 660)) ally4 = screenshot.crop((1019, 584, 1095, 660)) ally5 = screenshot.crop((1210, 584, 1286, 660)) ally6 = screenshot.crop((1402, 584, 1478, 660)) enemy1 = screenshot.crop((443, 279, 519, 355)) enemy2 = screenshot.crop((634, 279, 710, 355)) enemy3 = screenshot.crop((826, 279, 902, 355)) enemy4 = screenshot.crop((1019, 279, 1095, 355)) enemy5 = screenshot.crop((1210, 279, 1286, 355)) enemy6 = screenshot.crop((1402, 279, 1478, 355)) filenames_opened = [] if process_allies: filenames_opened.append(ally1) filenames_opened.append(ally2) filenames_opened.append(ally3) filenames_opened.append(ally4) filenames_opened.append(ally5) filenames_opened.append(ally6) filenames_opened.append(enemy1) filenames_opened.append(enemy2) filenames_opened.append(enemy3) filenames_opened.append(enemy4) filenames_opened.append(enemy5) filenames_opened.append(enemy6) allied_team = [] enemy_team = [] total_confidence = [] team_confidences = [] log.info("Starting image recognition") for h in tqdm(range(0, len(filenames)), file=sys.stdout, ncols=40, bar_format='{l_bar}{bar}|'): # loads an portrait to process unknown_unloaded = filenames_opened[h] unknown_unloaded = unknown_unloaded.filter(ImageFilter.GaussianBlur(radius=1)) unknown_unloaded.paste(mask, (0, 0), mask) # ...until I put on the mask unknown = unknown_unloaded.load() confidences = [] for i in heroes: confidences.append(0) # makes a hero-long list of zeroes for j in range(0, len(heroes)): # the image recognition magic learned_image = learned_images[heroes[j]] for x in range(0, 75, step): for y in range(0, 75, step): input_color = unknown[x, y] learned_color = learned_image[x, y] confidences[j] += abs(input_color[0] - learned_color[0]) confidences[j] = 1 - (confidences[j] / divisor) if show_processing_text: print("For " + filenames[h] + ":") likely_name = '' # find the most likely hero likely_num = -1 for i in range(0, len(confidences)): if confidences[i] > likely_num: likely_num = confidences[i] likely_name = heroes[i] print_conf = int(likely_num * 100) if print_conf < 0: print_conf = 0 if show_processing_text: print("Most likely is " + likely_name + ", with a confidence of " + str(print_conf) + "%") total_confidence.append(print_conf) if 'ally' in filenames[h]: allied_team.append(likely_name) # builds the team lists elif 'enemy' in filenames[h]: enemy_team.append(likely_name) print('\n') process_time_elapsed = time.perf_counter() - process_time_start print("Processing finished in " + str(process_time_elapsed)[0:3] + " seconds") log.info("Image recognition finished in " + str(process_time_elapsed) + " seconds") log.info("Enemy team is " + str(enemy_team)) if process_allies: log.info("Allied team is " + str(allied_team)) log.info("Confidences (allied first): " + str(total_confidence)) enemy_team_fancy = '' for i in enemy_team: hero = conv.fancify(i) enemy_team_fancy += (hero + ', ') if process_allies: allied_team_fancy = '' for i in allied_team: hero = conv.fancify(i) allied_team_fancy += (hero + ', ') total_conf_average = int(sum(total_confidence) / float(len(total_confidence))) log.info("Image recognition had a confidence of " + str(total_conf_average)) if total_conf_average > process_threshold: print("Enemy team: " + enemy_team_fancy[:-2]) print("Allied team: " + allied_team_fancy[:-2]) print("Confidence: " + str(total_conf_average) + '%') else: print("This screenshot doesn't seem to be of the tab menu " + "(needs " + str(process_threshold) + "% confidence, got " + str(total_conf_average) + "%)") enemy_is_heroes = True j = 0 for i in enemy_team: if (i == 'loading') or (i == 'unknown'): j += 1 if j == 6: enemy_is_heroes = False # if everyone on the enemy team is loading or unknown log.info("The enemy team IS loading or unknown") else: log.info("The enemy team is NOT loading or unknown") if total_conf_average > process_threshold and process_allies: allied_team_alive = [] for possibly_dead_hero in allied_team: allied_team_alive.append(conv.strip_dead(possibly_dead_hero)) if not any(x in allied_team_alive for x in heroes_dps): print("Your team doesn't have any DPS heroes!") if not any(x in allied_team_alive for x in heroes_tank): print("Your team doesn't have any tank heroes!") if not any(x in allied_team_alive for x in heroes_heal): print("Your team doesn't have any healers!") if total_conf_average > process_threshold and process_allies and enemy_is_heroes: # get overall team counter advantage allied_team_counter = 0 for i in enemy_team: for j in allied_team: cross_team_counter = get_counter(i, j) allied_team_counter -= cross_team_counter log.info("Overall team counter is " + str(allied_team_counter)) if allied_team_counter < 0: print("Your team has an counter advantage of " + str(-allied_team_counter)) elif allied_team_counter > 0: print("The enemy team has an counter advantage of " + str(allied_team_counter)) elif allied_team_counter == 0: print("Neither team has a counter advantage") else: log.error("This should never happen") raise ValueError # sure why not if enemy_is_heroes and (total_conf_average > process_threshold): # is this valid to get counters from # begin getting counters log.info("Getting counters") all_counters = {} for any_hero in heroes_normal: # actually gets counters all_counters[any_hero] = 0 for enemy_hero in enemy_team: enemy_hero = conv.strip_dead(enemy_hero) if ('unknown' not in any_hero) and ('loading' not in any_hero): countered = get_counter(any_hero, enemy_hero) all_counters[any_hero] -= countered sorted_counters = sorted(all_counters.items(), reverse=True, key=lambda z: z[1]) # wtf log.info("Got " + str(len(sorted_counters)) + " counters") if not old_counter_list: dps_counters = [] tank_counters = [] heal_counters = [] for pair in sorted_counters: just_name = pair[0] just_num = pair[1] if just_name not in allied_team or include_allies_in_counters: if just_name in heroes_dps: dps_counters.append(tuple((just_name, just_num))) if just_name in heroes_tank: tank_counters.append(tuple((just_name, just_num))) if just_name in heroes_heal: heal_counters.append(tuple((just_name, just_num))) if just_name == conv.strip_dead(allied_team[0]): yourself = 'You (' + conv.fancify(just_name) + '): ' + str(just_num) # no need to sort these, sorted_counters was already sorted (duh) final_counters_dps = format_counter_list(dps_counters) final_counters_tank = format_counter_list(tank_counters) final_counters_heal = format_counter_list(heal_counters) print('\n') print("Counters (higher is better)") print("DPS - " + final_counters_dps) print("Tanks - " + final_counters_tank) print("Healers - " + final_counters_heal) else: final_counters = format_counter_list(sorted_counters) print('\n') print("Counters (higher is better)") print(final_counters) if highlight_yourself: print(yourself) log.info("Yourself: '" + yourself + "'") # end getting counters elif not enemy_is_heroes: print("\nThe enemy team appears to be all loading or unknown, which counters can't be calculated from.") print('\n') # managing these is hard if total_conf_average > delete_thresehold and not dev: # deletes screenshot once done os.remove(screenshots_path + '/' + inputs_diff[0]) # doesn't recycle, fyi print("Deleted " + current_filename + ' (needed ' + str(delete_thresehold) + '% confidence, got ' + str(total_conf_average) + '%)') log.info("Deleted screenshot") else: print("Didn't delete " + current_filename + ' (needs ' + str(delete_thresehold) + '% confidence, got ' + str(total_conf_average) + '%)') log.info("Didn't delete screenshot") if delete_thresehold >= 100: print("The delete threshold is currently 100%, which means that even tab menu screenshots aren't" " deleted. Be sure to clean the screenshots folder out manually every now and then.") inputs_before = os.listdir(screenshots_path) # resets screenshot folder list log.info("END LOOP") if dev: log.info("Dev mode is on and a full loop has been completed, exiting") raise SystemExit print('\n') print('Analysis complete. Hold tab and press the "print screen" button to get a new set of counters.')
from django.db import models from django.conf import settings from django.utils.timezone import utc, localtime from restclients.canvas.sis_import import SISImport from restclients.models.canvas import SISImport as SISImportModel from restclients.gws import GWS from restclients.exceptions import DataFailureException from eos.models import EOSCourseDelta import datetime import json import re PRIORITY_NONE = 0 PRIORITY_DEFAULT = 1 PRIORITY_HIGH = 2 PRIORITY_IMMEDIATE = 3 PRIORITY_CHOICES = ( (PRIORITY_NONE, 'none'), (PRIORITY_DEFAULT, 'normal'), (PRIORITY_HIGH, 'high'), (PRIORITY_IMMEDIATE, 'immediate') ) class EmptyQueueException(Exception): pass class MissingImportPathException(Exception): pass class Job(models.Model): """ Represents provisioning commands. """ name = models.CharField(max_length=128) title = models.CharField(max_length=128) changed_by = models.CharField(max_length=32) changed_date = models.DateTimeField() last_run_date = models.DateTimeField(null=True) is_active = models.NullBooleanField() health_status = models.CharField(max_length=512, null=True) last_status_date = models.DateTimeField(null=True) def json_data(self): return { 'job_id': self.pk, 'name': self.name, 'title': self.title, 'changed_by': self.changed_by, 'changed_date': localtime(self.changed_date).isoformat() if ( self.changed_date is not None) else None, 'last_run_date': localtime(self.last_run_date).isoformat() if ( self.last_run_date is not None) else None, 'is_active': self.is_active, 'health_status': self.health_status, 'last_status_date': localtime( self.last_status_date).isoformat() if ( self.last_status_date is not None) else None, } class TermManager(models.Manager): def queue_unused_courses(self, term_id): try: term = Term.objects.get(term_id=term_id) if (term.deleted_unused_courses_date is not None or term.queue_id is not None): raise EmptyQueueException() except Term.DoesNotExist: term = Term(term_id=term_id) term.save() imp = Import(priority=PRIORITY_DEFAULT, csv_type='unused_course') imp.save() term.queue_id = imp.pk term.save() return imp def queued(self, queue_id): return super(TermManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): kwargs = {'queue_id': None} if provisioned_date is not None: # Currently only handles the 'unused_course' type kwargs['deleted_unused_courses_date'] = provisioned_date self.queued(queue_id).update(**kwargs) class Term(models.Model): """ Represents the provisioned state of courses for a term. """ term_id = models.CharField(max_length=20, unique=True) added_date = models.DateTimeField(auto_now_add=True) last_course_search_date = models.DateTimeField(null=True) courses_changed_since_date = models.DateTimeField(null=True) deleted_unused_courses_date = models.DateTimeField(null=True) queue_id = models.CharField(max_length=30, null=True) objects = TermManager() class CourseManager(models.Manager): def get_linked_course_ids(self, course_id): return super(CourseManager, self).get_query_set().filter( primary_id=course_id).values_list('course_id', flat=True) def get_joint_course_ids(self, course_id): return super(CourseManager, self).get_query_set().filter( xlist_id=course_id).exclude(course_id=course_id).values_list( 'course_id', flat=True) def queue_by_priority(self, priority=PRIORITY_DEFAULT): if priority > PRIORITY_DEFAULT: filter_limit = settings.SIS_IMPORT_LIMIT['course']['high'] else: filter_limit = settings.SIS_IMPORT_LIMIT['course']['default'] pks = super(CourseManager, self).get_query_set().filter( priority=priority, course_type=Course.SDB_TYPE, queue_id__isnull=True, provisioned_error__isnull=True ).order_by( 'provisioned_date', 'added_date' ).values_list('pk', flat=True)[:filter_limit] if not len(pks): raise EmptyQueueException() imp = Import(priority=priority, csv_type='course') imp.save() # Mark the courses as in process, and reset the priority super(CourseManager, self).get_query_set().filter( pk__in=list(pks) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def queued(self, queue_id): return super(CourseManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): kwargs = {'queue_id': None} if provisioned_date is not None: kwargs['provisioned_date'] = provisioned_date kwargs['priority'] = PRIORITY_DEFAULT self.queued(queue_id).update(**kwargs) class Course(models.Model): """ Represents the provisioned state of a course. """ SDB_TYPE = 'sdb' ADHOC_TYPE = 'adhoc' TYPE_CHOICES = ((SDB_TYPE, 'SDB'), (ADHOC_TYPE, 'Ad Hoc')) course_id = models.CharField(max_length=80, unique=True) course_type = models.CharField(max_length=16, choices=TYPE_CHOICES) term_id = models.CharField(max_length=20, db_index=True) primary_id = models.CharField(max_length=80, null=True) xlist_id = models.CharField(max_length=80, null=True) added_date = models.DateTimeField(auto_now_add=True) provisioned_date = models.DateTimeField(null=True) provisioned_error = models.NullBooleanField() provisioned_status = models.CharField(max_length=512, null=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = CourseManager() def is_sdb(self): return self.course_type == self.SDB_TYPE def is_adhoc(self): return self.course_type == self.ADHOC_TYPE def sws_url(self): try: (year, quarter, curr_abbr, course_num, section_id) = self.course_id.split('-', 4) sws_url = "%s/%s,%s,%s,%s/%s.json" % ( "/restclients/view/sws/student/v5/course", year, quarter, curr_abbr, course_num, section_id) except ValueError: sws_url = None return sws_url def json_data(self, include_sws_url=False): try: group_models = Group.objects.filter(course_id=self.course_id, is_deleted__isnull=True) groups = list(group_models.values_list("group_id", flat=True)) except Group.DoesNotExist: groups = [] return { "course_id": self.course_id, "term_id": self.term_id, "xlist_id": self.xlist_id, "is_sdb_type": self.is_sdb(), "added_date": localtime(self.added_date).isoformat() if ( self.added_date is not None) else None, "provisioned_date": localtime( self.provisioned_date).isoformat() if ( self.provisioned_date is not None) else None, "priority": PRIORITY_CHOICES[self.priority][1], "provisioned_error": self.provisioned_error, "provisioned_status": self.provisioned_status, "queue_id": self.queue_id, "groups": groups, "sws_url": self.sws_url() if ( include_sws_url and self.is_sdb()) else None, } class EnrollmentManager(models.Manager): def queue_by_priority(self, priority=PRIORITY_DEFAULT): filter_limit = settings.SIS_IMPORT_LIMIT['enrollment']['default'] pks = super(EnrollmentManager, self).get_query_set().filter( priority=priority, queue_id__isnull=True ).order_by( 'last_modified' ).values_list('pk', flat=True)[:filter_limit] if not len(pks): raise EmptyQueueException() imp = Import(priority=priority, csv_type='enrollment') imp.save() # Mark the enrollments as in process super(EnrollmentManager, self).get_query_set().filter( pk__in=list(pks) ).update(queue_id=imp.pk) return imp def queued(self, queue_id): return super(EnrollmentManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): if provisioned_date is None: self.queued(queue_id).update(queue_id=None) else: super(EnrollmentManager, self).get_query_set().filter( queue_id=queue_id, priority=PRIORITY_DEFAULT ).update( priority=PRIORITY_NONE, queue_id=None ) super(EnrollmentManager, self).get_query_set().filter( queue_id=queue_id, priority=PRIORITY_HIGH ).update( priority=PRIORITY_DEFAULT, queue_id=None ) class Enrollment(models.Model): """ Represents the provisioned state of an enrollment. """ ACTIVE_STATUS = "active" INACTIVE_STATUS = "inactive" DELETED_STATUS = "deleted" COMPLETED_STATUS = "completed" STATUS_CHOICES = ( (ACTIVE_STATUS, "Active"), (INACTIVE_STATUS, "Inactive"), (DELETED_STATUS, "Deleted"), (COMPLETED_STATUS, "Completed") ) STUDENT_ROLE = "Student" AUDITOR_ROLE = "Auditor" INSTRUCTOR_ROLE = "Teacher" reg_id = models.CharField(max_length=32, null=True) status = models.CharField(max_length=16, choices=STATUS_CHOICES) course_id = models.CharField(max_length=80) last_modified = models.DateTimeField() primary_course_id = models.CharField(max_length=80, null=True) instructor_reg_id = models.CharField(max_length=32, null=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = EnrollmentManager() def is_active(self): return self.status == self.ACTIVE_STATUS def json_data(self): return { "reg_id": self.reg_id, "status": self.status, "course_id": self.course_id, "last_modified": localtime(self.last_modified).isoformat() if ( self.last_modified is not None) else None, "primary_course_id": self.primary_course_id, "instructor_reg_id": self.instructor_reg_id, "priority": PRIORITY_CHOICES[self.priority][1], "queue_id": self.queue_id, } class Meta: unique_together = ("course_id", "reg_id") class UserManager(models.Manager): def queue_by_priority(self, priority=PRIORITY_DEFAULT): if priority > PRIORITY_DEFAULT: filter_limit = settings.SIS_IMPORT_LIMIT['user']['high'] else: filter_limit = settings.SIS_IMPORT_LIMIT['user']['default'] pks = super(UserManager, self).get_query_set().filter( priority=priority, queue_id__isnull=True ).order_by( 'provisioned_date', 'added_date' ).values_list('pk', flat=True)[:filter_limit] if not len(pks): raise EmptyQueueException() imp = Import(priority=priority, csv_type='user') imp.save() # Mark the users as in process, and reset the priority super(UserManager, self).get_query_set().filter( pk__in=list(pks) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def queued(self, queue_id): return super(UserManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): kwargs = {'queue_id': None} if provisioned_date is not None: kwargs['provisioned_date'] = provisioned_date kwargs['priority'] = PRIORITY_DEFAULT self.queued(queue_id).update(**kwargs) class User(models.Model): """ Represents the provisioned state of a user. """ net_id = models.CharField(max_length=20, unique=True) reg_id = models.CharField(max_length=32, unique=True) added_date = models.DateTimeField(auto_now_add=True) provisioned_date = models.DateTimeField(null=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = UserManager() def json_data(self): return { "net_id": self.net_id, "reg_id": self.reg_id, "added_date": localtime(self.added_date).isoformat(), "provisioned_date": localtime( self.provisioned_date).isoformat() if ( self.provisioned_date is not None) else None, "priority": PRIORITY_CHOICES[self.priority][1], "queue_id": self.queue_id, } class GroupManager(models.Manager): def queue_by_priority(self, priority=PRIORITY_DEFAULT): filter_limit = settings.SIS_IMPORT_LIMIT['group']['default'] course_ids = super(GroupManager, self).get_query_set().filter( priority=priority, queue_id__isnull=True ).order_by( 'provisioned_date' ).values_list('course_id', flat=True)[:filter_limit] if not len(course_ids): raise EmptyQueueException() imp = Import(priority=priority, csv_type='group') imp.save() # Mark the groups as in process, and reset the priority super(GroupManager, self).get_query_set().filter( course_id__in=list(course_ids) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def queue_by_modified_date(self, modified_since): filter_limit = settings.SIS_IMPORT_LIMIT['group']['default'] groups = super(GroupManager, self).get_query_set().filter( queue_id__isnull=True ).order_by('-priority', 'provisioned_date') group_ids = set() course_ids = set() self._gws = GWS() for group in groups: if group.group_id not in group_ids: group_ids.add(group.group_id) mod_group_ids = [] if self._is_modified_group(group.group_id, modified_since): mod_group_ids.append(group.group_id) else: for membergroup in GroupMemberGroup.objects.filter( root_group_id=group.group_id, is_deleted__isnull=True): if self._is_modified_group(membergroup.group_id, modified_since): group_ids.add(membergroup.group_id) mod_group_ids.append(membergroup.group_id) mod_group_ids.append(group.group_id) break for mod_group_id in mod_group_ids: course_ids.update(set(groups.filter( group_id=mod_group_id ).values_list('course_id', flat=True))) if len(course_ids) >= filter_limit: break if not len(course_ids): raise EmptyQueueException() imp = Import(priority=PRIORITY_DEFAULT, csv_type='group') imp.save() # Mark the groups as in process, and reset the priority super(GroupManager, self).get_query_set().filter( course_id__in=list(course_ids) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def _is_modified_group(self, group_id, mtime): try: group = self._gws.get_group_by_id(group_id) return (group.membership_modified > mtime) except DataFailureException as err: if err.status == 404: # deleted group? return True else: raise def queued(self, queue_id): return super(GroupManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): kwargs = {'queue_id': None} if provisioned_date is not None: kwargs['provisioned_date'] = provisioned_date kwargs['priority'] = PRIORITY_DEFAULT self.queued(queue_id).update(**kwargs) class Group(models.Model): """ Represents the provisioned state of a course group """ course_id = models.CharField(max_length=80) group_id = models.CharField(max_length=256) role = models.CharField(max_length=80) added_by = models.CharField(max_length=20) added_date = models.DateTimeField(auto_now_add=True, null=True) is_deleted = models.NullBooleanField() deleted_by = models.CharField(max_length=20, null=True) deleted_date = models.DateTimeField(null=True) provisioned_date = models.DateTimeField(null=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = GroupManager() def json_data(self): return { "id": self.pk, "group_id": self.group_id, "course_id": self.course_id, "role": self.role, "added_by": self.added_by, "added_date": localtime(self.added_date).isoformat(), "is_deleted": True if self.is_deleted else None, "deleted_date": localtime(self.deleted_date).isoformat() if ( self.deleted_date is not None) else None, "provisioned_date": localtime( self.provisioned_date).isoformat() if ( self.provisioned_date is not None) else None, "priority": PRIORITY_CHOICES[self.priority][1], "queue_id": self.queue_id, } class Meta: unique_together = ('course_id', 'group_id', 'role') class GroupMemberGroup(models.Model): """ Represents member group relationship """ group_id = models.CharField(max_length=256) root_group_id = models.CharField(max_length=256) is_deleted = models.NullBooleanField() class CourseMemberManager(models.Manager): def queue_by_priority(self, priority=PRIORITY_DEFAULT): filter_limit = settings.SIS_IMPORT_LIMIT['coursemember']['default'] pks = super(CourseMemberManager, self).get_query_set().filter( priority=priority, queue_id__isnull=True ).values_list('pk', flat=True)[:filter_limit] if not len(pks): raise EmptyQueueException() imp = Import(priority=priority, csv_type='coursemember') imp.save() # Mark the coursemembers as in process, and reset the priority super(CourseMemberManager, self).get_query_set().filter( pk__in=list(pks) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def queued(self, queue_id): return super(CourseMemberManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): if provisioned_date is None: self.queued(queue_id).update(queue_id=None) else: super(CourseMemberManager, self).get_query_set().filter( queue_id=queue_id, priority=PRIORITY_DEFAULT ).update( priority=PRIORITY_NONE, queue_id=None ) super(CourseMemberManager, self).get_query_set().filter( queue_id=queue_id, priority=PRIORITY_HIGH ).update( priority=PRIORITY_DEFAULT, queue_id=None ) class CourseMember(models.Model): UWNETID_TYPE = "uwnetid" EPPN_TYPE = "eppn" TYPE_CHOICES = ( (UWNETID_TYPE, "UWNetID"), (EPPN_TYPE, "ePPN") ) course_id = models.CharField(max_length=80) name = models.CharField(max_length=256) member_type = models.SlugField(max_length=16, choices=TYPE_CHOICES) role = models.CharField(max_length=80) is_deleted = models.NullBooleanField() deleted_date = models.DateTimeField(null=True, blank=True) priority = models.SmallIntegerField(default=0, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = CourseMemberManager() def is_uwnetid(self): return self.member_type.lower() == self.UWNETID_TYPE def is_eppn(self): return self.member_type.lower() == self.EPPN_TYPE def __eq__(self, other): return (self.course_id == other.course_id and self.name.lower() == other.name.lower() and self.member_type.lower() == other.member_type.lower() and self.role.lower() == other.role.lower()) class CurriculumManager(models.Manager): def queued(self, queue_id): return super(CurriculumManager, self).get_query_set() def dequeue(self, queue_id, provisioned_date=None): pass class Curriculum(models.Model): """ Maps curricula to sub-account IDs """ curriculum_abbr = models.SlugField(max_length=20, unique=True) full_name = models.CharField(max_length=100) subaccount_id = models.CharField(max_length=100, unique=True) objects = CurriculumManager() class Import(models.Model): """ Represents a set of files that have been queued for import. """ CSV_TYPE_CHOICES = ( ('account', 'Curriculum'), ('user', 'User'), ('course', 'Course'), ('unused_course', 'Term'), ('coursemember', 'CourseMember'), ('enrollment', 'Enrollment'), ('group', 'Group'), ('eoscourse', 'EOSCourseDelta') ) csv_type = models.SlugField(max_length=20, choices=CSV_TYPE_CHOICES) csv_path = models.CharField(max_length=80, null=True) csv_errors = models.TextField(null=True) added_date = models.DateTimeField(auto_now_add=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) post_status = models.SmallIntegerField(max_length=3, null=True) monitor_date = models.DateTimeField(null=True) monitor_status = models.SmallIntegerField(max_length=3, null=True) canvas_id = models.CharField(max_length=30, null=True) canvas_state = models.CharField(max_length=80, null=True) canvas_progress = models.SmallIntegerField(max_length=3, default=0) canvas_errors = models.TextField(null=True) def json_data(self): return { "queue_id": self.pk, "type": self.csv_type, "type_name": self.get_csv_type_display(), "added_date": localtime(self.added_date).isoformat(), "priority": PRIORITY_CHOICES[self.priority][1], "csv_errors": self.csv_errors, "post_status": self.post_status, "canvas_state": self.canvas_state, "canvas_progress": self.canvas_progress, "canvas_errors": self.canvas_errors, } def import_csv(self): """ Imports all csv files for the passed import object, as a zipped archive. """ if not self.csv_path: raise MissingImportPathException() try: sis_import = SISImport().import_dir(self.csv_path) self.post_status = 200 self.canvas_id = sis_import.import_id self.canvas_state = sis_import.workflow_state except DataFailureException as ex: self.post_status = ex.status self.canvas_errors = ex except Exception as ex: self.canvas_errors = ex self.save() def update_import_status(self): """ Updates import attributes, based on the sis import resource. """ if (self.canvas_id and self.post_status == 200 and (self.canvas_errors is None or self.monitor_status in [500, 503, 504])): self.monitor_date = datetime.datetime.utcnow().replace(tzinfo=utc) try: sis_import = SISImport().get_import_status( SISImportModel(import_id=str(self.canvas_id))) self.monitor_status = 200 self.canvas_errors = None self.canvas_state = sis_import.workflow_state self.canvas_progress = sis_import.progress if len(sis_import.processing_warnings): canvas_errors = json.dumps(sis_import.processing_warnings) self.canvas_errors = canvas_errors except DataFailureException as ex: self.monitor_status = ex.status self.canvas_errors = ex if self.is_cleanly_imported(): self.delete() else: self.save() if self.is_imported(): self.dequeue_dependent_models() def is_completed(self): return (self.post_status == 200 and self.canvas_progress == 100) def is_cleanly_imported(self): return (self.is_completed() and self.canvas_state == 'imported') def is_imported(self): return (self.is_completed() and re.match(r'^imported', self.canvas_state) is not None) def dependent_model(self): return globals()[self.get_csv_type_display()] def queued_objects(self): return self.dependent_model().objects.queued(self.pk) def dequeue_dependent_models(self): provisioned_date = self.monitor_date if self.is_imported() else None if self.csv_type != 'user' and self.csv_type != 'account': User.objects.dequeue(self.pk, provisioned_date) self.dependent_model().objects.dequeue(self.pk, provisioned_date) def delete(self, *args, **kwargs): self.dequeue_dependent_models() return super(Import, self).delete(*args, **kwargs) class SubAccountOverride(models.Model): course_id = models.CharField(max_length=80) subaccount_id = models.CharField(max_length=100) reference_date = models.DateTimeField(auto_now_add=True) class TermOverride(models.Model): course_id = models.CharField(max_length=80) term_sis_id = models.CharField(max_length=24) term_name = models.CharField(max_length=24) reference_date = models.DateTimeField(auto_now_add=True) drops invalid max_length from django.db import models from django.conf import settings from django.utils.timezone import utc, localtime from restclients.canvas.sis_import import SISImport from restclients.models.canvas import SISImport as SISImportModel from restclients.gws import GWS from restclients.exceptions import DataFailureException from eos.models import EOSCourseDelta import datetime import json import re PRIORITY_NONE = 0 PRIORITY_DEFAULT = 1 PRIORITY_HIGH = 2 PRIORITY_IMMEDIATE = 3 PRIORITY_CHOICES = ( (PRIORITY_NONE, 'none'), (PRIORITY_DEFAULT, 'normal'), (PRIORITY_HIGH, 'high'), (PRIORITY_IMMEDIATE, 'immediate') ) class EmptyQueueException(Exception): pass class MissingImportPathException(Exception): pass class Job(models.Model): """ Represents provisioning commands. """ name = models.CharField(max_length=128) title = models.CharField(max_length=128) changed_by = models.CharField(max_length=32) changed_date = models.DateTimeField() last_run_date = models.DateTimeField(null=True) is_active = models.NullBooleanField() health_status = models.CharField(max_length=512, null=True) last_status_date = models.DateTimeField(null=True) def json_data(self): return { 'job_id': self.pk, 'name': self.name, 'title': self.title, 'changed_by': self.changed_by, 'changed_date': localtime(self.changed_date).isoformat() if ( self.changed_date is not None) else None, 'last_run_date': localtime(self.last_run_date).isoformat() if ( self.last_run_date is not None) else None, 'is_active': self.is_active, 'health_status': self.health_status, 'last_status_date': localtime( self.last_status_date).isoformat() if ( self.last_status_date is not None) else None, } class TermManager(models.Manager): def queue_unused_courses(self, term_id): try: term = Term.objects.get(term_id=term_id) if (term.deleted_unused_courses_date is not None or term.queue_id is not None): raise EmptyQueueException() except Term.DoesNotExist: term = Term(term_id=term_id) term.save() imp = Import(priority=PRIORITY_DEFAULT, csv_type='unused_course') imp.save() term.queue_id = imp.pk term.save() return imp def queued(self, queue_id): return super(TermManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): kwargs = {'queue_id': None} if provisioned_date is not None: # Currently only handles the 'unused_course' type kwargs['deleted_unused_courses_date'] = provisioned_date self.queued(queue_id).update(**kwargs) class Term(models.Model): """ Represents the provisioned state of courses for a term. """ term_id = models.CharField(max_length=20, unique=True) added_date = models.DateTimeField(auto_now_add=True) last_course_search_date = models.DateTimeField(null=True) courses_changed_since_date = models.DateTimeField(null=True) deleted_unused_courses_date = models.DateTimeField(null=True) queue_id = models.CharField(max_length=30, null=True) objects = TermManager() class CourseManager(models.Manager): def get_linked_course_ids(self, course_id): return super(CourseManager, self).get_query_set().filter( primary_id=course_id).values_list('course_id', flat=True) def get_joint_course_ids(self, course_id): return super(CourseManager, self).get_query_set().filter( xlist_id=course_id).exclude(course_id=course_id).values_list( 'course_id', flat=True) def queue_by_priority(self, priority=PRIORITY_DEFAULT): if priority > PRIORITY_DEFAULT: filter_limit = settings.SIS_IMPORT_LIMIT['course']['high'] else: filter_limit = settings.SIS_IMPORT_LIMIT['course']['default'] pks = super(CourseManager, self).get_query_set().filter( priority=priority, course_type=Course.SDB_TYPE, queue_id__isnull=True, provisioned_error__isnull=True ).order_by( 'provisioned_date', 'added_date' ).values_list('pk', flat=True)[:filter_limit] if not len(pks): raise EmptyQueueException() imp = Import(priority=priority, csv_type='course') imp.save() # Mark the courses as in process, and reset the priority super(CourseManager, self).get_query_set().filter( pk__in=list(pks) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def queued(self, queue_id): return super(CourseManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): kwargs = {'queue_id': None} if provisioned_date is not None: kwargs['provisioned_date'] = provisioned_date kwargs['priority'] = PRIORITY_DEFAULT self.queued(queue_id).update(**kwargs) class Course(models.Model): """ Represents the provisioned state of a course. """ SDB_TYPE = 'sdb' ADHOC_TYPE = 'adhoc' TYPE_CHOICES = ((SDB_TYPE, 'SDB'), (ADHOC_TYPE, 'Ad Hoc')) course_id = models.CharField(max_length=80, unique=True) course_type = models.CharField(max_length=16, choices=TYPE_CHOICES) term_id = models.CharField(max_length=20, db_index=True) primary_id = models.CharField(max_length=80, null=True) xlist_id = models.CharField(max_length=80, null=True) added_date = models.DateTimeField(auto_now_add=True) provisioned_date = models.DateTimeField(null=True) provisioned_error = models.NullBooleanField() provisioned_status = models.CharField(max_length=512, null=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = CourseManager() def is_sdb(self): return self.course_type == self.SDB_TYPE def is_adhoc(self): return self.course_type == self.ADHOC_TYPE def sws_url(self): try: (year, quarter, curr_abbr, course_num, section_id) = self.course_id.split('-', 4) sws_url = "%s/%s,%s,%s,%s/%s.json" % ( "/restclients/view/sws/student/v5/course", year, quarter, curr_abbr, course_num, section_id) except ValueError: sws_url = None return sws_url def json_data(self, include_sws_url=False): try: group_models = Group.objects.filter(course_id=self.course_id, is_deleted__isnull=True) groups = list(group_models.values_list("group_id", flat=True)) except Group.DoesNotExist: groups = [] return { "course_id": self.course_id, "term_id": self.term_id, "xlist_id": self.xlist_id, "is_sdb_type": self.is_sdb(), "added_date": localtime(self.added_date).isoformat() if ( self.added_date is not None) else None, "provisioned_date": localtime( self.provisioned_date).isoformat() if ( self.provisioned_date is not None) else None, "priority": PRIORITY_CHOICES[self.priority][1], "provisioned_error": self.provisioned_error, "provisioned_status": self.provisioned_status, "queue_id": self.queue_id, "groups": groups, "sws_url": self.sws_url() if ( include_sws_url and self.is_sdb()) else None, } class EnrollmentManager(models.Manager): def queue_by_priority(self, priority=PRIORITY_DEFAULT): filter_limit = settings.SIS_IMPORT_LIMIT['enrollment']['default'] pks = super(EnrollmentManager, self).get_query_set().filter( priority=priority, queue_id__isnull=True ).order_by( 'last_modified' ).values_list('pk', flat=True)[:filter_limit] if not len(pks): raise EmptyQueueException() imp = Import(priority=priority, csv_type='enrollment') imp.save() # Mark the enrollments as in process super(EnrollmentManager, self).get_query_set().filter( pk__in=list(pks) ).update(queue_id=imp.pk) return imp def queued(self, queue_id): return super(EnrollmentManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): if provisioned_date is None: self.queued(queue_id).update(queue_id=None) else: super(EnrollmentManager, self).get_query_set().filter( queue_id=queue_id, priority=PRIORITY_DEFAULT ).update( priority=PRIORITY_NONE, queue_id=None ) super(EnrollmentManager, self).get_query_set().filter( queue_id=queue_id, priority=PRIORITY_HIGH ).update( priority=PRIORITY_DEFAULT, queue_id=None ) class Enrollment(models.Model): """ Represents the provisioned state of an enrollment. """ ACTIVE_STATUS = "active" INACTIVE_STATUS = "inactive" DELETED_STATUS = "deleted" COMPLETED_STATUS = "completed" STATUS_CHOICES = ( (ACTIVE_STATUS, "Active"), (INACTIVE_STATUS, "Inactive"), (DELETED_STATUS, "Deleted"), (COMPLETED_STATUS, "Completed") ) STUDENT_ROLE = "Student" AUDITOR_ROLE = "Auditor" INSTRUCTOR_ROLE = "Teacher" reg_id = models.CharField(max_length=32, null=True) status = models.CharField(max_length=16, choices=STATUS_CHOICES) course_id = models.CharField(max_length=80) last_modified = models.DateTimeField() primary_course_id = models.CharField(max_length=80, null=True) instructor_reg_id = models.CharField(max_length=32, null=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = EnrollmentManager() def is_active(self): return self.status == self.ACTIVE_STATUS def json_data(self): return { "reg_id": self.reg_id, "status": self.status, "course_id": self.course_id, "last_modified": localtime(self.last_modified).isoformat() if ( self.last_modified is not None) else None, "primary_course_id": self.primary_course_id, "instructor_reg_id": self.instructor_reg_id, "priority": PRIORITY_CHOICES[self.priority][1], "queue_id": self.queue_id, } class Meta: unique_together = ("course_id", "reg_id") class UserManager(models.Manager): def queue_by_priority(self, priority=PRIORITY_DEFAULT): if priority > PRIORITY_DEFAULT: filter_limit = settings.SIS_IMPORT_LIMIT['user']['high'] else: filter_limit = settings.SIS_IMPORT_LIMIT['user']['default'] pks = super(UserManager, self).get_query_set().filter( priority=priority, queue_id__isnull=True ).order_by( 'provisioned_date', 'added_date' ).values_list('pk', flat=True)[:filter_limit] if not len(pks): raise EmptyQueueException() imp = Import(priority=priority, csv_type='user') imp.save() # Mark the users as in process, and reset the priority super(UserManager, self).get_query_set().filter( pk__in=list(pks) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def queued(self, queue_id): return super(UserManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): kwargs = {'queue_id': None} if provisioned_date is not None: kwargs['provisioned_date'] = provisioned_date kwargs['priority'] = PRIORITY_DEFAULT self.queued(queue_id).update(**kwargs) class User(models.Model): """ Represents the provisioned state of a user. """ net_id = models.CharField(max_length=20, unique=True) reg_id = models.CharField(max_length=32, unique=True) added_date = models.DateTimeField(auto_now_add=True) provisioned_date = models.DateTimeField(null=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = UserManager() def json_data(self): return { "net_id": self.net_id, "reg_id": self.reg_id, "added_date": localtime(self.added_date).isoformat(), "provisioned_date": localtime( self.provisioned_date).isoformat() if ( self.provisioned_date is not None) else None, "priority": PRIORITY_CHOICES[self.priority][1], "queue_id": self.queue_id, } class GroupManager(models.Manager): def queue_by_priority(self, priority=PRIORITY_DEFAULT): filter_limit = settings.SIS_IMPORT_LIMIT['group']['default'] course_ids = super(GroupManager, self).get_query_set().filter( priority=priority, queue_id__isnull=True ).order_by( 'provisioned_date' ).values_list('course_id', flat=True)[:filter_limit] if not len(course_ids): raise EmptyQueueException() imp = Import(priority=priority, csv_type='group') imp.save() # Mark the groups as in process, and reset the priority super(GroupManager, self).get_query_set().filter( course_id__in=list(course_ids) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def queue_by_modified_date(self, modified_since): filter_limit = settings.SIS_IMPORT_LIMIT['group']['default'] groups = super(GroupManager, self).get_query_set().filter( queue_id__isnull=True ).order_by('-priority', 'provisioned_date') group_ids = set() course_ids = set() self._gws = GWS() for group in groups: if group.group_id not in group_ids: group_ids.add(group.group_id) mod_group_ids = [] if self._is_modified_group(group.group_id, modified_since): mod_group_ids.append(group.group_id) else: for membergroup in GroupMemberGroup.objects.filter( root_group_id=group.group_id, is_deleted__isnull=True): if self._is_modified_group(membergroup.group_id, modified_since): group_ids.add(membergroup.group_id) mod_group_ids.append(membergroup.group_id) mod_group_ids.append(group.group_id) break for mod_group_id in mod_group_ids: course_ids.update(set(groups.filter( group_id=mod_group_id ).values_list('course_id', flat=True))) if len(course_ids) >= filter_limit: break if not len(course_ids): raise EmptyQueueException() imp = Import(priority=PRIORITY_DEFAULT, csv_type='group') imp.save() # Mark the groups as in process, and reset the priority super(GroupManager, self).get_query_set().filter( course_id__in=list(course_ids) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def _is_modified_group(self, group_id, mtime): try: group = self._gws.get_group_by_id(group_id) return (group.membership_modified > mtime) except DataFailureException as err: if err.status == 404: # deleted group? return True else: raise def queued(self, queue_id): return super(GroupManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): kwargs = {'queue_id': None} if provisioned_date is not None: kwargs['provisioned_date'] = provisioned_date kwargs['priority'] = PRIORITY_DEFAULT self.queued(queue_id).update(**kwargs) class Group(models.Model): """ Represents the provisioned state of a course group """ course_id = models.CharField(max_length=80) group_id = models.CharField(max_length=256) role = models.CharField(max_length=80) added_by = models.CharField(max_length=20) added_date = models.DateTimeField(auto_now_add=True, null=True) is_deleted = models.NullBooleanField() deleted_by = models.CharField(max_length=20, null=True) deleted_date = models.DateTimeField(null=True) provisioned_date = models.DateTimeField(null=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = GroupManager() def json_data(self): return { "id": self.pk, "group_id": self.group_id, "course_id": self.course_id, "role": self.role, "added_by": self.added_by, "added_date": localtime(self.added_date).isoformat(), "is_deleted": True if self.is_deleted else None, "deleted_date": localtime(self.deleted_date).isoformat() if ( self.deleted_date is not None) else None, "provisioned_date": localtime( self.provisioned_date).isoformat() if ( self.provisioned_date is not None) else None, "priority": PRIORITY_CHOICES[self.priority][1], "queue_id": self.queue_id, } class Meta: unique_together = ('course_id', 'group_id', 'role') class GroupMemberGroup(models.Model): """ Represents member group relationship """ group_id = models.CharField(max_length=256) root_group_id = models.CharField(max_length=256) is_deleted = models.NullBooleanField() class CourseMemberManager(models.Manager): def queue_by_priority(self, priority=PRIORITY_DEFAULT): filter_limit = settings.SIS_IMPORT_LIMIT['coursemember']['default'] pks = super(CourseMemberManager, self).get_query_set().filter( priority=priority, queue_id__isnull=True ).values_list('pk', flat=True)[:filter_limit] if not len(pks): raise EmptyQueueException() imp = Import(priority=priority, csv_type='coursemember') imp.save() # Mark the coursemembers as in process, and reset the priority super(CourseMemberManager, self).get_query_set().filter( pk__in=list(pks) ).update( priority=PRIORITY_DEFAULT, queue_id=imp.pk ) return imp def queued(self, queue_id): return super(CourseMemberManager, self).get_query_set().filter( queue_id=queue_id) def dequeue(self, queue_id, provisioned_date=None): if provisioned_date is None: self.queued(queue_id).update(queue_id=None) else: super(CourseMemberManager, self).get_query_set().filter( queue_id=queue_id, priority=PRIORITY_DEFAULT ).update( priority=PRIORITY_NONE, queue_id=None ) super(CourseMemberManager, self).get_query_set().filter( queue_id=queue_id, priority=PRIORITY_HIGH ).update( priority=PRIORITY_DEFAULT, queue_id=None ) class CourseMember(models.Model): UWNETID_TYPE = "uwnetid" EPPN_TYPE = "eppn" TYPE_CHOICES = ( (UWNETID_TYPE, "UWNetID"), (EPPN_TYPE, "ePPN") ) course_id = models.CharField(max_length=80) name = models.CharField(max_length=256) member_type = models.SlugField(max_length=16, choices=TYPE_CHOICES) role = models.CharField(max_length=80) is_deleted = models.NullBooleanField() deleted_date = models.DateTimeField(null=True, blank=True) priority = models.SmallIntegerField(default=0, choices=PRIORITY_CHOICES) queue_id = models.CharField(max_length=30, null=True) objects = CourseMemberManager() def is_uwnetid(self): return self.member_type.lower() == self.UWNETID_TYPE def is_eppn(self): return self.member_type.lower() == self.EPPN_TYPE def __eq__(self, other): return (self.course_id == other.course_id and self.name.lower() == other.name.lower() and self.member_type.lower() == other.member_type.lower() and self.role.lower() == other.role.lower()) class CurriculumManager(models.Manager): def queued(self, queue_id): return super(CurriculumManager, self).get_query_set() def dequeue(self, queue_id, provisioned_date=None): pass class Curriculum(models.Model): """ Maps curricula to sub-account IDs """ curriculum_abbr = models.SlugField(max_length=20, unique=True) full_name = models.CharField(max_length=100) subaccount_id = models.CharField(max_length=100, unique=True) objects = CurriculumManager() class Import(models.Model): """ Represents a set of files that have been queued for import. """ CSV_TYPE_CHOICES = ( ('account', 'Curriculum'), ('user', 'User'), ('course', 'Course'), ('unused_course', 'Term'), ('coursemember', 'CourseMember'), ('enrollment', 'Enrollment'), ('group', 'Group'), ('eoscourse', 'EOSCourseDelta') ) csv_type = models.SlugField(max_length=20, choices=CSV_TYPE_CHOICES) csv_path = models.CharField(max_length=80, null=True) csv_errors = models.TextField(null=True) added_date = models.DateTimeField(auto_now_add=True) priority = models.SmallIntegerField(default=1, choices=PRIORITY_CHOICES) post_status = models.SmallIntegerField(null=True) monitor_date = models.DateTimeField(null=True) monitor_status = models.SmallIntegerField(null=True) canvas_id = models.CharField(max_length=30, null=True) canvas_state = models.CharField(max_length=80, null=True) canvas_progress = models.SmallIntegerField(default=0) canvas_errors = models.TextField(null=True) def json_data(self): return { "queue_id": self.pk, "type": self.csv_type, "type_name": self.get_csv_type_display(), "added_date": localtime(self.added_date).isoformat(), "priority": PRIORITY_CHOICES[self.priority][1], "csv_errors": self.csv_errors, "post_status": self.post_status, "canvas_state": self.canvas_state, "canvas_progress": self.canvas_progress, "canvas_errors": self.canvas_errors, } def import_csv(self): """ Imports all csv files for the passed import object, as a zipped archive. """ if not self.csv_path: raise MissingImportPathException() try: sis_import = SISImport().import_dir(self.csv_path) self.post_status = 200 self.canvas_id = sis_import.import_id self.canvas_state = sis_import.workflow_state except DataFailureException as ex: self.post_status = ex.status self.canvas_errors = ex except Exception as ex: self.canvas_errors = ex self.save() def update_import_status(self): """ Updates import attributes, based on the sis import resource. """ if (self.canvas_id and self.post_status == 200 and (self.canvas_errors is None or self.monitor_status in [500, 503, 504])): self.monitor_date = datetime.datetime.utcnow().replace(tzinfo=utc) try: sis_import = SISImport().get_import_status( SISImportModel(import_id=str(self.canvas_id))) self.monitor_status = 200 self.canvas_errors = None self.canvas_state = sis_import.workflow_state self.canvas_progress = sis_import.progress if len(sis_import.processing_warnings): canvas_errors = json.dumps(sis_import.processing_warnings) self.canvas_errors = canvas_errors except DataFailureException as ex: self.monitor_status = ex.status self.canvas_errors = ex if self.is_cleanly_imported(): self.delete() else: self.save() if self.is_imported(): self.dequeue_dependent_models() def is_completed(self): return (self.post_status == 200 and self.canvas_progress == 100) def is_cleanly_imported(self): return (self.is_completed() and self.canvas_state == 'imported') def is_imported(self): return (self.is_completed() and re.match(r'^imported', self.canvas_state) is not None) def dependent_model(self): return globals()[self.get_csv_type_display()] def queued_objects(self): return self.dependent_model().objects.queued(self.pk) def dequeue_dependent_models(self): provisioned_date = self.monitor_date if self.is_imported() else None if self.csv_type != 'user' and self.csv_type != 'account': User.objects.dequeue(self.pk, provisioned_date) self.dependent_model().objects.dequeue(self.pk, provisioned_date) def delete(self, *args, **kwargs): self.dequeue_dependent_models() return super(Import, self).delete(*args, **kwargs) class SubAccountOverride(models.Model): course_id = models.CharField(max_length=80) subaccount_id = models.CharField(max_length=100) reference_date = models.DateTimeField(auto_now_add=True) class TermOverride(models.Model): course_id = models.CharField(max_length=80) term_sis_id = models.CharField(max_length=24) term_name = models.CharField(max_length=24) reference_date = models.DateTimeField(auto_now_add=True)
from __future__ import absolute_import, print_function import os import sys import json import errno import socket import signal import logging import logging.config import warnings import threading import traceback import multiprocessing from time import sleep from kuyruk import importer, signals from kuyruk.task import get_queue_name from kuyruk.exceptions import Reject, Discard, ConnectionError logger = logging.getLogger(__name__) class Worker(object): """Consumes tasks from a queue and runs them. :param app: An instance of :class:`~kuyruk.Kuyruk` :param args: Command line arguments """ def __init__(self, app, args): self.kuyruk = app if not args.queues: raise ValueError("no queue given") self.queues = [get_queue_name(q, local=args.local) for q in args.queues] self.shutdown_pending = threading.Event() self._pause = False self._started = None self.consuming = False self._current_message = None self.current_task = None self.current_args = None self.current_kwargs = None self._heartbeat_exc_info = None if self.config.WORKER_MAX_LOAD is None: self.config.WORKER_MAX_LOAD = multiprocessing.cpu_count() self._pid = os.getpid() self._hostname = socket.gethostname() signals.worker_init.send(self.kuyruk, worker=self) @property def queue(self): warnings.warn("Worker.queue is deprecated. Use Worker.queues instead.") return self.queues[0] @property def config(self): return self.kuyruk.config def run(self): """Runs the worker and consumes messages from RabbitMQ. Returns only after `shutdown()` is called. """ # Lazy import setproctitle. # There is bug with the latest version of Python with # uWSGI and setproctitle combination. # Watch: https://github.com/unbit/uwsgi/issues/1030 from setproctitle import setproctitle setproctitle("kuyruk: worker on %s" % ','.join(self.queues)) self._setup_logging() signal.signal(signal.SIGINT, self._handle_sigint) signal.signal(signal.SIGTERM, self._handle_sigterm) signal.signal(signal.SIGHUP, self._handle_sighup) signal.signal(signal.SIGUSR1, self._handle_sigusr1) signal.signal(signal.SIGUSR2, self._handle_sigusr2) self._started = os.times()[4] for f in (self._watch_load, self._shutdown_timer): t = threading.Thread(target=f) t.daemon = True t.start() signals.worker_start.send(self.kuyruk, worker=self) self._consume_messages() signals.worker_shutdown.send(self.kuyruk, worker=self) logger.debug("End run worker") def _setup_logging(self): if self.config.WORKER_LOGGING_CONFIG: logging.config.fileConfig(self.config.WORKER_LOGGING_CONFIG) else: level = getattr(logging, self.config.WORKER_LOGGING_LEVEL.upper()) fmt = "%(levelname).1s " \ "%(name)s.%(funcName)s:%(lineno)d - %(message)s" logging.basicConfig(level=level, format=fmt) def _consume_messages(self): with self.kuyruk.channel() as ch: # Set prefetch count to 1. If we don't set this, RabbitMQ keeps # sending messages while we are already working on a message. ch.basic_qos(0, 1, True) self._declare_queues(ch) while not self.shutdown_pending.is_set(): # Consume or pause if self._pause and self.consuming: self._cancel_queues(ch) logger.info('Consumer cancelled') self.consuming = False elif not self._pause and not self.consuming: self._consume_queues(ch) logger.info('Consumer started') self.consuming = True if self._heartbeat_exc_info: break try: ch.connection.send_heartbeat() ch.connection.drain_events(timeout=1) except socket.error as e: if isinstance(e, socket.timeout): pass elif e.errno == errno.EINTR: pass # happens when the process receives a signal else: raise logger.debug("End run worker") def _consumer_tag(self, queue): return "%s:%s@%s" % (queue, self._pid, self._hostname) def _declare_queues(self, ch): for queue in self.queues: logger.debug("queue_declare: %s", queue) ch.queue_declare( queue=queue, durable=True, auto_delete=False) def _consume_queues(self, ch): for queue in self.queues: logger.debug("basic_consume: %s", queue) ch.basic_consume(queue=queue, consumer_tag=self._consumer_tag(queue), callback=self._process_message) def _cancel_queues(self, ch): for queue in self.queues: logger.debug("basic_cancel: %s", queue) ch.basic_cancel(self._consumer_tag(queue)) def _process_message(self, message): """Processes the message received from the queue.""" try: description = json.loads(message.body) except Exception: message.channel.basic_reject(message.delivery_tag, requeue=False) logger.error("Cannot decode message. Dropping.") else: logger.info("Processing task: %r", description) self._process_description(message, description) def _process_description(self, message, description): try: task = importer.import_object(description['module'], description['function']) args, kwargs = description['args'], description['kwargs'] except Exception: logger.error('Cannot import task') exc_info = sys.exc_info() signals.worker_failure.send(self.kuyruk, description=description, exc_info=exc_info, worker=self) message.channel.basic_reject(message.delivery_tag, requeue=False) else: self._process_task(message, description, task, args, kwargs) def _process_task(self, message, description, task, args, kwargs): try: self._current_message = message self.current_task = task self.current_args = args self.current_kwargs = kwargs stop_heartbeat = threading.Event() heartbeat_thread = threading.Thread( target=self._heartbeat_tick, args=(message.channel.connection, stop_heartbeat)) heartbeat_thread.start() try: task.apply(*args, **kwargs) finally: self._current_message = None self.current_task = None self.current_args = None self.current_kwargs = None stop_heartbeat.set() heartbeat_thread.join() except Reject: logger.warning('Task is rejected') sleep(1) # Prevent cpu burning message.channel.basic_reject(message.delivery_tag, requeue=True) except Discard: logger.warning('Task is discarded') message.channel.basic_reject(message.delivery_tag, requeue=False) except ConnectionError: pass except Exception: logger.error('Task raised an exception') exc_info = sys.exc_info() logger.error(''.join(traceback.format_exception(*exc_info))) signals.worker_failure.send(self.kuyruk, description=description, task=task, args=args, kwargs=kwargs, exc_info=exc_info, worker=self) message.channel.basic_reject(message.delivery_tag, requeue=False) else: logger.info('Task is successful') message.channel.basic_ack(message.delivery_tag) finally: logger.debug("Task is processed") def _watch_load(self): """Pause consuming messages if lood goes above the allowed limit.""" while not self.shutdown_pending.is_set(): load = os.getloadavg()[0] if load > self.config.WORKER_MAX_LOAD: if self._pause is False: logger.warning( 'Load is above the treshold (%.2f/%s), ' 'pausing consumer', load, self.config.WORKER_MAX_LOAD) self._pause = True else: if self._pause is True: logger.warning( 'Load is below the treshold (%.2f/%s), ' 'resuming consumer', load, self.config.WORKER_MAX_LOAD) self._pause = False sleep(1) @property def uptime(self): if self._started is not None: return os.times()[4] - self._started def _shutdown_timer(self): """Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown gracefully. """ if not self.config.WORKER_MAX_RUN_TIME: return while not self.shutdown_pending.is_set(): remaining = self.config.WORKER_MAX_RUN_TIME - self.uptime if remaining > 0: sleep(remaining) else: logger.warning('Run time reached zero') self.shutdown() break def shutdown(self): """Exits after the current task is finished.""" logger.warning("Shutdown requested") self.shutdown_pending.set() def _handle_sigint(self, signum, frame): """Shutdown after processing current task.""" logger.warning("Catched SIGINT") self.shutdown() def _handle_sigterm(self, signum, frame): """Shutdown after processing current task.""" logger.warning("Catched SIGTERM") self.shutdown() def _handle_sighup(self, signum, frame): """Used internally to fail the task when connection to RabbitMQ is lost during the execution of the task. """ logger.warning("Catched SIGHUP") raise ConnectionError(self._heartbeat_exc_info) @staticmethod def _handle_sigusr1(signum, frame): """Print stacktrace.""" print('=' * 70) print(''.join(traceback.format_stack())) print('-' * 70) def _handle_sigusr2(self, signum, frame): """Drop current task.""" logger.warning("Catched SIGUSR2") if self._current_message: logger.warning("Dropping current task...") raise Discard def drop_task(self): os.kill(os.getpid(), signal.SIGUSR2) def _heartbeat_tick(self, connection, stop_event): while not stop_event.wait(1): try: connection.send_heartbeat() except socket.timeout: pass except Exception as e: logger.error(e) self._heartbeat_exc_info = sys.exc_info() os.kill(os.getpid(), signal.SIGHUP) break fix shutdown bug Worker exits from the consume loop when shutdown is requested. When the loop is exited the channel is closed amqp library calls drain_events method. There may be received messages but since the channel is closed we cannot process them. from __future__ import absolute_import, print_function import os import sys import json import errno import socket import signal import logging import logging.config import warnings import threading import traceback import multiprocessing from time import sleep from kuyruk import importer, signals from kuyruk.task import get_queue_name from kuyruk.exceptions import Reject, Discard, ConnectionError logger = logging.getLogger(__name__) class Worker(object): """Consumes tasks from a queue and runs them. :param app: An instance of :class:`~kuyruk.Kuyruk` :param args: Command line arguments """ def __init__(self, app, args): self.kuyruk = app if not args.queues: raise ValueError("no queue given") self.queues = [get_queue_name(q, local=args.local) for q in args.queues] self.shutdown_pending = threading.Event() self._pause = False self._started = None self.consuming = False self._current_message = None self.current_task = None self.current_args = None self.current_kwargs = None self._heartbeat_exc_info = None if self.config.WORKER_MAX_LOAD is None: self.config.WORKER_MAX_LOAD = multiprocessing.cpu_count() self._pid = os.getpid() self._hostname = socket.gethostname() signals.worker_init.send(self.kuyruk, worker=self) @property def queue(self): warnings.warn("Worker.queue is deprecated. Use Worker.queues instead.") return self.queues[0] @property def config(self): return self.kuyruk.config def run(self): """Runs the worker and consumes messages from RabbitMQ. Returns only after `shutdown()` is called. """ # Lazy import setproctitle. # There is bug with the latest version of Python with # uWSGI and setproctitle combination. # Watch: https://github.com/unbit/uwsgi/issues/1030 from setproctitle import setproctitle setproctitle("kuyruk: worker on %s" % ','.join(self.queues)) self._setup_logging() signal.signal(signal.SIGINT, self._handle_sigint) signal.signal(signal.SIGTERM, self._handle_sigterm) signal.signal(signal.SIGHUP, self._handle_sighup) signal.signal(signal.SIGUSR1, self._handle_sigusr1) signal.signal(signal.SIGUSR2, self._handle_sigusr2) self._started = os.times()[4] for f in (self._watch_load, self._shutdown_timer): t = threading.Thread(target=f) t.daemon = True t.start() signals.worker_start.send(self.kuyruk, worker=self) self._consume_messages() signals.worker_shutdown.send(self.kuyruk, worker=self) logger.debug("End run worker") def _setup_logging(self): if self.config.WORKER_LOGGING_CONFIG: logging.config.fileConfig(self.config.WORKER_LOGGING_CONFIG) else: level = getattr(logging, self.config.WORKER_LOGGING_LEVEL.upper()) fmt = "%(levelname).1s " \ "%(name)s.%(funcName)s:%(lineno)d - %(message)s" logging.basicConfig(level=level, format=fmt) def _consume_messages(self): with self.kuyruk.channel() as ch: # Set prefetch count to 1. If we don't set this, RabbitMQ keeps # sending messages while we are already working on a message. ch.basic_qos(0, 1, True) self._declare_queues(ch) while not self.shutdown_pending.is_set(): # Consume or pause if self._pause and self.consuming: self._cancel_queues(ch) logger.info('Consumer cancelled') self.consuming = False elif not self._pause and not self.consuming: self._consume_queues(ch) logger.info('Consumer started') self.consuming = True if self._heartbeat_exc_info: break try: ch.connection.send_heartbeat() ch.connection.drain_events(timeout=1) except socket.error as e: if isinstance(e, socket.timeout): pass elif e.errno == errno.EINTR: pass # happens when the process receives a signal else: raise logger.debug("End run worker") def _consumer_tag(self, queue): return "%s:%s@%s" % (queue, self._pid, self._hostname) def _declare_queues(self, ch): for queue in self.queues: logger.debug("queue_declare: %s", queue) ch.queue_declare( queue=queue, durable=True, auto_delete=False) def _consume_queues(self, ch): for queue in self.queues: logger.debug("basic_consume: %s", queue) ch.basic_consume(queue=queue, consumer_tag=self._consumer_tag(queue), callback=self._process_message) def _cancel_queues(self, ch): for queue in self.queues: logger.debug("basic_cancel: %s", queue) ch.basic_cancel(self._consumer_tag(queue)) def _process_message(self, message): """Processes the message received from the queue.""" if self.shutdown_pending.is_set(): return try: description = json.loads(message.body) except Exception: message.channel.basic_reject(message.delivery_tag, requeue=False) logger.error("Cannot decode message. Dropping.") else: logger.info("Processing task: %r", description) self._process_description(message, description) def _process_description(self, message, description): try: task = importer.import_object(description['module'], description['function']) args, kwargs = description['args'], description['kwargs'] except Exception: logger.error('Cannot import task') exc_info = sys.exc_info() signals.worker_failure.send(self.kuyruk, description=description, exc_info=exc_info, worker=self) message.channel.basic_reject(message.delivery_tag, requeue=False) else: self._process_task(message, description, task, args, kwargs) def _process_task(self, message, description, task, args, kwargs): try: self._current_message = message self.current_task = task self.current_args = args self.current_kwargs = kwargs stop_heartbeat = threading.Event() heartbeat_thread = threading.Thread( target=self._heartbeat_tick, args=(message.channel.connection, stop_heartbeat)) heartbeat_thread.start() try: task.apply(*args, **kwargs) finally: self._current_message = None self.current_task = None self.current_args = None self.current_kwargs = None stop_heartbeat.set() heartbeat_thread.join() except Reject: logger.warning('Task is rejected') sleep(1) # Prevent cpu burning message.channel.basic_reject(message.delivery_tag, requeue=True) except Discard: logger.warning('Task is discarded') message.channel.basic_reject(message.delivery_tag, requeue=False) except ConnectionError: pass except Exception: logger.error('Task raised an exception') exc_info = sys.exc_info() logger.error(''.join(traceback.format_exception(*exc_info))) signals.worker_failure.send(self.kuyruk, description=description, task=task, args=args, kwargs=kwargs, exc_info=exc_info, worker=self) message.channel.basic_reject(message.delivery_tag, requeue=False) else: logger.info('Task is successful') message.channel.basic_ack(message.delivery_tag) finally: logger.debug("Task is processed") def _watch_load(self): """Pause consuming messages if lood goes above the allowed limit.""" while not self.shutdown_pending.is_set(): load = os.getloadavg()[0] if load > self.config.WORKER_MAX_LOAD: if self._pause is False: logger.warning( 'Load is above the treshold (%.2f/%s), ' 'pausing consumer', load, self.config.WORKER_MAX_LOAD) self._pause = True else: if self._pause is True: logger.warning( 'Load is below the treshold (%.2f/%s), ' 'resuming consumer', load, self.config.WORKER_MAX_LOAD) self._pause = False sleep(1) @property def uptime(self): if self._started is not None: return os.times()[4] - self._started def _shutdown_timer(self): """Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown gracefully. """ if not self.config.WORKER_MAX_RUN_TIME: return while not self.shutdown_pending.is_set(): remaining = self.config.WORKER_MAX_RUN_TIME - self.uptime if remaining > 0: sleep(remaining) else: logger.warning('Run time reached zero') self.shutdown() break def shutdown(self): """Exits after the current task is finished.""" logger.warning("Shutdown requested") self.shutdown_pending.set() def _handle_sigint(self, signum, frame): """Shutdown after processing current task.""" logger.warning("Catched SIGINT") self.shutdown() def _handle_sigterm(self, signum, frame): """Shutdown after processing current task.""" logger.warning("Catched SIGTERM") self.shutdown() def _handle_sighup(self, signum, frame): """Used internally to fail the task when connection to RabbitMQ is lost during the execution of the task. """ logger.warning("Catched SIGHUP") raise ConnectionError(self._heartbeat_exc_info) @staticmethod def _handle_sigusr1(signum, frame): """Print stacktrace.""" print('=' * 70) print(''.join(traceback.format_stack())) print('-' * 70) def _handle_sigusr2(self, signum, frame): """Drop current task.""" logger.warning("Catched SIGUSR2") if self._current_message: logger.warning("Dropping current task...") raise Discard def drop_task(self): os.kill(os.getpid(), signal.SIGUSR2) def _heartbeat_tick(self, connection, stop_event): while not stop_event.wait(1): try: connection.send_heartbeat() except socket.timeout: pass except Exception as e: logger.error(e) self._heartbeat_exc_info = sys.exc_info() os.kill(os.getpid(), signal.SIGHUP) break
import discord from discord.ext import commands import time from random import SystemRandom random = SystemRandom() import sys import subprocess import importlib import copy import gc sys.path.append("..") import jauxiliar as jaux import josecommon as jcommon import joseerror as je DEFAULT_BLOCKS_JSON = '''{ "guilds": [], "users": [] }''' NEW_BACKEND = [''] class JoseBot(jaux.Auxiliar): def __init__(self, _client): jaux.Auxiliar.__init__(self, _client) self.nick = 'jose-bot' self.modules = {} self.env = { 'cooldowns': {}, } self.start_time = time.time() self.command_lock = False self.dev_mode = False self.made_gshutdown = False self.jsondb('blocks', path='db/blocks.json', default=DEFAULT_BLOCKS_JSON) self.ev_empty() async def do_dev_mode(self): self.logger.info("Developer Mode Enabled") g = discord.Game(name='JOSÉ IN MAINTENANCE', url='fuck you') await self.client.change_presence(game=g) def ev_empty(self): self.event_tbl = { 'on_message': [], 'any_message': [], 'server_join': [], 'client_ready': [], 'socket_response': [], # member stuff 'member_join': [], 'member_remove': [], 'server_remove': [], } def ev_load(self, dflag=False): # register events count = 0 for modname in self.modules: module = self.modules[modname] modinst = self.modules[modname]['inst'] for method in module['handlers']: if method.startswith("e_"): evname = method[method.find("_")+1:] if dflag: self.logger.info("Event handler %s@%s:%s", \ method, modname, evname) # check if event exists if evname in self.event_tbl: handler = getattr(modinst, method, None) if handler is None: # ???? self.logger.error("Event handler %s@%s:%s doesn't... exist????", \ method, modname, evname) sys.exit(0) self.event_tbl[evname].append(handler) count += 1 else: self.logger.warning("Event %s@%s:%s doesn't exist in Event Table", \ method, modname, evname) self.logger.info("[ev_load] Loaded %d handlers" % count) async def unload_mod(self, modname): module = self.modules[modname] # if ext_unload exists if getattr(module['inst'], 'ext_unload', False): try: instance = module['inst'] ok = await instance.ext_unload() # first, we should, at least, remove the commands the module has # it will help a LOT on memory usage. instance_methods = (method for method in dir(instance) if callable(getattr(instance, method))) for method in instance_methods: if method.startswith('c_'): # command, remove it delattr(self, method) # delete stuff from the module table del instance_methods, self.modules[modname] # remove its events from the evt. table, if any if len(module['handlers']) > 0: self.ev_empty() self.ev_load() self.logger.info("[unload_mod] Unloaded %s", modname) return ok except Exception as e: self.logger.error("[ERR][unload_mod]%s: %s", (modname, repr(e))) return False, repr(e) else: self.logger.info("%s doesn't have ext_unload", modname) return False, "ext_unload isn't available in %s" % (modname) async def unload_all(self): # unload all modules # copy.copy doesn't work on dict_keys objects to_remove = [] for key in self.modules: to_remove.append(key) count = 0 for modname in to_remove: ok = await self.unload_mod(modname) if not ok: self.logger.error("[unload_all] %s didn't return a True", modname) return ok count += 1 self.logger.info("[unload_all] Unloaded %d out of %d modules", \ count, len(to_remove)) return True, '' async def get_module(self, name): if name in self.modules: # Already loaded module, unload it mod = self.modules[name] try: ok = await mod['inst'].ext_unload() if not ok[0]: self.logger.error("Error on ext_unload(%s): %s", name, ok[1]) return False except Exception as e: self.logger.warn("Almost unloaded %s: %s", name, repr(e)) return False # import new code return importlib.reload(mod['module']) else: # import return importlib.import_module('ext.%s' % name) async def mod_instance(self, name, classobj): instance = classobj(self.client) # set its logger instance.logger = jcommon.logger.getChild(name) # check if it has ext_load method mod_ext_load = getattr(instance, 'ext_load', False) if not mod_ext_load: # module not compatible with Extension API self.logger.error("Module not compatible with EAPI") return False else: # hey thats p good try: ok = await instance.ext_load() if not ok[0]: self.logger.error("Error happened on ext_load(%s): %s", name, ok[1]) return False else: return instance except Exception as e: self.logger.warn("Almost loaded %s", name, exc_info=True) return False async def register_mod(self, name, class_name, module, instance): instance_methods = (method for method in dir(instance) if callable(getattr(instance, method))) # create module in the... module table... yaaaaay... self.modules[name] = ref = { 'inst': instance, 'class': class_name, 'module': module, } methods = [] handlers = [] for method in instance_methods: stw = str.startswith if stw(method, 'c_'): # command setattr(self, method, getattr(instance, method)) methods.append(method) elif stw(method, 'e_'): # Event handler handlers.append(method) # copy them and kill them ref['methods'] = copy.copy(methods) ref['handlers'] = copy.copy(handlers) del methods, handlers # done return True def load_new_backend(self, name): # ok so, gotta be ready # we need to make SURE the new module can handle discord.py's cogs # the last thing we need to do is run bot.add_cog module_name = "ext.{}".format(name) module = importlib.import_module(module_name) importlib.reload(module) instance = module.setup(self.client) instance_methods = (method for method in dir(instance) \ if callable(getattr(instance, method))) # this is a giant hack stw = str.startswith for method in instance_methods: if stw(method, 'c_'): async def cmd(self, ctx): t = time.time() jcxt = jcommon.Context(self.client, ctx.message, t, self) await method(instance, ctx.message, \ ctx.message.content.split(' '), jcxt) cmd = commands.group(pass_context=True)(cmd) cmd = self.client.command(cmd) setattr(instance, method.replace('c_', ''), cmd) elif stw(method, 'e_'): setattr(instance, method.replace('e_', 'on_'), method) self.client.add_cog(instance) return True async def _load_ext(self, name, class_name, cxt): self.logger.info("load_ext: %s@%s", class_name, name) if name not in NEW_BACKEND: # find/reload the module module = await self.get_module(name) if not module: self.logger.error("module not found/error loading module") return False # get the class that represents the module module_class = getattr(module, class_name, None) if not module_class: if cxt is not None: await cxt.say(":train:") self.logger.error("class instance is None") return False # instantiate and ext_load it instance = await self.mod_instance(name, module_class) if not instance: # catches False and None self.logger.error("instance isn't good") return False if name in self.modules: # delete old one del self.modules[name] # instiated with success, register all shit this module has ok = await self.register_mod(name, class_name, module, instance) if not ok: self.logger.error("Error registering module") return False # redo the event handler shit self.ev_empty() self.ev_load() # finally return True else: # module in new backend return self.load_new_backend(name) async def load_ext(self, name, class_name, cxt): # try ok = await self._load_ext(name, class_name, cxt) if ok: self.logger.info("Loaded %s", name) try: await cxt.say(":ok_hand:") except: pass return True else: self.logger.info("Error loading %s", name) try: await cxt.say(":poop:") except: sys.exit(0) return False async def c_reload(self, message, args, cxt): '''`j!reload module` - recarrega um módulo do josé''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_reload.__doc__) return n = args[1] if n in self.modules: await self.load_ext(n, self.modules[n]['class'], cxt) else: await cxt.say("%s: module not found/loaded", (n,)) async def c_unload(self, message, args, cxt): '''`j!unload module` - desrecarrega um módulo do josé''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_reload.__doc__) return modname = args[1] if modname not in self.modules: await cxt.say("%s: module not loaded", (modname,)) else: # unload it self.logger.info("!unload: %s" % modname) res = await self.unload_mod(modname) if res[0]: await cxt.say(":skull: `%s` is dead :skull:", (modname,)) else: await cxt.say(":warning: Error happened: %s", (res[1],)) async def c_loadmod(self, message, args, cxt): '''`j!loadmod class@module` - carrega um módulo do josé''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_loadmod.__doc__) return # parse class@module modclass, modname = args[1].split('@') ok = await self.load_ext(modname, modclass, cxt) if ok: self.logger.info("!loadmod: %s" % modname) await cxt.say(":ok_hand: Success loading `%s`!", (modname,)) else: await cxt.say(":warning: Error loading `%s` :warning:", (modname,)) async def c_modlist(self, message, args, cxt): '''`j!modlist` - List loaded modules''' await cxt.say(self.codeblock("", " ".join(self.modules.keys()))) async def c_hjose(self, message, args, cxt): await cxt.say(jcommon.JOSE_GENERAL_HTEXT, message.author) async def sec_auth(self, f, cxt): auth = await self.is_admin(cxt.message.author.id) if auth: self.command_lock = True await f(cxt) else: raise je.PermissionError() async def general_shutdown(self, cxt): self.made_gshutdown = True jcoin = self.modules['jcoin']['inst'] josextra = self.modules['josextra']['inst'] if cxt is not None: await jcoin.josecoin_save(cxt.message) else: await jcoin.josecoin_save(None) jcommon.log_channel_handler.in_shutdown() self.logger.info("%d messages in this session", josextra.total_msg) # unload all shit and shutdown. await self.unload_all() await self.client.logout() self.logger.info("Logged out") async def turnoff(self, cxt): self.logger.info("Turning Off from %s", str(cxt.message.author)) josextra = self.modules['josextra']['inst'] await cxt.say(":wave: My best showdown was %d msgs/minute, %d msgs/hour, recv %d messages", \ (josextra.best_msg_minute, josextra.best_msg_hour, josextra.total_msg)) await self.general_shutdown(cxt) async def update(self, cxt): self.logger.info("Update from %s", str(cxt.message.author)) josextra = self.modules['josextra']['inst'] shutdown_msg = (":wave: My best showdown was %d msgs/minute, %d msgs/hour, recv %d messages" % \ (josextra.best_msg_minute, josextra.best_msg_hour, josextra.total_msg)) out = subprocess.check_output("git pull", shell=True, \ stderr=subprocess.STDOUT) res = out.decode("utf-8") await cxt.say("`git pull`: ```%s```\n %s", (res, shutdown_msg)) await self.general_shutdown(cxt) async def c_shutdown(self, message, args, cxt): '''`j!shutdown` - turns off josé''' await self.sec_auth(self.turnoff, cxt) async def c_update(self, message, args, cxt): '''`j!update` - Pulls from github and shutsdown''' await self.sec_auth(self.update, cxt) async def c_shell(self, message, args, cxt): '''`j!shell command` - execute shell commands''' await self.is_admin(cxt.message.author.id) command = ' '.join(args[1:]) out = subprocess.check_output(command, shell=True, \ stderr=subprocess.STDOUT) res = out.decode("utf-8") await cxt.say("`%s`: ```%s```\n", (command, res,)) async def c_ping(self, message, args, cxt): '''`j!ping` - pong''' delta_cmd_process = (time.time() - cxt.t_creation) * 1000 t_init = time.time() await cxt.send_typing() t_end = time.time() delta_typing = (t_end - t_init) * 1000 t_init = time.time() pong = await cxt.say("Pong! `cmd_process`: **%.2fms**, `send_typing`: **%.2fms**", \ (delta_cmd_process, delta_typing)) t_end = time.time() delta_send_message = (t_end - t_init) * 1000 await self.client.edit_message(pong, pong.content + \ ", `send_message`: **%.2fms**" % (delta_send_message)) async def c_rand(self, message, args, cxt): '''`j!rand min max` - gera um número aleatório no intervalo [min, max]''' n_min, n_max = 0,0 try: n_min = int(args[1]) n_max = int(args[2]) except: await cxt.say("Error parsing numbers") return if n_min > n_max: await cxt.say("`min` > `max`, sorry") return n_rand = random.randint(n_min, n_max) await cxt.say("random number from %d to %d: %d", (n_min, n_max, n_rand)) return async def c_pstatus(self, message, args, cxt): '''`j!pstatus` - muda o status do josé''' await self.is_admin(message.author.id) playing_name = ' '.join(args[1:]) g = discord.Game(name=playing_name, url=playing_name) await self.client.change_presence(game=g) async def c_escolha(self, message, args, cxt): '''`j!escolha elemento1;elemento2;elemento3;...;elementon` - escolha.''' if len(args) < 2: await cxt.say(self.c_escolha.__doc__) return escolhas = (' '.join(args[1:])).split(';') choice = random.choice(escolhas) await cxt.say(">%s", (choice,)) async def c_pick(self, message, args, cxt): '''`j!pick` - alias for `!escolha`''' await self.c_escolha(message, args, cxt) async def c_nick(self, message, args, cxt): '''`j!nick nickname` - splitted''' await cxt.say("Use `j!gnick` for global nickname change(you don't want that)\ use `j!lnick` for local nickname") async def c_gnick(self, message, args, cxt): '''`j!gnick [nick]` - only admins''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_gnick.__doc__) return self.nick = ' '.join(args[1:]) guilds = 0 for server in self.client.servers: m = server.get_member(jcommon.JOSE_ID) await self.client.change_nickname(m, self.nick) guilds += 1 await cxt.say("Changed nickname to `%r` in %d guilds", (self.nick, guilds)) async def c_lnick(self, message, args, cxt): '''`j!lnick nick` - change josé\'s nickname for this server''' if len(args) < 2: await cxt.say(self.c_lnick.__doc__) return nick = ' '.join(args[1:]) m = message.server.get_member(jcommon.JOSE_ID) await self.client.change_nickname(m, nick) await cxt.say("Nickname changed to `%r`", (nick,)) async def c_version(self, message, args, cxt): pyver = '%d.%d.%d' % (sys.version_info[:3]) head_id = subprocess.check_output("git rev-parse --short HEAD", \ shell=True).decode('utf-8') await cxt.say("`José v%s git:%s py:%s d.py:%s`", (jcommon.JOSE_VERSION, \ head_id, pyver, discord.__version__)) async def c_jose_add(self, message, args, cxt): await cxt.say("José Add URL:\n```%s```", (jcommon.OAUTH_URL,)) async def c_clist(self, message, args, cxt): '''`j!clist module` - mostra todos os comandos de tal módulo''' if len(args) < 2: await cxt.say(self.c_clist.__doc__) return modname = args[1] if modname not in self.modules: await cxt.say("`%s`: Not found", (modname,)) return res = ' '.join(self.modules[modname]['methods']) res = res.replace('c_', jcommon.JOSE_PREFIX) await cxt.say(self.codeblock('', res)) async def c_uptime(self, message, args, cxt): '''`j!uptime` - mostra o uptime do josé''' sec = (time.time() - self.start_time) MINUTE = 60 HOUR = MINUTE * 60 DAY = HOUR * 24 days = int(sec / DAY) hours = int((sec % DAY) / HOUR) minutes = int((sec % HOUR) / MINUTE) seconds = int(sec % MINUTE) fmt = "`Uptime: %d days, %d hours, %d minutes, %d seconds`" await cxt.say(fmt % (days, hours, minutes, seconds)) async def c_eval(self, message, args, cxt): # eval expr await self.is_admin(message.author.id) eval_cmd = ' '.join(args[1:]) if eval_cmd[0] == '`' and eval_cmd[-1] == '`': eval_cmd = eval_cmd[1:-1] self.logger.info("%s[%s] is EVALing %r", message.author, \ message.author.id, eval_cmd) res = eval(eval_cmd) await cxt.say("```%s``` -> `%s`", (eval_cmd, res)) async def c_rplaying(self, message, args, cxt): await self.is_admin(message.author.id) # do the same thing again playing_phrase = random.choice(jcommon.JOSE_PLAYING_PHRASES) playing_name = '%s | v%s | %d guilds | %shjose' % (playing_phrase, jcommon.JOSE_VERSION, \ len(self.client.servers), jcommon.JOSE_PREFIX) self.logger.info("Playing %s", playing_name) g = discord.Game(name = playing_name, url = playing_name) await self.client.change_presence(game = g) async def c_tempadmin(self, message, args, cxt): '''`j!tempadmin userID` - maka a user an admin until josé restarts''' await self.is_admin(message.author.id) try: userid = args[1] except Exception as e: await cxt.say(repr(e)) return jcommon.ADMIN_IDS.append(userid) if userid in jcommon.ADMIN_IDS: await cxt.say(":cop: Added `%r` as temporary admin!", (userid,)) else: await cxt.say(":poop: Error adding user as temporary admin") async def c_username(self, message, args, cxt): '''`j!username` - change josé username''' await self.is_admin(message.author.id) try: name = str(args[1]) await self.client.edit_profile(username=name) await cxt.say("done!!!!1!!1 i am now %s", (name,)) except Exception as e: await cxt.say(":thinking: %r", (e,)) async def c_announce(self, message, args, cxt): '''`j!announce` - announce stuff''' await self.is_admin(message.author.id) announcement = ' '.join(args[1:]) await cxt.say("I'm gonna say `\n%r\n` to all servers I'm in, are you \ sure about that, pretty admin? (y/n)", (announcement,)) yesno = await self.client.wait_for_message(author=message.author) if yesno.content == 'y': svcount, chcount = 0, 0 for server in self.client.servers: for channel in server.channels: if channel.is_default: await self.client.send_message(channel, announcement) chcount += 1 svcount += 1 await cxt.say(":cop: Sent announcement to \ %d servers, %d channels", (svcount, chcount)) else: await cxt.say("jk I'm not gonna do what you \ don't want (unless I'm skynet)") async def c_gcollect(self, message, args, cxt): await self.is_admin(message.author.id) obj = gc.collect() await cxt.say(":cop: Collected %d objects!", (obj,)) async def c_listev(self, message, args, cxt): res = [] for evname in sorted(self.event_tbl): evcount = len(self.event_tbl[evname]) res.append('event %r : %d handlers' % (evname, evcount)) await cxt.say(":cop: There are %d registered events: ```%s```" % \ (len(self.event_tbl), '\n'.join(res))) async def c_logs(self, message, args, cxt): '''`j!logs num` - get `num` last lines from `José.log`''' await self.is_admin(message.author.id) try: linestoget = int(args[1]) except IndexError: await cxt.say("use the command fucking properly") return except Exception as e: await cxt.say(":warning: %r" % e) return cmd = "cat José.log | tail -%d" % (linestoget) res = subprocess.check_output(cmd, shell=True, \ stderr=subprocess.STDOUT) res = res.decode("utf-8") await cxt.say("Last `%d` lines from José.log said: \n```%s```" % \ (linestoget, res)) async def c_sysping(self, message, args, cxt): '''`j!sysping host` - ping from josebox''' await self.is_admin(message.author.id) if len(args) < 1: await cxt.say(self.c_sysping.__doc__) return host = ' '.join(args[1:]) ping = subprocess.Popen( ["ping", "-c", "2", host], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) _out, _error = ping.communicate() out = self.codeblock("", _out.decode('utf-8')) error = self.codeblock("", _error.decode('utf-8')) await cxt.say("OUT:%s\nERR:%s", (out, error)) async def c_mode(self, message, args, cxt): '''`j!mode normal|dev` - change jose mode''' await self.is_admin(message.author.id) if len(args) < 1: await cxt.say(self.c_mode.__doc__) return mode = args[1] if mode == 'normal': self.dev_mode = False elif mode == 'dev': self.dev_mode = True await self.do_dev_mode() await cxt.say("mode changed to `%r`", (mode,)) async def c_blockserver(self, message, args, cxt): '''`j!blockserver serverid` - Blocks/Unblocks a server from message processing.''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_blockserver.__doc__) return guild_id = args[1] guild = self.client.get_server(guild_id) if guild is None: await cxt.say("Guild not found, are you sure José is in it?") return guild_name = guild.name if guild_id in self.blocks['guilds']: # remove from blocks self.blocks['guilds'].remove(guild_id) self.logger.info("Unblocked guild %s, %s", guild_name, guild_id) await cxt.say("Unblocked guild `%s[%s]`.", (guild_name, guild_id,)) else: self.blocks['guilds'].append(guild_id) self.logger.info("Blocked guild %s, %s", guild_name, guild_id) await cxt.say("Blocked guild `%s[%s]`.", (guild_name, guild_id,)) self.jsondb_save('blocks') async def c_blockuser(self, message, args, cxt): '''`j!blockuser userid` - Blocks/Unblocks an User from message processing.''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_blockuser.__doc__) return user_id = args[1] user = discord.utils.get(self.client.get_all_members(), id = user_id) if user is None: await cxt.say("User not found") return if user_id in self.blocks['users']: # remove from blocks self.blocks['users'].remove(user_id) self.logger.info("Unblocked user %s, %s", user, user_id) await cxt.say("Unblocked user `%s[%s]`.", (user, user_id,)) else: self.blocks['users'].append(user_id) self.logger.info("Blocked user %s, %s", user, user_id) await cxt.say("Blocked user `%s[%s]`.", (user, user_id,)) self.jsondb_save('blocks') jose: events: don't check e_ prefix import discord from discord.ext import commands import time from random import SystemRandom random = SystemRandom() import sys import subprocess import importlib import copy import gc sys.path.append("..") import jauxiliar as jaux import josecommon as jcommon import joseerror as je DEFAULT_BLOCKS_JSON = '''{ "guilds": [], "users": [] }''' NEW_BACKEND = [''] class JoseBot(jaux.Auxiliar): def __init__(self, _client): jaux.Auxiliar.__init__(self, _client) self.nick = 'jose-bot' self.modules = {} self.env = { 'cooldowns': {}, } self.start_time = time.time() self.command_lock = False self.dev_mode = False self.made_gshutdown = False self.jsondb('blocks', path='db/blocks.json', default=DEFAULT_BLOCKS_JSON) self.ev_empty() async def do_dev_mode(self): self.logger.info("Developer Mode Enabled") g = discord.Game(name='JOSÉ IN MAINTENANCE', url='fuck you') await self.client.change_presence(game=g) def ev_empty(self): self.event_tbl = { 'on_message': [], 'any_message': [], 'server_join': [], 'client_ready': [], 'socket_response': [], # member stuff 'member_join': [], 'member_remove': [], 'server_remove': [], } def ev_load(self, dflag=False): # register events count = 0 for modname in self.modules: module = self.modules[modname] modinst = self.modules[modname]['inst'] for method in module['handlers']: evname = method[method.find("_")+1:] if dflag: self.logger.info("Event handler %s@%s:%s", \ method, modname, evname) # check if event exists if evname not in self.event_tbl: self.logger.warning("Event %s@%s:%s doesn't exist in Event Table, creating", \ method, modname, evname) self.event_tbl[evname] = [] try: handler = getattr(modinst, method) except Exception as err: self.logger.error("fuck", exc_info=True) sys.exit(0) self.event_tbl[evname].append(handler) count += 1 self.logger.info("[ev_load] Loaded %d handlers" % count) async def unload_mod(self, modname): module = self.modules[modname] # if ext_unload exists if getattr(module['inst'], 'ext_unload', False): try: instance = module['inst'] ok = await instance.ext_unload() # first, we should, at least, remove the commands the module has # it will help a LOT on memory usage. instance_methods = (method for method in dir(instance) if callable(getattr(instance, method))) for method in instance_methods: if method.startswith('c_'): # command, remove it delattr(self, method) # delete stuff from the module table del instance_methods, self.modules[modname] # remove its events from the evt. table, if any if len(module['handlers']) > 0: self.ev_empty() self.ev_load() self.logger.info("[unload_mod] Unloaded %s", modname) return ok except Exception as e: self.logger.error("[ERR][unload_mod]%s: %s", (modname, repr(e))) return False, repr(e) else: self.logger.info("%s doesn't have ext_unload", modname) return False, "ext_unload isn't available in %s" % (modname) async def unload_all(self): # unload all modules # copy.copy doesn't work on dict_keys objects to_remove = [] for key in self.modules: to_remove.append(key) count = 0 for modname in to_remove: ok = await self.unload_mod(modname) if not ok: self.logger.error("[unload_all] %s didn't return a True", modname) return ok count += 1 self.logger.info("[unload_all] Unloaded %d out of %d modules", \ count, len(to_remove)) return True, '' async def get_module(self, name): if name in self.modules: # Already loaded module, unload it mod = self.modules[name] try: ok = await mod['inst'].ext_unload() if not ok[0]: self.logger.error("Error on ext_unload(%s): %s", name, ok[1]) return False except Exception as e: self.logger.warn("Almost unloaded %s: %s", name, repr(e)) return False # import new code return importlib.reload(mod['module']) else: # import return importlib.import_module('ext.%s' % name) async def mod_instance(self, name, classobj): instance = classobj(self.client) # set its logger instance.logger = jcommon.logger.getChild(name) # check if it has ext_load method mod_ext_load = getattr(instance, 'ext_load', False) if not mod_ext_load: # module not compatible with Extension API self.logger.error("Module not compatible with EAPI") return False else: # hey thats p good try: ok = await instance.ext_load() if not ok[0]: self.logger.error("Error happened on ext_load(%s): %s", name, ok[1]) return False else: return instance except Exception as e: self.logger.warn("Almost loaded %s", name, exc_info=True) return False async def register_mod(self, name, class_name, module, instance): instance_methods = (method for method in dir(instance) if callable(getattr(instance, method))) # create module in the... module table... yaaaaay... self.modules[name] = ref = { 'inst': instance, 'class': class_name, 'module': module, } methods = [] handlers = [] for method in instance_methods: stw = str.startswith if stw(method, 'c_'): # command setattr(self, method, getattr(instance, method)) methods.append(method) elif stw(method, 'e_'): # Event handler handlers.append(method) # copy them and kill them ref['methods'] = copy.copy(methods) ref['handlers'] = copy.copy(handlers) del methods, handlers # done return True def load_new_backend(self, name): # ok so, gotta be ready # we need to make SURE the new module can handle discord.py's cogs # the last thing we need to do is run bot.add_cog module_name = "ext.{}".format(name) module = importlib.import_module(module_name) importlib.reload(module) instance = module.setup(self.client) instance_methods = (method for method in dir(instance) \ if callable(getattr(instance, method))) # this is a giant hack stw = str.startswith for method in instance_methods: if stw(method, 'c_'): async def cmd(self, ctx): t = time.time() jcxt = jcommon.Context(self.client, ctx.message, t, self) await method(instance, ctx.message, \ ctx.message.content.split(' '), jcxt) cmd = commands.group(pass_context=True)(cmd) cmd = self.client.command(cmd) setattr(instance, method.replace('c_', ''), cmd) elif stw(method, 'e_'): setattr(instance, method.replace('e_', 'on_'), method) self.client.add_cog(instance) return True async def _load_ext(self, name, class_name, cxt): self.logger.info("load_ext: %s@%s", class_name, name) if name not in NEW_BACKEND: # find/reload the module module = await self.get_module(name) if not module: self.logger.error("module not found/error loading module") return False # get the class that represents the module module_class = getattr(module, class_name, None) if not module_class: if cxt is not None: await cxt.say(":train:") self.logger.error("class instance is None") return False # instantiate and ext_load it instance = await self.mod_instance(name, module_class) if not instance: # catches False and None self.logger.error("instance isn't good") return False if name in self.modules: # delete old one del self.modules[name] # instiated with success, register all shit this module has ok = await self.register_mod(name, class_name, module, instance) if not ok: self.logger.error("Error registering module") return False # redo the event handler shit self.ev_empty() self.ev_load() # finally return True else: # module in new backend return self.load_new_backend(name) async def load_ext(self, name, class_name, cxt): # try ok = await self._load_ext(name, class_name, cxt) if ok: self.logger.info("Loaded %s", name) try: await cxt.say(":ok_hand:") except: pass return True else: self.logger.info("Error loading %s", name) try: await cxt.say(":poop:") except: sys.exit(0) return False async def c_reload(self, message, args, cxt): '''`j!reload module` - recarrega um módulo do josé''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_reload.__doc__) return n = args[1] if n in self.modules: await self.load_ext(n, self.modules[n]['class'], cxt) else: await cxt.say("%s: module not found/loaded", (n,)) async def c_unload(self, message, args, cxt): '''`j!unload module` - desrecarrega um módulo do josé''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_reload.__doc__) return modname = args[1] if modname not in self.modules: await cxt.say("%s: module not loaded", (modname,)) else: # unload it self.logger.info("!unload: %s" % modname) res = await self.unload_mod(modname) if res[0]: await cxt.say(":skull: `%s` is dead :skull:", (modname,)) else: await cxt.say(":warning: Error happened: %s", (res[1],)) async def c_loadmod(self, message, args, cxt): '''`j!loadmod class@module` - carrega um módulo do josé''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_loadmod.__doc__) return # parse class@module modclass, modname = args[1].split('@') ok = await self.load_ext(modname, modclass, cxt) if ok: self.logger.info("!loadmod: %s" % modname) await cxt.say(":ok_hand: Success loading `%s`!", (modname,)) else: await cxt.say(":warning: Error loading `%s` :warning:", (modname,)) async def c_modlist(self, message, args, cxt): '''`j!modlist` - List loaded modules''' await cxt.say(self.codeblock("", " ".join(self.modules.keys()))) async def c_hjose(self, message, args, cxt): await cxt.say(jcommon.JOSE_GENERAL_HTEXT, message.author) async def sec_auth(self, f, cxt): auth = await self.is_admin(cxt.message.author.id) if auth: self.command_lock = True await f(cxt) else: raise je.PermissionError() async def general_shutdown(self, cxt): self.made_gshutdown = True jcoin = self.modules['jcoin']['inst'] josextra = self.modules['josextra']['inst'] if cxt is not None: await jcoin.josecoin_save(cxt.message) else: await jcoin.josecoin_save(None) jcommon.log_channel_handler.in_shutdown() self.logger.info("%d messages in this session", josextra.total_msg) # unload all shit and shutdown. await self.unload_all() await self.client.logout() self.logger.info("Logged out") async def turnoff(self, cxt): self.logger.info("Turning Off from %s", str(cxt.message.author)) josextra = self.modules['josextra']['inst'] await cxt.say(":wave: My best showdown was %d msgs/minute, %d msgs/hour, recv %d messages", \ (josextra.best_msg_minute, josextra.best_msg_hour, josextra.total_msg)) await self.general_shutdown(cxt) async def update(self, cxt): self.logger.info("Update from %s", str(cxt.message.author)) josextra = self.modules['josextra']['inst'] shutdown_msg = (":wave: My best showdown was %d msgs/minute, %d msgs/hour, recv %d messages" % \ (josextra.best_msg_minute, josextra.best_msg_hour, josextra.total_msg)) out = subprocess.check_output("git pull", shell=True, \ stderr=subprocess.STDOUT) res = out.decode("utf-8") await cxt.say("`git pull`: ```%s```\n %s", (res, shutdown_msg)) await self.general_shutdown(cxt) async def c_shutdown(self, message, args, cxt): '''`j!shutdown` - turns off josé''' await self.sec_auth(self.turnoff, cxt) async def c_update(self, message, args, cxt): '''`j!update` - Pulls from github and shutsdown''' await self.sec_auth(self.update, cxt) async def c_shell(self, message, args, cxt): '''`j!shell command` - execute shell commands''' await self.is_admin(cxt.message.author.id) command = ' '.join(args[1:]) out = subprocess.check_output(command, shell=True, \ stderr=subprocess.STDOUT) res = out.decode("utf-8") await cxt.say("`%s`: ```%s```\n", (command, res,)) async def c_ping(self, message, args, cxt): '''`j!ping` - pong''' delta_cmd_process = (time.time() - cxt.t_creation) * 1000 t_init = time.time() await cxt.send_typing() t_end = time.time() delta_typing = (t_end - t_init) * 1000 t_init = time.time() pong = await cxt.say("Pong! `cmd_process`: **%.2fms**, `send_typing`: **%.2fms**", \ (delta_cmd_process, delta_typing)) t_end = time.time() delta_send_message = (t_end - t_init) * 1000 await self.client.edit_message(pong, pong.content + \ ", `send_message`: **%.2fms**" % (delta_send_message)) async def c_rand(self, message, args, cxt): '''`j!rand min max` - gera um número aleatório no intervalo [min, max]''' n_min, n_max = 0,0 try: n_min = int(args[1]) n_max = int(args[2]) except: await cxt.say("Error parsing numbers") return if n_min > n_max: await cxt.say("`min` > `max`, sorry") return n_rand = random.randint(n_min, n_max) await cxt.say("random number from %d to %d: %d", (n_min, n_max, n_rand)) return async def c_pstatus(self, message, args, cxt): '''`j!pstatus` - muda o status do josé''' await self.is_admin(message.author.id) playing_name = ' '.join(args[1:]) g = discord.Game(name=playing_name, url=playing_name) await self.client.change_presence(game=g) async def c_escolha(self, message, args, cxt): '''`j!escolha elemento1;elemento2;elemento3;...;elementon` - escolha.''' if len(args) < 2: await cxt.say(self.c_escolha.__doc__) return escolhas = (' '.join(args[1:])).split(';') choice = random.choice(escolhas) await cxt.say(">%s", (choice,)) async def c_pick(self, message, args, cxt): '''`j!pick` - alias for `!escolha`''' await self.c_escolha(message, args, cxt) async def c_nick(self, message, args, cxt): '''`j!nick nickname` - splitted''' await cxt.say("Use `j!gnick` for global nickname change(you don't want that)\ use `j!lnick` for local nickname") async def c_gnick(self, message, args, cxt): '''`j!gnick [nick]` - only admins''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_gnick.__doc__) return self.nick = ' '.join(args[1:]) guilds = 0 for server in self.client.servers: m = server.get_member(jcommon.JOSE_ID) await self.client.change_nickname(m, self.nick) guilds += 1 await cxt.say("Changed nickname to `%r` in %d guilds", (self.nick, guilds)) async def c_lnick(self, message, args, cxt): '''`j!lnick nick` - change josé\'s nickname for this server''' if len(args) < 2: await cxt.say(self.c_lnick.__doc__) return nick = ' '.join(args[1:]) m = message.server.get_member(jcommon.JOSE_ID) await self.client.change_nickname(m, nick) await cxt.say("Nickname changed to `%r`", (nick,)) async def c_version(self, message, args, cxt): pyver = '%d.%d.%d' % (sys.version_info[:3]) head_id = subprocess.check_output("git rev-parse --short HEAD", \ shell=True).decode('utf-8') await cxt.say("`José v%s git:%s py:%s d.py:%s`", (jcommon.JOSE_VERSION, \ head_id, pyver, discord.__version__)) async def c_jose_add(self, message, args, cxt): await cxt.say("José Add URL:\n```%s```", (jcommon.OAUTH_URL,)) async def c_clist(self, message, args, cxt): '''`j!clist module` - mostra todos os comandos de tal módulo''' if len(args) < 2: await cxt.say(self.c_clist.__doc__) return modname = args[1] if modname not in self.modules: await cxt.say("`%s`: Not found", (modname,)) return res = ' '.join(self.modules[modname]['methods']) res = res.replace('c_', jcommon.JOSE_PREFIX) await cxt.say(self.codeblock('', res)) async def c_uptime(self, message, args, cxt): '''`j!uptime` - mostra o uptime do josé''' sec = (time.time() - self.start_time) MINUTE = 60 HOUR = MINUTE * 60 DAY = HOUR * 24 days = int(sec / DAY) hours = int((sec % DAY) / HOUR) minutes = int((sec % HOUR) / MINUTE) seconds = int(sec % MINUTE) fmt = "`Uptime: %d days, %d hours, %d minutes, %d seconds`" await cxt.say(fmt % (days, hours, minutes, seconds)) async def c_eval(self, message, args, cxt): # eval expr await self.is_admin(message.author.id) eval_cmd = ' '.join(args[1:]) if eval_cmd[0] == '`' and eval_cmd[-1] == '`': eval_cmd = eval_cmd[1:-1] self.logger.info("%s[%s] is EVALing %r", message.author, \ message.author.id, eval_cmd) res = eval(eval_cmd) await cxt.say("```%s``` -> `%s`", (eval_cmd, res)) async def c_rplaying(self, message, args, cxt): await self.is_admin(message.author.id) # do the same thing again playing_phrase = random.choice(jcommon.JOSE_PLAYING_PHRASES) playing_name = '%s | v%s | %d guilds | %shjose' % (playing_phrase, jcommon.JOSE_VERSION, \ len(self.client.servers), jcommon.JOSE_PREFIX) self.logger.info("Playing %s", playing_name) g = discord.Game(name = playing_name, url = playing_name) await self.client.change_presence(game = g) async def c_tempadmin(self, message, args, cxt): '''`j!tempadmin userID` - maka a user an admin until josé restarts''' await self.is_admin(message.author.id) try: userid = args[1] except Exception as e: await cxt.say(repr(e)) return jcommon.ADMIN_IDS.append(userid) if userid in jcommon.ADMIN_IDS: await cxt.say(":cop: Added `%r` as temporary admin!", (userid,)) else: await cxt.say(":poop: Error adding user as temporary admin") async def c_username(self, message, args, cxt): '''`j!username` - change josé username''' await self.is_admin(message.author.id) try: name = str(args[1]) await self.client.edit_profile(username=name) await cxt.say("done!!!!1!!1 i am now %s", (name,)) except Exception as e: await cxt.say(":thinking: %r", (e,)) async def c_announce(self, message, args, cxt): '''`j!announce` - announce stuff''' await self.is_admin(message.author.id) announcement = ' '.join(args[1:]) await cxt.say("I'm gonna say `\n%r\n` to all servers I'm in, are you \ sure about that, pretty admin? (y/n)", (announcement,)) yesno = await self.client.wait_for_message(author=message.author) if yesno.content == 'y': svcount, chcount = 0, 0 for server in self.client.servers: for channel in server.channels: if channel.is_default: await self.client.send_message(channel, announcement) chcount += 1 svcount += 1 await cxt.say(":cop: Sent announcement to \ %d servers, %d channels", (svcount, chcount)) else: await cxt.say("jk I'm not gonna do what you \ don't want (unless I'm skynet)") async def c_gcollect(self, message, args, cxt): await self.is_admin(message.author.id) obj = gc.collect() await cxt.say(":cop: Collected %d objects!", (obj,)) async def c_listev(self, message, args, cxt): res = [] for evname in sorted(self.event_tbl): evcount = len(self.event_tbl[evname]) res.append('event %r : %d handlers' % (evname, evcount)) await cxt.say(":cop: There are %d registered events: ```%s```" % \ (len(self.event_tbl), '\n'.join(res))) async def c_logs(self, message, args, cxt): '''`j!logs num` - get `num` last lines from `José.log`''' await self.is_admin(message.author.id) try: linestoget = int(args[1]) except IndexError: await cxt.say("use the command fucking properly") return except Exception as e: await cxt.say(":warning: %r" % e) return cmd = "cat José.log | tail -%d" % (linestoget) res = subprocess.check_output(cmd, shell=True, \ stderr=subprocess.STDOUT) res = res.decode("utf-8") await cxt.say("Last `%d` lines from José.log said: \n```%s```" % \ (linestoget, res)) async def c_sysping(self, message, args, cxt): '''`j!sysping host` - ping from josebox''' await self.is_admin(message.author.id) if len(args) < 1: await cxt.say(self.c_sysping.__doc__) return host = ' '.join(args[1:]) ping = subprocess.Popen( ["ping", "-c", "2", host], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) _out, _error = ping.communicate() out = self.codeblock("", _out.decode('utf-8')) error = self.codeblock("", _error.decode('utf-8')) await cxt.say("OUT:%s\nERR:%s", (out, error)) async def c_mode(self, message, args, cxt): '''`j!mode normal|dev` - change jose mode''' await self.is_admin(message.author.id) if len(args) < 1: await cxt.say(self.c_mode.__doc__) return mode = args[1] if mode == 'normal': self.dev_mode = False elif mode == 'dev': self.dev_mode = True await self.do_dev_mode() await cxt.say("mode changed to `%r`", (mode,)) async def c_blockserver(self, message, args, cxt): '''`j!blockserver serverid` - Blocks/Unblocks a server from message processing.''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_blockserver.__doc__) return guild_id = args[1] guild = self.client.get_server(guild_id) if guild is None: await cxt.say("Guild not found, are you sure José is in it?") return guild_name = guild.name if guild_id in self.blocks['guilds']: # remove from blocks self.blocks['guilds'].remove(guild_id) self.logger.info("Unblocked guild %s, %s", guild_name, guild_id) await cxt.say("Unblocked guild `%s[%s]`.", (guild_name, guild_id,)) else: self.blocks['guilds'].append(guild_id) self.logger.info("Blocked guild %s, %s", guild_name, guild_id) await cxt.say("Blocked guild `%s[%s]`.", (guild_name, guild_id,)) self.jsondb_save('blocks') async def c_blockuser(self, message, args, cxt): '''`j!blockuser userid` - Blocks/Unblocks an User from message processing.''' await self.is_admin(message.author.id) if len(args) < 2: await cxt.say(self.c_blockuser.__doc__) return user_id = args[1] user = discord.utils.get(self.client.get_all_members(), id = user_id) if user is None: await cxt.say("User not found") return if user_id in self.blocks['users']: # remove from blocks self.blocks['users'].remove(user_id) self.logger.info("Unblocked user %s, %s", user, user_id) await cxt.say("Unblocked user `%s[%s]`.", (user, user_id,)) else: self.blocks['users'].append(user_id) self.logger.info("Blocked user %s, %s", user, user_id) await cxt.say("Blocked user `%s[%s]`.", (user, user_id,)) self.jsondb_save('blocks')
!python -m spacy download en_core_web_sm from interfaces.SentenceOperation import SentenceOperation from evaluation.evaluation_engine import evaluate, execute_model from tasks.TaskTypes import TaskType import spacy import string from spacy.lang.en.examples import sentences nlp = spacy.load("en_core_web_sm") # A dict containing offensive words and their alternatives disability_names = {"blind":"person or people with a visual impairment", "deformed": "person or people with a physical disability", "handicapped":"person or people with a physical disability", "cripple":"person with a physical disability", "crippled":"person or people with a physical disability", "paraplegic":"person or people with paraplegia", "psychotic":"person or people with a psychotic condition", "psycho":"person with a psychotic condition", "psychopath":"person with a psychotic condition", "quadriplegic":"person or people with quadriplegia", "schizophrenic":"person or people with schizophrenia", "vegetable":"person in a vegetative state", "bonkers":"person or people with a mental disability", "senile":"person or people with dementia", "gimp":"person with a physical disability", "spastic":"person with a physical disability", "spaz":"person with a physical disability", "lame":"person with a physical disability", "lunatic":"person with a mental disability", "lunatics":"people with a mental disability", "looney":"person with a mental disability", "manic":"person with a psychological disability", "mutant":"person with an uncommon genetic mutation", "mutants": "people with an uncommon genetic mutation", "wheelchairbound":"wheelchair user", "subnormal":"person or people with learning difficulties or a developmental disorder", "dwarf":"short-statured person", "midget":"short-statured person", "deaf":"person or people with a hearing disability", "mute":"person or people with a listening disability", "dumb":"person or people with a mental and/or speech impairment", "demented":"person or people with dementia", "dotard":"old person with impaired intellect or physical disability", "dotards":"old people with impaired intellect or physical disability", "derp":"person with intellectual disabilities", "imbecile":"person with intellectual disabilities", "imbeciles":"people with intellectual disabilities", "crazy":"person or people with a mental impairment", "insane ":"person or people with a mental impairment", "wacko":"person with a mental impairment", "nuts":"person or people with a mental impairment", "retard":"person with an intellectual disability", "retards":"people with an intellectual disability", "retarded":"person or people with an intellectual disability", } def postag(text): doc = nlp(text) pos_list = [] word_list = [] for token in doc: pos_list.append(token.pos_) word_list.append(token.text) print(pos_list, word_list) return word_list, pos_list def preserve_capitalization(original, transformed): if original[0].isupper(): transformed = transformed.capitalize() else: return original return transformed def get_index(wl, n): indices = [i for i, x in enumerate(wl) if x == n] return indices def placement(index_of_dis, wl, pl, input, disability_names, name): text = input.lower() wl,pl = postag(text) index_of_dis = get_index(wl,name) max_len = len(wl) for i in index_of_dis: print("For Occurence", i) print("For Words Less than Maximum Length:") if i < (max_len-1): print("Words in between") if pl[i+1] == 'NOUN': s = ' '.join(wl) text = s elif pl[i+1]!='NOUN': s = ' '.join(wl) namew = wl[i] wl[i] = disability_names[namew] text = ' '.join(wl) elif i >= (max_len-1): print("For Words At Maximum Length:") namew = wl[i] wl[i] = disability_names[namew] text = ' '.join(wl) else: s = ' '.join(wl) text = s text = preserve_capitalization(input, text) return text def replace_punc(text): for i in string.punctuation: text = text.replace(i," "+i) return text def restore_punc(text): for i in string.punctuation: text = text.replace(" "+i,i) return text def different_ability(input, disability_names): text = input.lower() text=replace_punc(text) for name in disability_names.keys(): if name in text: wl, pl = postag(text) max_len = len(wl) indices = get_index(wl, name) textp = placement(indices, wl, pl, input, disability_names, name) text = restore_punc(textp) text = preserve_capitalization(input,text) text = restore_punc(text) return text class DifferentAbilityTransformation(SentenceOperation): tasks = [ TaskType.TEXT_CLASSIFICATION, TaskType.TEXT_TO_TEXT_GENERATION ] languages = ["en"] def __init__(self, seed=0, max_outputs=1): super().__init__(seed, max_outputs = max_outputs) self.disability_names = disability_names def generate(self, sentence: str): return [different_ability(sentence, self.disability_names)] Update transformation.py !python -m spacy download en_core_web_sm from interfaces.SentenceOperation import SentenceOperation from evaluation.evaluation_engine import evaluate, execute_model from tasks.TaskTypes import TaskType import spacy import string from spacy.lang.en.examples import sentences nlp = spacy.load("en_core_web_sm") # A dict containing offensive words and their alternatives disability_names = {"blind":"person or people with a visual impairment", "deformed": "person or people with a physical disability", "handicapped":"person or people with a physical disability", "cripple":"person with a physical disability", "crippled":"person or people with a physical disability", "paraplegic":"person or people with paraplegia", "psychotic":"person or people with a psychotic condition", "psycho":"person with a psychotic condition", "psychopath":"person with a psychotic condition", "quadriplegic":"person or people with quadriplegia", "schizophrenic":"person or people with schizophrenia", "vegetable":"person in a vegetative state", "bonkers":"person or people with a mental disability", "senile":"person or people with dementia", "gimp":"person with a physical disability", "spastic":"person with a physical disability", "spaz":"person with a physical disability", "lame":"person with a physical disability", "lunatic":"person with a mental disability", "lunatics":"people with a mental disability", "looney":"person with a mental disability", "manic":"person with a psychological disability", "mutant":"person with an uncommon genetic mutation", "mutants": "people with an uncommon genetic mutation", "wheelchairbound":"wheelchair user", "subnormal":"person or people with learning difficulties or a developmental disorder", "dwarf":"short-statured person", "midget":"short-statured person", "deaf":"person or people with a hearing disability", "mute":"person or people with a listening disability", "dumb":"person or people with a mental and/or speech impairment", "demented":"person or people with dementia", "dotard":"old person with impaired intellect or physical disability", "dotards":"old people with impaired intellect or physical disability", "derp":"person with intellectual disabilities", "imbecile":"person with intellectual disabilities", "imbeciles":"people with intellectual disabilities", "crazy":"person or people with a mental impairment", "insane ":"person or people with a mental impairment", "wacko":"person with a mental impairment", "nuts":"person or people with a mental impairment", "retard":"person with an intellectual disability", "retards":"people with an intellectual disability", "retarded":"person or people with an intellectual disability", } def postag(text): doc = nlp(text) pos_list = [] word_list = [] for token in doc: pos_list.append(token.pos_) word_list.append(token.text) print(pos_list, word_list) return word_list, pos_list def preserve_capitalization(original, transformed): if original[0].isupper(): transformed = transformed.capitalize() else: return original return transformed def get_index(wl, n): indices = [i for i, x in enumerate(wl) if x == n] return indices def placement(index_of_dis, wl, pl, input, disability_names, name): text = input.lower() wl,pl = postag(text) index_of_dis = get_index(wl,name) max_len = len(wl) for i in index_of_dis: print("For Occurence", i) print("For Words Less than Maximum Length:") if i < (max_len-1): print("Words in between") if pl[i+1] == 'NOUN': s = ' '.join(wl) text = s elif pl[i+1]!='NOUN': s = ' '.join(wl) namew = wl[i] wl[i] = disability_names[namew] text = ' '.join(wl) elif i >= (max_len-1): print("For Words At Maximum Length:") namew = wl[i] wl[i] = disability_names[namew] text = ' '.join(wl) else: s = ' '.join(wl) text = s text = preserve_capitalization(input, text) return text def replace_punc(text): for i in string.punctuation: text = text.replace(i," "+i) return text def restore_punc(text): for i in string.punctuation: text = text.replace(" "+i,i) return text def different_ability(input, disability_names): text = input.lower() text=replace_punc(text) for name in disability_names.keys(): if name in text: wl, pl = postag(text) max_len = len(wl) indices = get_index(wl, name) textp = placement(indices, wl, pl, input, disability_names, name) text = restore_punc(textp) text = preserve_capitalization(input,text) text = restore_punc(text) return text class DifferentAbilityTransformation(SentenceOperation): tasks = [ TaskType.TEXT_CLASSIFICATION, TaskType.TEXT_TO_TEXT_GENERATION ] languages = ["en"] def __init__(self, seed=0, max_outputs=1): super().__init__(seed, max_outputs=max_outputs) self.disability_names = disability_names def generate(self, sentence: str): return [different_ability(sentence, self.disability_names)]
from dolo.misc.nth_order_derivatives import NonDecreasingTree from compiler import * import sympy from dolo.misc.nth_order_derivatives import * import time class CustomPrinter(sympy.printing.StrPrinter): def _print_TSymbol(self, expr): return expr.__str__() class DynareCompiler(Compiler): def compute_main_file(self,omit_nnz=True): model = self.model # should be computed somewhere else all_symbols = set([]) for eq in model.equations: all_symbols.update( eq.atoms() ) format_dict = dict() format_dict['fname'] = model.fname format_dict['maximum_lag'] = max([-v.lag for v in all_symbols if isinstance(v,TSymbol)]) format_dict['maximum_lead'] = max([v.lag for v in all_symbols if isinstance(v,TSymbol)]) format_dict['maximum_endo_lag'] = max([-v.lag for v in all_symbols if isinstance(v,Variable)]) format_dict['maximum_endo_lead'] = max([v.lag for v in all_symbols if isinstance(v,Variable)]) format_dict['maximum_exo_lag'] = max([-v.lag for v in all_symbols if isinstance(v,Shock)]) format_dict['maximum_exo_lead'] = max([v.lag for v in all_symbols if isinstance(v,Shock)]) format_dict['endo_nbr'] = len(model.variables) format_dict['exo_nbr'] = len(model.shocks) format_dict['param_nbr'] = len(model.parameters) output = """% % Status : main Dynare file % % Warning : this file is generated automatically by Dolo for Dynare % from model file (.mod) clear all tic; global M_ oo_ options_ global ys0_ ex0_ ct_ options_ = []; M_.fname = '{fname}'; % % Some global variables initialization % global_initialization; diary off; warning_old_state = warning; warning off; delete {fname}.log; warning warning_old_state; logname_ = '{fname}.log'; diary {fname}.log; options_.model_mode = 0; erase_compiled_function('{fname}_static'); erase_compiled_function('{fname}_dynamic'); M_.exo_det_nbr = 0; M_.exo_nbr = {exo_nbr}; M_.endo_nbr = {endo_nbr}; M_.param_nbr = {param_nbr}; M_.Sigma_e = zeros({exo_nbr}, {exo_nbr}); M_.exo_names_orig_ord = [1:{exo_nbr}]; """.format( **format_dict ) string_of_names = lambda l: str.join(' , ',["'%s'"%str(v) for v in l]) string_of_tex_names = lambda l: str.join(' , ',["'%s'"%v._latex_() for v in l]) output += "M_.exo_names = strvcat( {0} );\n" .format(string_of_names(model.shocks)) output += "M_.exo_names_tex = strvcat( {0} );\n".format(string_of_tex_names(model.shocks)) output += "M_.endo_names = strvcat( {0} );\n".format(string_of_names(model.variables)) output += "M_.endo_names_tex = strvcat( {0} );\n".format(string_of_tex_names(model.variables)) output += "M_.param_names = strvcat( {0} );\n".format( string_of_names(model.parameters) ) output += "M_.param_names_tex = strvcat( {0} );\n".format( string_of_tex_names(model.parameters) ) from dolo.misc.matlab import value_to_mat lli = value_to_mat(self.lead_lag_incidence_matrix()) output += "M_.lead_lag_incidence = {0}';\n".format(lli) output += """M_.maximum_lag = {maximum_lag}; M_.maximum_lead = {maximum_lead}; M_.maximum_endo_lag = {maximum_endo_lag}; M_.maximum_endo_lead = {maximum_endo_lead}; M_.maximum_exo_lag = {maximum_exo_lag}; M_.maximum_exo_lead = {maximum_exo_lead}; oo_.steady_state = zeros({endo_nbr}, 1); oo_.exo_steady_state = zeros({exo_nbr}, 1); M_.params = repmat(NaN,{param_nbr}, 1); """.format( **format_dict ) # Now we add tags for equations tags_array_string = [] for eq in model.equations: for k in eq.tags.keys(): tags_array_string.append( "{n}, '{key}', '{value}'".format(n=eq.n, key=k, value=eq.tags[k]) ) output += "M_.equations_tags = {{\n{0}\n}};\n".format(";\n".join(tags_array_string)) if not omit_nnz: # we don't set the number of non zero derivatives yet order = max([ndt.depth() for ndt in self.dynamic_derivatives]) output += "M_.NNZDerivatives = zeros({0}, 1); % parrot mode\n".format(order) output += "M_.NNZDerivatives(1) = {0}; % parrot mode\n".format(self.NNZDerivatives(1)) output += "M_.NNZDerivatives(2) = {0}; % parrot mode\n".format(self.NNZDerivatives(2)) output += "M_.NNZDerivatives(3) = {0}; % parrot mode\n".format(self.NNZDerivatives(3)) idp = DicPrinter(self.static_substitution_list(y='oo_.steady_state',params='M_.params')) porder = model.order_parameters_values() vorder = model.order_init_values() for p in porder: i = model.parameters.index(p) + 1 output += "M_.params({0}) = {1};\n".format(i,idp.doprint_matlab(model.parameters_values[p])) output += "{0} = M_.params({1});\n".format(p,i) output += '''% % INITVAL instructions % ''' #idp = DicPrinter(self.static_substitution_list(y='oo_.steady_state',params='M_.params')) output += "options_.initval_file = 0; % parrot mode\n" for v in vorder: if v in self.model.variables: # should be removed i = model.variables.index(v) + 1 output += "oo_.steady_state({0}) = {1};\n".format(i,idp.doprint_matlab(model.init_values[v])) # we don't allow initialization of shocks to nonzero values output += "oo_.exo_steady_state = zeros({0},1);\n".format( len(model.shocks) ) output += '''oo_.endo_simul=[oo_.steady_state*ones(1,M_.maximum_lag)]; if M_.exo_nbr > 0; oo_.exo_simul = [ones(M_.maximum_lag,1)*oo_.exo_steady_state']; end; if M_.exo_det_nbr > 0; oo_.exo_det_simul = [ones(M_.maximum_lag,1)*oo_.exo_det_steady_state']; end; ''' #output += '''steady; output +=""" % % SHOCKS instructions % make_ex_; M_.exo_det_length = 0; % parrot """ for i in range(model.covariances.shape[0]): for j in range(model.covariances.shape[1]): expr = model.covariances[i,j] if expr != 0: v = str(expr).replace("**","^") #if (v != 0) and not isinstance(v,sympy.core.numbers.Zero): output += "M_.Sigma_e({0}, {1}) = {2};\n".format(i+1,j+1,v) # This results from the stoch_simul( # output += '''options_.drop = 200; #options_.order = 3; #var_list_=[]; #info = stoch_simul(var_list_); #''' # # output += '''save('example2_results.mat', 'oo_', 'M_', 'options_'); #diary off # #disp(['Total computing time : ' dynsec2hms(toc) ]);''' f = file(model.fname + '.m','w') f.write(output) f.close() return output def NNZDerivatives(self,order): n = 0 for ndt in self.dynamic_derivatives: # @type ndt NonDecreasingTree l = ndt.list_nth_order_children(order) for c in l: # we must compute the number of permutations vars = c.vars s = factorial(len(vars)) for v in set(vars): s = s / factorial(vars.count(v)) n += s return n def NNZStaticDerivatives(self,order): n = 0 for ndt in self.static_derivatives: # @type ndt NonDecreasingTree l = ndt.list_nth_order_children(order) for c in l: # we must compute the number of permutations vars = c.vars s = factorial(len(vars)) for v in set(vars): s = s / factorial(vars.count(v)) n += s return n def export_to_modfile(self,output_file=None,return_text=False,options={},append="",comments = "", solve_init_state=False): model = self.model #init_state = self.get_init_dict() default = {'steady':False,'check':False,'dest':'dynare','order':1}#default options for o in default: if not o in options: options[o] = default[o] init_block = ["// Generated by Dolo"] init_block.append( "// Model basename : " + self.model.fname) init_block.append(comments) init_block.append( "" ) init_block.append( "var " + str.join(",", map(str,self.model.variables) ) + ";") init_block.append( "" ) init_block.append( "varexo " + str.join(",", map(str,self.model.shocks) ) + ";" ) init_block.append( "" ) init_block.append( "parameters " + str.join(",",map(str,self.model.parameters)) + ";" ) init_state = model.parameters_values.copy() init_state.update( model.init_values.copy() ) from dolo.misc.calculus import solve_triangular_system if not solve_init_state: itd = model.init_values order = solve_triangular_system(init_state,return_order=True) else: itd,order = calculus.solve_triangular_system(init_state) for p in order: if p in model.parameters: #init_block.append(p.name + " = " + str(init_state[p]) + ";") if p in model.parameters_values: init_block.append(p.name + " = " + str(model.parameters_values[p]).replace('**','^') + ";") printer = CustomPrinter() model_block = [] model_block.append( "model;" ) for eq in self.model.equations: s = printer.doprint(eq) s = s.replace("==","=") s = s.replace("**","^") # s = s.replace("_b1","(-1)") # this should allow lags more than 1 # s = s.replace("_f1","(+1)") # this should allow lags more than 1 model_block += "\n" if 'name' in eq.tags: model_block.append("// eq %s : %s" %(eq.n,eq.tags.get('name'))) else: model_block.append("// eq %s" %(eq.n)) if len(eq.tags)>0: model_block.append("[ {0} ]".format(" , ".join(["{0} = '{1}'".format(k,eq.tags[k]) for k in eq.tags]))) model_block.append(s + ";") model_block.append( "end;" ) if options['dest'] == 'dynare': shocks_block = [] if model.covariances != None: shocks_block.append("shocks;") cov_shape = model.covariances.shape for i in range(cov_shape[0]): for j in range(i,cov_shape[1]): cov = model.covariances[i,j] if cov != 0: tcov = str(cov).replace('**','^') if i == j: shocks_block.append("var " + str(self.model.shocks[i]) + " = " + tcov + " ;") else: shocks_block.append("var " + str(self.model.shocks[i]) + "," + str(self.model.shocks[j]) + " = " + tcov + " ;") shocks_block.append("end;") elif options['dest'] == 'dynare++': shocks_block = [] shocks_block.append("vcov = [") cov_shape = self.covariances.shape shocks_matrix = [] for i in range(cov_shape[0]): shocks_matrix.append(" ".join( map(str,self.covariances[i,:]) )) shocks_block.append( ";\n".join(shocks_matrix)) shocks_block.append( "];" ) initval_block = [] if len(model.init_values)>0: initval_block.append("initval;") for v in order: if v in model.init_values: initval_block.append(str(v) + " = " + str( itd[v] ).replace('**','^') + ";") elif options['dest'] == 'dynare++': # dynare++ doesn't default to zero for non initialized variables initval_block.append(str(v) + " = 0 ;") initval_block.append("end;") #else: #itd = self.get_init_dict() #initval_block = [] #initval_block.append("initval;") #for v in self.model.variables: #if v in self.init_values: #initval_block.append(str(v) + " = " + str(itd[v]) + ";") #initval_block.append("end;") model_text = "" model_text += "\n".join(init_block) model_text += "\n\n" + "\n".join(model_block) model_text += "\n\n" + "\n".join(shocks_block) model_text += "\n\n" + "\n".join(initval_block) if options['steady'] and options['dest']=='dynare': model_text += "\n\nsteady;\n" if options['check'] and options['dest']=='dynare': model_text += "\n\ncheck;\n" if options['dest'] == 'dynare++': model_text += "\n\norder = " + str(options['order']) + ";\n" model_text += "\n" + append if output_file == None: output_file = self.model.fname + '.mod' if output_file != False: f = file(output_file,'w' ) f.write(model_text) f.close() if return_text: return(model_text) else: return None def compute_dynamic_mfile(self,max_order=2): print "Computing dynamic .m file at order {0}.".format(max_order) NonDecreasingTree.symbol_type = TSymbol model = self.model var_order = model.dyn_var_order + model.shocks # TODO create a log system t = [] t.append(time.time()) print(' - compute derivatives ...') sols = [] i = 0 for eq in model.equations: i+=1 ndt = NonDecreasingTree(eq.gap) ndt.compute_nth_order_children(max_order) sols.append(ndt) t.append(time.time()) print(' done ' + str(t[-1] - t[-2])) self.dynamic_derivatives = sols dyn_subs_dict = self.dynamic_substitution_list() dyn_printer = DicPrinter(dyn_subs_dict) txt = """function [residual, {gs}] = {fname}_dynamic(y, x, params, it_) % % Status : Computes dynamic model for Dynare % % Warning : this file is generated automatically by Dynare % from model file (.mod) % % Model equations % residual = zeros({neq}, 1); """ gs = str.join(', ',[('g'+str(i)) for i in range(1,(max_order+1))]) txt = txt.format(gs=gs,fname=model.fname,neq=len(model.equations)) print(' - writing equations ...') t.append(time.time()) for i in range(len(sols)): ndt = sols[i] eq = ndt.expr rhs = dyn_printer.doprint_matlab(eq) txt += ' residual({0}) = {1};\n'.format(i+1,rhs ) t.append(time.time()) print(' done ' + str(t[-1] - t[-2])) for current_order in range(1,(max_order+1)): if current_order == 1: matrix_name = "Jacobian" elif current_order == 2: matrix_name = "Hessian" else: matrix_name = "{0}_th order".format(current_order) txt += """ if nargout >= {orderr} % % {matrix_name} matrix % """.format(orderr=current_order+1,matrix_name=matrix_name) if current_order == 2: txt.format(matrix_name="Hessian") elif current_order == 1: txt.format(matrix_name="Jacobian") print ' - printing {0}th order derivatives'.format(current_order) t.append(time.time()) nnzd = self.NNZDerivatives(current_order) print " {0} derivatives are going to be written".format(nnzd) if True: # we write full matrices ... txt += " v{order} = zeros({nnzd}, 3);\n".format(order=current_order, nnzd=nnzd) i = 0 for n in range(len(sols)): ndt = sols[n] l = ndt.list_nth_order_children(current_order) for nd in l: i += 1 # here we compute indices where we write the derivatives indices = nd.compute_index_set_matlab(var_order) rhs = dyn_printer.doprint_matlab(nd.expr) i0 = indices[0] indices.remove(i0) i_ref = i txt += ' v{order}({i},:) = [{i_eq}, {i_col}, {value}] ;\n'.format(order=current_order,i=i,i_eq=n+1,i_col=i0,value=rhs) for ind in indices: i += 1 txt += ' v{order}({i},:) = [{i_eq}, {i_col}, v{order}({i_ref},3)];\n'.format(order=current_order,i=i,i_eq = n+1,i_col=ind,i_ref=i_ref) txt += ' g{order} = sparse(v{order}(:,1),v{order}(:,2),v{order}(:,3),{n_rows},{n_cols});\n'.format(order=current_order,n_rows=len(model.equations),n_cols=len(var_order)**current_order) else: # ... or sparse matrices print 'to be implemented' txt += """ end """ t.append(time.time()) print(' done ' + str(t[-1] - t[-2])) f = file(model.fname + '_dynamic.m','w') f.write(txt) f.close() return txt def compute_static_mfile(self,max_order=1): print "Computing static .m file at order {0}.".format(max_order) NonDecreasingTree.symbol_type = Variable model = self.model var_order = model.variables # TODO create a log system sols = [] i = 0 for eq in model.equations: i+=1 l = [tv for tv in eq.atoms() if isinstance(tv,Variable)] expr = eq.gap for tv in l: if tv.lag != 0: expr = expr.subs(tv,tv.P) ndt = NonDecreasingTree(expr) ndt.compute_nth_order_children(max_order) sols.append(ndt) self.static_derivatives = sols stat_subs_dict = self.static_substitution_list() stat_printer = DicPrinter(stat_subs_dict) txt = """function [residual, {gs}] = {fname}_static(y, x, params, it_) % % Status : Computes static model for Dynare % % Warning : this file is generated automatically by Dynare % from model file (.mod) % % Model equations % residual = zeros({neq}, 1); """ gs = str.join(', ',[('g'+str(i)) for i in range(1,(max_order+1))]) txt = txt.format(gs=gs,fname=model.fname,neq=len(model.equations)) for i in range(len(sols)): ndt = sols[i] eq = ndt.expr rhs = stat_printer.doprint_matlab(eq) txt += ' residual({0}) = {1};\n'.format(i+1,rhs ) for current_order in range(1,(max_order+1)): if current_order == 1: matrix_name = "Jacobian" elif current_order == 2: matrix_name = "Hessian" else: matrix_name = "{0}_th order".format(current_order) txt += """ if nargout >= {orderr} g{order} = zeros({n_rows}, {n_cols}); % % {matrix_name} matrix % \n""".format(order=current_order,orderr=current_order+1,n_rows=len(model.equations),n_cols=len(var_order)**current_order,matrix_name=matrix_name) if current_order == 2: txt.format(matrix_name="Hessian") # What is the equivalent of NNZ for static files ? nnzd = self.NNZStaticDerivatives(current_order) if True: for n in range(len(sols)): ndt = sols[n] l = ndt.list_nth_order_children(current_order) for nd in l: # here we compute indices where we write the derivatives indices = nd.compute_index_set_matlab(var_order) rhs = stat_printer.doprint_matlab(nd.expr) #rhs = comp.dyn_tabify_expression(nd.expr) i0 = indices[0] indices.remove(i0) txt += ' g{order}({0},{1}) = {2};\n'.format(n+1,i0,rhs,order=current_order) for ind in indices: txt += ' g{order}({0},{1}) = g{order}({0},{2});\n'.format(n+1,ind,i0,order=current_order) else: print 'to be implemented' txt += """ end """ f = file(model.fname + '_static.m','w') f.write(txt) f.close() return txt def export_infos(self): from dolo.misc.matlab import struct_to_mat, value_to_mat model = self.model txt = 'global infos_;\n' txt += struct_to_mat(model.info,'infos_') # we compute the list of portfolio equations def select(x): if x.tags.get('portfolio','false') == 'true': return '1' else: return '0' txt += 'infos_.portfolio_equations = [%s];\n' % str.join(' ',[select(x) for x in model.equations]) incidence_matrix = model.incidence_matrix_static() txt += 'infos_.incidence_matrix_static = %s;\n' % value_to_mat(incidence_matrix) f = file(model.fname + '_infos.m','w') f.write(txt) f.close() def compute_static_pfile(self,max_order): NonDecreasingTree.symbol_type = Variable model = self.model var_order = model.variables # TODO create a log system sols = [] i = 0 for eq in model.equations: i+=1 l = [tv for tv in eq.atoms() if isinstance(tv,Variable)] expr = eq.gap for tv in l: if tv.lag != 0: expr = expr.subs(tv,tv.P) ndt = NonDecreasingTree(expr) ndt.compute_nth_order_children(max_order) sols.append(ndt) self.static_derivatives = sols stat_subs_dict = self.static_substitution_list(ind_0=0,brackets = True) stat_printer = DicPrinter(stat_subs_dict) txt = """def static_gaps(y, x, params): # # Status : Computes static model for Python # # Warning : this file is generated automatically by Dynare # from model file (.mod) # # # Model equations # import numpy as np from numpy import exp,log it_ = 1 # should remove this ! g = [] residual = np.zeros({neq}) """ gs = str.join(', ',[('g'+str(i)) for i in range(1,(max_order+1))]) txt = txt.format(gs=gs,fname=model.fname,neq=len(model.equations)) for i in range(len(sols)): ndt = sols[i] eq = ndt.expr rhs = stat_printer.doprint_matlab(eq) txt += ' residual[{0}] = {1}\n'.format(i,rhs ) txt += ' g.append(residual)\n' for current_order in range(1,(max_order+1)): if current_order == 1: matrix_name = "Jacobian" elif current_order == 2: matrix_name = "Hessian" else: matrix_name = "{0}_th order".format(current_order) txt += """ g{order} = np.zeros(({n_rows}, {n_cols})) # {matrix_name} matrix\n""".format(order=current_order,orderr=current_order+1,n_rows=len(model.equations),n_cols=len(var_order)**current_order,matrix_name=matrix_name) for n in range(len(sols)): ndt = sols[n] l = ndt.list_nth_order_children(current_order) for nd in l: # here we compute indices where we write the derivatives indices = nd.compute_index_set_matlab(var_order) rhs = stat_printer.doprint_matlab(nd.expr) #rhs = comp.dyn_tabify_expression(nd.expr) i0 = indices[0] indices.remove(i0) txt += ' g{order}[{0},{1}] = {2}\n'.format(n,i0-1,rhs,order=current_order) for ind in indices: txt += ' g{order}[{0},{1}] = g{order}[{0},{2}]\n'.format(n,ind-1,i0-1,order=current_order) txt += ' g.append(g{order})\n'.format(order=current_order) txt += " return g\n" txt = txt.replace('^','**') exec txt return static_gaps def compute_dynamic_pfile(self,max_order=1): NonDecreasingTree.symbol_type = TSymbol model = self.model var_order = model.dyn_var_order + model.shocks # TODO create a log system sols = [] i = 0 for eq in model.equations: i+=1 ndt = NonDecreasingTree(eq.gap) ndt.compute_nth_order_children(max_order) sols.append(ndt) self.dynamic_derivatives = sols dyn_subs_dict = self.dynamic_substitution_list(ind_0=0,brackets = True) dyn_printer = DicPrinter(dyn_subs_dict) txt = """def dynamic_gaps(y, x, params): # # Status : Computes dynamic model for Dynare # # Warning : this file is generated automatically by Dynare # from model file (.mod) # # Model equations # it_ = 0 import numpy as np from numpy import exp, log g = [] residual = np.zeros({neq}); """ gs = str.join(', ',[('g'+str(i)) for i in range(1,(max_order+1))]) txt = txt.format(gs=gs,fname=model.fname,neq=len(model.equations)) for i in range(len(sols)): ndt = sols[i] eq = ndt.expr rhs = dyn_printer.doprint_matlab(eq) txt += ' residual[{0}] = {1};\n'.format(i,rhs ) txt += ' g.append(residual)\n' for current_order in range(1,(max_order+1)): if current_order == 1: matrix_name = "Jacobian" elif current_order == 2: matrix_name = "Hessian" else: matrix_name = "{0}_th order".format(current_order) txt += """ # # {matrix_name} matrix # """.format(orderr=current_order+1,matrix_name=matrix_name) if current_order == 2: txt.format(matrix_name="Hessian") elif current_order == 1: txt.format(matrix_name="Jacobian") #nnzd = self.NNZDerivatives(current_order) n_cols = (len(var_order),)*current_order n_cols = ','.join( [str(s) for s in n_cols] ) txt += " g{order} = np.zeros( ({n_eq}, {n_cols}) );\n".format(order=current_order,n_eq=len(model.equations), n_cols=n_cols ) for n in range(len(sols)): ndt = sols[n] l = ndt.list_nth_order_children(current_order) for nd in l: # here we compute indices where we write the derivatives indices = nd.compute_index_set(var_order) rhs = dyn_printer.doprint_matlab(nd.expr) i0 = indices[0] i_col_s = ','.join([str(nn) for nn in i0]) indices.remove(i0) i_col_s_ref = i_col_s txt += ' g{order}[{i_eq},{i_col}] = {value}\n'.format(order=current_order,i_eq=n,i_col=i_col_s,value=rhs) for ind in indices: i += 1 i_col_s = ','.join([str(nn) for nn in ind]) txt += ' g{order}[{i_eq},{i_col}] = g{order}[{i_eq},{i_col_ref}] \n'.format(order=current_order,i_eq = n,i_col=i_col_s,i_col_ref = i_col_s_ref) txt += " g.append(g{order})\n".format(order=current_order) txt += " return g\n" txt = txt.replace('^','**') exec txt return dynamic_gaps def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) In compiler_dynare.py : - removed unnecessary messages - temporary fixed for arguments appearing in init_values, not in model from dolo.misc.nth_order_derivatives import NonDecreasingTree from compiler import * import sympy from dolo.misc.nth_order_derivatives import * import time class CustomPrinter(sympy.printing.StrPrinter): def _print_TSymbol(self, expr): return expr.__str__() class DynareCompiler(Compiler): def compute_main_file(self,omit_nnz=True): model = self.model # should be computed somewhere else all_symbols = set([]) for eq in model.equations: all_symbols.update( eq.atoms() ) format_dict = dict() format_dict['fname'] = model.fname format_dict['maximum_lag'] = max([-v.lag for v in all_symbols if isinstance(v,TSymbol)]) format_dict['maximum_lead'] = max([v.lag for v in all_symbols if isinstance(v,TSymbol)]) format_dict['maximum_endo_lag'] = max([-v.lag for v in all_symbols if isinstance(v,Variable)]) format_dict['maximum_endo_lead'] = max([v.lag for v in all_symbols if isinstance(v,Variable)]) format_dict['maximum_exo_lag'] = max([-v.lag for v in all_symbols if isinstance(v,Shock)]) format_dict['maximum_exo_lead'] = max([v.lag for v in all_symbols if isinstance(v,Shock)]) format_dict['endo_nbr'] = len(model.variables) format_dict['exo_nbr'] = len(model.shocks) format_dict['param_nbr'] = len(model.parameters) output = """% % Status : main Dynare file % % Warning : this file is generated automatically by Dolo for Dynare % from model file (.mod) clear all tic; global M_ oo_ options_ global ys0_ ex0_ ct_ options_ = []; M_.fname = '{fname}'; % % Some global variables initialization % global_initialization; diary off; warning_old_state = warning; warning off; delete {fname}.log; warning warning_old_state; logname_ = '{fname}.log'; diary {fname}.log; options_.model_mode = 0; erase_compiled_function('{fname}_static'); erase_compiled_function('{fname}_dynamic'); M_.exo_det_nbr = 0; M_.exo_nbr = {exo_nbr}; M_.endo_nbr = {endo_nbr}; M_.param_nbr = {param_nbr}; M_.Sigma_e = zeros({exo_nbr}, {exo_nbr}); M_.exo_names_orig_ord = [1:{exo_nbr}]; """.format( **format_dict ) string_of_names = lambda l: str.join(' , ',["'%s'"%str(v) for v in l]) string_of_tex_names = lambda l: str.join(' , ',["'%s'"%v._latex_() for v in l]) output += "M_.exo_names = strvcat( {0} );\n" .format(string_of_names(model.shocks)) output += "M_.exo_names_tex = strvcat( {0} );\n".format(string_of_tex_names(model.shocks)) output += "M_.endo_names = strvcat( {0} );\n".format(string_of_names(model.variables)) output += "M_.endo_names_tex = strvcat( {0} );\n".format(string_of_tex_names(model.variables)) output += "M_.param_names = strvcat( {0} );\n".format( string_of_names(model.parameters) ) output += "M_.param_names_tex = strvcat( {0} );\n".format( string_of_tex_names(model.parameters) ) from dolo.misc.matlab import value_to_mat lli = value_to_mat(self.lead_lag_incidence_matrix()) output += "M_.lead_lag_incidence = {0}';\n".format(lli) output += """M_.maximum_lag = {maximum_lag}; M_.maximum_lead = {maximum_lead}; M_.maximum_endo_lag = {maximum_endo_lag}; M_.maximum_endo_lead = {maximum_endo_lead}; M_.maximum_exo_lag = {maximum_exo_lag}; M_.maximum_exo_lead = {maximum_exo_lead}; oo_.steady_state = zeros({endo_nbr}, 1); oo_.exo_steady_state = zeros({exo_nbr}, 1); M_.params = repmat(NaN,{param_nbr}, 1); """.format( **format_dict ) # Now we add tags for equations tags_array_string = [] for eq in model.equations: for k in eq.tags.keys(): tags_array_string.append( "{n}, '{key}', '{value}'".format(n=eq.n, key=k, value=eq.tags[k]) ) output += "M_.equations_tags = {{\n{0}\n}};\n".format(";\n".join(tags_array_string)) if not omit_nnz: # we don't set the number of non zero derivatives yet order = max([ndt.depth() for ndt in self.dynamic_derivatives]) output += "M_.NNZDerivatives = zeros({0}, 1); % parrot mode\n".format(order) output += "M_.NNZDerivatives(1) = {0}; % parrot mode\n".format(self.NNZDerivatives(1)) output += "M_.NNZDerivatives(2) = {0}; % parrot mode\n".format(self.NNZDerivatives(2)) output += "M_.NNZDerivatives(3) = {0}; % parrot mode\n".format(self.NNZDerivatives(3)) idp = DicPrinter(self.static_substitution_list(y='oo_.steady_state',params='M_.params')) # BUG: how do we treat parameters absent from the model, but present in parameters_values ? porder = model.order_parameters_values() porder = [p for p in porder if p in model.parameters] vorder = model.order_init_values() for p in porder: i = model.parameters.index(p) + 1 output += "M_.params({0}) = {1};\n".format(i,idp.doprint_matlab(model.parameters_values[p])) output += "{0} = M_.params({1});\n".format(p,i) output += '''% % INITVAL instructions % ''' #idp = DicPrinter(self.static_substitution_list(y='oo_.steady_state',params='M_.params')) output += "options_.initval_file = 0; % parrot mode\n" for v in vorder: if v in self.model.variables: # should be removed i = model.variables.index(v) + 1 output += "oo_.steady_state({0}) = {1};\n".format(i,idp.doprint_matlab(model.init_values[v])) # we don't allow initialization of shocks to nonzero values output += "oo_.exo_steady_state = zeros({0},1);\n".format( len(model.shocks) ) output += '''oo_.endo_simul=[oo_.steady_state*ones(1,M_.maximum_lag)]; if M_.exo_nbr > 0; oo_.exo_simul = [ones(M_.maximum_lag,1)*oo_.exo_steady_state']; end; if M_.exo_det_nbr > 0; oo_.exo_det_simul = [ones(M_.maximum_lag,1)*oo_.exo_det_steady_state']; end; ''' #output += '''steady; output +=""" % % SHOCKS instructions % make_ex_; M_.exo_det_length = 0; % parrot """ for i in range(model.covariances.shape[0]): for j in range(model.covariances.shape[1]): expr = model.covariances[i,j] if expr != 0: v = str(expr).replace("**","^") #if (v != 0) and not isinstance(v,sympy.core.numbers.Zero): output += "M_.Sigma_e({0}, {1}) = {2};\n".format(i+1,j+1,v) # This results from the stoch_simul( # output += '''options_.drop = 200; #options_.order = 3; #var_list_=[]; #info = stoch_simul(var_list_); #''' # # output += '''save('example2_results.mat', 'oo_', 'M_', 'options_'); #diary off # #disp(['Total computing time : ' dynsec2hms(toc) ]);''' f = file(model.fname + '.m','w') f.write(output) f.close() return output def NNZDerivatives(self,order): n = 0 for ndt in self.dynamic_derivatives: # @type ndt NonDecreasingTree l = ndt.list_nth_order_children(order) for c in l: # we must compute the number of permutations vars = c.vars s = factorial(len(vars)) for v in set(vars): s = s / factorial(vars.count(v)) n += s return n def NNZStaticDerivatives(self,order): n = 0 for ndt in self.static_derivatives: # @type ndt NonDecreasingTree l = ndt.list_nth_order_children(order) for c in l: # we must compute the number of permutations vars = c.vars s = factorial(len(vars)) for v in set(vars): s = s / factorial(vars.count(v)) n += s return n def export_to_modfile(self,output_file=None,return_text=False,options={},append="",comments = "", solve_init_state=False): model = self.model #init_state = self.get_init_dict() default = {'steady':False,'check':False,'dest':'dynare','order':1}#default options for o in default: if not o in options: options[o] = default[o] init_block = ["// Generated by Dolo"] init_block.append( "// Model basename : " + self.model.fname) init_block.append(comments) init_block.append( "" ) init_block.append( "var " + str.join(",", map(str,self.model.variables) ) + ";") init_block.append( "" ) init_block.append( "varexo " + str.join(",", map(str,self.model.shocks) ) + ";" ) init_block.append( "" ) init_block.append( "parameters " + str.join(",",map(str,self.model.parameters)) + ";" ) init_state = model.parameters_values.copy() init_state.update( model.init_values.copy() ) from dolo.misc.calculus import solve_triangular_system if not solve_init_state: itd = model.init_values order = solve_triangular_system(init_state,return_order=True) else: itd,order = calculus.solve_triangular_system(init_state) for p in order: if p in model.parameters: #init_block.append(p.name + " = " + str(init_state[p]) + ";") if p in model.parameters_values: init_block.append(p.name + " = " + str(model.parameters_values[p]).replace('**','^') + ";") printer = CustomPrinter() model_block = [] model_block.append( "model;" ) for eq in self.model.equations: s = printer.doprint(eq) s = s.replace("==","=") s = s.replace("**","^") # s = s.replace("_b1","(-1)") # this should allow lags more than 1 # s = s.replace("_f1","(+1)") # this should allow lags more than 1 model_block += "\n" if 'name' in eq.tags: model_block.append("// eq %s : %s" %(eq.n,eq.tags.get('name'))) else: model_block.append("// eq %s" %(eq.n)) if len(eq.tags)>0: model_block.append("[ {0} ]".format(" , ".join(["{0} = '{1}'".format(k,eq.tags[k]) for k in eq.tags]))) model_block.append(s + ";") model_block.append( "end;" ) if options['dest'] == 'dynare': shocks_block = [] if model.covariances != None: shocks_block.append("shocks;") cov_shape = model.covariances.shape for i in range(cov_shape[0]): for j in range(i,cov_shape[1]): cov = model.covariances[i,j] if cov != 0: tcov = str(cov).replace('**','^') if i == j: shocks_block.append("var " + str(self.model.shocks[i]) + " = " + tcov + " ;") else: shocks_block.append("var " + str(self.model.shocks[i]) + "," + str(self.model.shocks[j]) + " = " + tcov + " ;") shocks_block.append("end;") elif options['dest'] == 'dynare++': shocks_block = [] shocks_block.append("vcov = [") cov_shape = self.covariances.shape shocks_matrix = [] for i in range(cov_shape[0]): shocks_matrix.append(" ".join( map(str,self.covariances[i,:]) )) shocks_block.append( ";\n".join(shocks_matrix)) shocks_block.append( "];" ) initval_block = [] if len(model.init_values)>0: initval_block.append("initval;") for v in order: if v in model.init_values: initval_block.append(str(v) + " = " + str( itd[v] ).replace('**','^') + ";") elif options['dest'] == 'dynare++': # dynare++ doesn't default to zero for non initialized variables initval_block.append(str(v) + " = 0 ;") initval_block.append("end;") #else: #itd = self.get_init_dict() #initval_block = [] #initval_block.append("initval;") #for v in self.model.variables: #if v in self.init_values: #initval_block.append(str(v) + " = " + str(itd[v]) + ";") #initval_block.append("end;") model_text = "" model_text += "\n".join(init_block) model_text += "\n\n" + "\n".join(model_block) model_text += "\n\n" + "\n".join(shocks_block) model_text += "\n\n" + "\n".join(initval_block) if options['steady'] and options['dest']=='dynare': model_text += "\n\nsteady;\n" if options['check'] and options['dest']=='dynare': model_text += "\n\ncheck;\n" if options['dest'] == 'dynare++': model_text += "\n\norder = " + str(options['order']) + ";\n" model_text += "\n" + append if output_file == None: output_file = self.model.fname + '.mod' if output_file != False: f = file(output_file,'w' ) f.write(model_text) f.close() if return_text: return(model_text) else: return None def compute_dynamic_mfile(self,max_order=2): print "Computing dynamic .m file at order {0}.".format(max_order) NonDecreasingTree.symbol_type = TSymbol model = self.model var_order = model.dyn_var_order + model.shocks # TODO create a log system t = [] t.append(time.time()) sols = [] i = 0 for eq in model.equations: i+=1 ndt = NonDecreasingTree(eq.gap) ndt.compute_nth_order_children(max_order) sols.append(ndt) t.append(time.time()) self.dynamic_derivatives = sols dyn_subs_dict = self.dynamic_substitution_list() dyn_printer = DicPrinter(dyn_subs_dict) txt = """function [residual, {gs}] = {fname}_dynamic(y, x, params, it_) % % Status : Computes dynamic model for Dynare % % Warning : this file is generated automatically by Dynare % from model file (.mod) % % Model equations % residual = zeros({neq}, 1); """ gs = str.join(', ',[('g'+str(i)) for i in range(1,(max_order+1))]) txt = txt.format(gs=gs,fname=model.fname,neq=len(model.equations)) t.append(time.time()) for i in range(len(sols)): ndt = sols[i] eq = ndt.expr rhs = dyn_printer.doprint_matlab(eq) txt += ' residual({0}) = {1};\n'.format(i+1,rhs ) t.append(time.time()) for current_order in range(1,(max_order+1)): if current_order == 1: matrix_name = "Jacobian" elif current_order == 2: matrix_name = "Hessian" else: matrix_name = "{0}_th order".format(current_order) txt += """ if nargout >= {orderr} % % {matrix_name} matrix % """.format(orderr=current_order+1,matrix_name=matrix_name) if current_order == 2: txt.format(matrix_name="Hessian") elif current_order == 1: txt.format(matrix_name="Jacobian") t.append(time.time()) nnzd = self.NNZDerivatives(current_order) if True: # we write full matrices ... txt += " v{order} = zeros({nnzd}, 3);\n".format(order=current_order, nnzd=nnzd) i = 0 for n in range(len(sols)): ndt = sols[n] l = ndt.list_nth_order_children(current_order) for nd in l: i += 1 # here we compute indices where we write the derivatives indices = nd.compute_index_set_matlab(var_order) rhs = dyn_printer.doprint_matlab(nd.expr) i0 = indices[0] indices.remove(i0) i_ref = i txt += ' v{order}({i},:) = [{i_eq}, {i_col}, {value}] ;\n'.format(order=current_order,i=i,i_eq=n+1,i_col=i0,value=rhs) for ind in indices: i += 1 txt += ' v{order}({i},:) = [{i_eq}, {i_col}, v{order}({i_ref},3)];\n'.format(order=current_order,i=i,i_eq = n+1,i_col=ind,i_ref=i_ref) txt += ' g{order} = sparse(v{order}(:,1),v{order}(:,2),v{order}(:,3),{n_rows},{n_cols});\n'.format(order=current_order,n_rows=len(model.equations),n_cols=len(var_order)**current_order) else: # ... or sparse matrices print 'to be implemented' txt += """ end """ t.append(time.time()) f = file(model.fname + '_dynamic.m','w') f.write(txt) f.close() return txt def compute_static_mfile(self,max_order=1): print "Computing static .m file at order {0}.".format(max_order) NonDecreasingTree.symbol_type = Variable model = self.model var_order = model.variables # TODO create a log system sols = [] i = 0 for eq in model.equations: i+=1 l = [tv for tv in eq.atoms() if isinstance(tv,Variable)] expr = eq.gap for tv in l: if tv.lag != 0: expr = expr.subs(tv,tv.P) ndt = NonDecreasingTree(expr) ndt.compute_nth_order_children(max_order) sols.append(ndt) self.static_derivatives = sols stat_subs_dict = self.static_substitution_list() stat_printer = DicPrinter(stat_subs_dict) txt = """function [residual, {gs}] = {fname}_static(y, x, params, it_) % % Status : Computes static model for Dynare % % Warning : this file is generated automatically by Dynare % from model file (.mod) % % Model equations % residual = zeros({neq}, 1); """ gs = str.join(', ',[('g'+str(i)) for i in range(1,(max_order+1))]) txt = txt.format(gs=gs,fname=model.fname,neq=len(model.equations)) for i in range(len(sols)): ndt = sols[i] eq = ndt.expr rhs = stat_printer.doprint_matlab(eq) txt += ' residual({0}) = {1};\n'.format(i+1,rhs ) for current_order in range(1,(max_order+1)): if current_order == 1: matrix_name = "Jacobian" elif current_order == 2: matrix_name = "Hessian" else: matrix_name = "{0}_th order".format(current_order) txt += """ if nargout >= {orderr} g{order} = zeros({n_rows}, {n_cols}); % % {matrix_name} matrix % \n""".format(order=current_order,orderr=current_order+1,n_rows=len(model.equations),n_cols=len(var_order)**current_order,matrix_name=matrix_name) if current_order == 2: txt.format(matrix_name="Hessian") # What is the equivalent of NNZ for static files ? nnzd = self.NNZStaticDerivatives(current_order) if True: for n in range(len(sols)): ndt = sols[n] l = ndt.list_nth_order_children(current_order) for nd in l: # here we compute indices where we write the derivatives indices = nd.compute_index_set_matlab(var_order) rhs = stat_printer.doprint_matlab(nd.expr) #rhs = comp.dyn_tabify_expression(nd.expr) i0 = indices[0] indices.remove(i0) txt += ' g{order}({0},{1}) = {2};\n'.format(n+1,i0,rhs,order=current_order) for ind in indices: txt += ' g{order}({0},{1}) = g{order}({0},{2});\n'.format(n+1,ind,i0,order=current_order) else: print 'to be implemented' txt += """ end """ f = file(model.fname + '_static.m','w') f.write(txt) f.close() return txt def export_infos(self): from dolo.misc.matlab import struct_to_mat, value_to_mat model = self.model txt = 'global infos_;\n' txt += struct_to_mat(model.info,'infos_') # we compute the list of portfolio equations def select(x): if x.tags.get('portfolio','false') == 'true': return '1' else: return '0' txt += 'infos_.portfolio_equations = [%s];\n' % str.join(' ',[select(x) for x in model.equations]) incidence_matrix = model.incidence_matrix_static() txt += 'infos_.incidence_matrix_static = %s;\n' % value_to_mat(incidence_matrix) f = file(model.fname + '_infos.m','w') f.write(txt) f.close() def compute_static_pfile(self,max_order): NonDecreasingTree.symbol_type = Variable model = self.model var_order = model.variables # TODO create a log system sols = [] i = 0 for eq in model.equations: i+=1 l = [tv for tv in eq.atoms() if isinstance(tv,Variable)] expr = eq.gap for tv in l: if tv.lag != 0: expr = expr.subs(tv,tv.P) ndt = NonDecreasingTree(expr) ndt.compute_nth_order_children(max_order) sols.append(ndt) self.static_derivatives = sols stat_subs_dict = self.static_substitution_list(ind_0=0,brackets = True) stat_printer = DicPrinter(stat_subs_dict) txt = """def static_gaps(y, x, params): # # Status : Computes static model for Python # # Warning : this file is generated automatically by Dynare # from model file (.mod) # # # Model equations # import numpy as np from numpy import exp,log it_ = 1 # should remove this ! g = [] residual = np.zeros({neq}) """ gs = str.join(', ',[('g'+str(i)) for i in range(1,(max_order+1))]) txt = txt.format(gs=gs,fname=model.fname,neq=len(model.equations)) for i in range(len(sols)): ndt = sols[i] eq = ndt.expr rhs = stat_printer.doprint_matlab(eq) txt += ' residual[{0}] = {1}\n'.format(i,rhs ) txt += ' g.append(residual)\n' for current_order in range(1,(max_order+1)): if current_order == 1: matrix_name = "Jacobian" elif current_order == 2: matrix_name = "Hessian" else: matrix_name = "{0}_th order".format(current_order) txt += """ g{order} = np.zeros(({n_rows}, {n_cols})) # {matrix_name} matrix\n""".format(order=current_order,orderr=current_order+1,n_rows=len(model.equations),n_cols=len(var_order)**current_order,matrix_name=matrix_name) for n in range(len(sols)): ndt = sols[n] l = ndt.list_nth_order_children(current_order) for nd in l: # here we compute indices where we write the derivatives indices = nd.compute_index_set_matlab(var_order) rhs = stat_printer.doprint_matlab(nd.expr) #rhs = comp.dyn_tabify_expression(nd.expr) i0 = indices[0] indices.remove(i0) txt += ' g{order}[{0},{1}] = {2}\n'.format(n,i0-1,rhs,order=current_order) for ind in indices: txt += ' g{order}[{0},{1}] = g{order}[{0},{2}]\n'.format(n,ind-1,i0-1,order=current_order) txt += ' g.append(g{order})\n'.format(order=current_order) txt += " return g\n" txt = txt.replace('^','**') exec txt return static_gaps def compute_dynamic_pfile(self,max_order=1): NonDecreasingTree.symbol_type = TSymbol model = self.model var_order = model.dyn_var_order + model.shocks # TODO create a log system sols = [] i = 0 for eq in model.equations: i+=1 ndt = NonDecreasingTree(eq.gap) ndt.compute_nth_order_children(max_order) sols.append(ndt) self.dynamic_derivatives = sols dyn_subs_dict = self.dynamic_substitution_list(ind_0=0,brackets = True) dyn_printer = DicPrinter(dyn_subs_dict) txt = """def dynamic_gaps(y, x, params): # # Status : Computes dynamic model for Dynare # # Warning : this file is generated automatically by Dynare # from model file (.mod) # # Model equations # it_ = 0 import numpy as np from numpy import exp, log g = [] residual = np.zeros({neq}); """ gs = str.join(', ',[('g'+str(i)) for i in range(1,(max_order+1))]) txt = txt.format(gs=gs,fname=model.fname,neq=len(model.equations)) for i in range(len(sols)): ndt = sols[i] eq = ndt.expr rhs = dyn_printer.doprint_matlab(eq) txt += ' residual[{0}] = {1};\n'.format(i,rhs ) txt += ' g.append(residual)\n' for current_order in range(1,(max_order+1)): if current_order == 1: matrix_name = "Jacobian" elif current_order == 2: matrix_name = "Hessian" else: matrix_name = "{0}_th order".format(current_order) txt += """ # # {matrix_name} matrix # """.format(orderr=current_order+1,matrix_name=matrix_name) if current_order == 2: txt.format(matrix_name="Hessian") elif current_order == 1: txt.format(matrix_name="Jacobian") #nnzd = self.NNZDerivatives(current_order) n_cols = (len(var_order),)*current_order n_cols = ','.join( [str(s) for s in n_cols] ) txt += " g{order} = np.zeros( ({n_eq}, {n_cols}) );\n".format(order=current_order,n_eq=len(model.equations), n_cols=n_cols ) for n in range(len(sols)): ndt = sols[n] l = ndt.list_nth_order_children(current_order) for nd in l: # here we compute indices where we write the derivatives indices = nd.compute_index_set(var_order) rhs = dyn_printer.doprint_matlab(nd.expr) i0 = indices[0] i_col_s = ','.join([str(nn) for nn in i0]) indices.remove(i0) i_col_s_ref = i_col_s txt += ' g{order}[{i_eq},{i_col}] = {value}\n'.format(order=current_order,i_eq=n,i_col=i_col_s,value=rhs) for ind in indices: i += 1 i_col_s = ','.join([str(nn) for nn in ind]) txt += ' g{order}[{i_eq},{i_col}] = g{order}[{i_eq},{i_col_ref}] \n'.format(order=current_order,i_eq = n,i_col=i_col_s,i_col_ref = i_col_s_ref) txt += " g.append(g{order})\n".format(order=current_order) txt += " return g\n" txt = txt.replace('^','**') exec txt return dynamic_gaps def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
# Copyright 2013,2014 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Dunya # # Dunya 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 (FSF), 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/ import os import logging eyed3api = None try: import eyed3 import eyed3.mp3 eyed3.utils.log.log.setLevel(logging.ERROR) eyed3api = "new" except ImportError: pass try: import eyeD3 eyed3api = "old" except ImportError: pass if not eyed3api: raise ImportError("Cannot find eyed3 or eyeD3") def has_musicbrainz_tags(fname): """Return true if a file has musicbrainz tags set.""" pass def get_coverart(fname): """Get the embedded coverart, or None. Currently returns the first found coverart.""" audfile = eyed3.load(fname) images = audfile.tag.frame_set.get("APIC", []) if images: for i in images: if i.picture_type == i.FRONT_COVER: return i.image_data return images[0].image_data else: return None def is_mp3_file(fname): return os.path.isfile(fname) and fname.lower().endswith(".mp3") def _mb_id(tag, key): if eyed3api == "old": texttags = tag.getUserTextFrames() elif eyed3api == "new": texttags = tag.frame_set.get("TXXX", []) tags = [t for t in texttags if t.description == key] if len(tags): return tags[0].text else: return None def mb_release_id(tag): """Return the Musicbrainz release ID in an eyed3 tag""" return _mb_id(tag, "MusicBrainz Album Id") def mb_artist_id(tag): return _mb_id(tag, "MusicBrainz Artist Id") def mb_recording_id(tag): if eyed3api == "old": ids = tag.getUniqueFileIDs() else: ids = list(tag.unique_file_ids) for i in ids: if i.owner_id == "http://musicbrainz.org": d = i.data.split("\0") return d[-1] return None def file_metadata(fname): """ Get the file metadata for an mp3 file. The argument is expected to be an mp3 file. No checking is done """ print fname if eyed3api == "old": audfile = eyeD3.Mp3AudioFile(fname) if not audfile: return None duration = audfile.play_time artist = audfile.tag.getArtist() title = audfile.tag.getTitle() release = audfile.tag.getAlbum() elif eyed3api == "new": # We load the file directly instead of using .load() because # load calls magic(), which is not threadsafe. audfile = eyed3.mp3.Mp3AudioFile(fname) if not audfile: return None duration = audfile.info.time_secs artist = audfile.tag.artist title = audfile.tag.title release = audfile.tag.album releaseid = mb_release_id(audfile.tag) # TODO: Album release artist. # TODO: If there are 2 artists, the tags are separated by '; ' # TODO: In id3 2.4 it's a \0 artistid = mb_artist_id(audfile.tag) recordingid = mb_recording_id(audfile.tag) return {"file": fname, "duration": duration, "meta": {"artist": artist, "title": title, "release": release, "releaseid": releaseid, "artistid": artistid, "recordingid": recordingid } } Updated ID3 lookup # Copyright 2013,2014 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Dunya # # Dunya 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 (FSF), 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/ import os import logging eyed3api = None try: import eyed3 import eyed3.mp3 eyed3.utils.log.log.setLevel(logging.ERROR) eyed3api = "new" except ImportError: pass try: import eyeD3 eyed3api = "old" except ImportError: pass if not eyed3api: raise ImportError("Cannot find eyed3 or eyeD3") def has_musicbrainz_tags(fname): """Return true if a file has musicbrainz tags set.""" pass def get_coverart(fname): """Get the embedded coverart, or None. Currently returns the first found coverart.""" audfile = eyed3.load(fname) images = audfile.tag.frame_set.get("APIC", []) if images: for i in images: if i.picture_type == i.FRONT_COVER: return i.image_data return images[0].image_data else: return None def is_mp3_file(fname): return os.path.isfile(fname) and fname.lower().endswith(".mp3") def _mb_id(tag, key): if eyed3api == "old": texttags = tag.getUserTextFrames() elif eyed3api == "new": texttags = tag.frame_set.get("TXXX", []) tags = [t for t in texttags if t.description == key] if len(tags): return tags[0].text else: return None def mb_release_id(tag): """Return the Musicbrainz release ID in an eyed3 tag""" return _mb_id(tag, "MusicBrainz Album Id") def mb_artist_id(tag): return _mb_id(tag, "MusicBrainz Artist Id") def mb_recording_id(tag): if eyed3api == "old": ids = tag.getUniqueFileIDs() else: ids = list(tag.unique_file_ids) for i in ids: if i.owner_id == "http://musicbrainz.org": d = i.data.split("\0") return d[-1] return None def file_metadata(fname): """ Get the file metadata for an mp3 file. The argument is expected to be an mp3 file. No checking is done """ if eyed3api == "old": audfile = eyeD3.Mp3AudioFile(fname) if not audfile: return None duration = audfile.play_time artist = audfile.tag.getArtist() title = audfile.tag.getTitle() release = audfile.tag.getAlbum() elif eyed3api == "new": # We load the file directly instead of using .load() because # load calls magic(), which is not threadsafe. audfile = eyed3.mp3.Mp3AudioFile(fname) if not audfile or not audfile.tag: return None duration = audfile.info.time_secs artist = audfile.tag.artist title = audfile.tag.title release = audfile.tag.album releaseid = mb_release_id(audfile.tag) # TODO: Album release artist. # TODO: If there are 2 artists, the tags are separated by '; ' # TODO: In id3 2.4 it's a \0 artistid = mb_artist_id(audfile.tag) recordingid = mb_recording_id(audfile.tag) return {"file": fname, "duration": duration, "meta": {"artist": artist, "title": title, "release": release, "releaseid": releaseid, "artistid": artistid, "recordingid": recordingid } }
from flask import Flask, render_template, request import json # pyMongodb wrapper from kyzr_db import dbEditor kyzr = dbEditor() # Setup flask app = Flask(__name__) # Main homepage # TODO: Add login ability and other inputs @app.route('/') def index(): return render_template('index.html') # Map page # TODO: Merge with homepage (?) # Call map data from database # Have input from phone ID #@app.route('/maps/<coords>') @app.route('/maps', methods=['GET', 'POST']) def maps(): coords = [] center = [0,0] if(request.method=="POST"): if("id" in request.form.keys()): user = kyzr.find_user(request.form["id"]) if(user is not None): coords = user['locs'] else: return "ID: " + id_request + " not found" if coords: center = [ float(sum(i)/len(i)) for i in ([coords[j][0] for j in coords], [coords[k][1] for k in coords]) ] #center = [42.2927482, -71.2640407] #return render_template('maps.html', coords=json.dumps(coords), center=json.dumps(center)) return render_template('error.html', coords=json.dumps(coords), center=json.dumps(center)) #return render_template('error.html', coords=coords, center=center) # Next two functions are for database # adding/receiving for the android phones @app.route('/dbadd', methods=['GET','POST']) def dbadd(): if request.method=="POST": if("lat" in request.form.keys() and "lng" in request.form.keys() and "id1" in request.form.keys() and "id2" in request.form.keys()): for key in request.form.keys(): if key == "lat": try: lat = float(request.form[key]) except: return "Request Failed: latitude was not a float" elif key == "lng": try: lng = float(request.form[key]) except: return "Request Failed: longitude was not a float" elif key == "id1": phone1_id = request.form[key] elif key == "id2": phone2_id = request.form[key] kyzr.swap_torch(phone1_id, phone2_id, lat, lng) return "Success" return "Request method failed." if __name__ == "__main__": app.run() Fixed center finder from flask import Flask, render_template, request import json # pyMongodb wrapper from kyzr_db import dbEditor kyzr = dbEditor() # Setup flask app = Flask(__name__) # Main homepage # TODO: Add login ability and other inputs @app.route('/') def index(): return render_template('index.html') # Map page # TODO: Merge with homepage (?) # Call map data from database # Have input from phone ID #@app.route('/maps/<coords>') @app.route('/maps', methods=['GET', 'POST']) def maps(): coords = [] center = [0,0] if(request.method=="POST"): if("id" in request.form.keys()): user = kyzr.find_user(request.form["id"]) if(user is not None): coords = user['locs'] else: return "ID: " + id_request + " not found" if coords: center = [ float(sum(i)/len(i)) for i in ([coords[j][0] for j in xrange(len(coords))], [coords[k][1] for k in xrange(len(coords))]) ] #return render_template('maps.html', coords=json.dumps(coords), center=json.dumps(center)) return render_template('error.html', coords=json.dumps(coords), center=json.dumps(center)) # Next two functions are for database # adding/receiving for the android phones @app.route('/dbadd', methods=['GET','POST']) def dbadd(): if request.method=="POST": if("lat" in request.form.keys() and "lng" in request.form.keys() and "id1" in request.form.keys() and "id2" in request.form.keys()): for key in request.form.keys(): if key == "lat": try: lat = float(request.form[key]) except: return "Request Failed: latitude was not a float" elif key == "lng": try: lng = float(request.form[key]) except: return "Request Failed: longitude was not a float" elif key == "id1": phone1_id = request.form[key] elif key == "id2": phone2_id = request.form[key] kyzr.swap_torch(phone1_id, phone2_id, lat, lng) return "Success" return "Request method failed." if __name__ == "__main__": app.run()
#!/usr/bin/env python3 # # Copyright (C) 2015 Clifford Wolf <clifford@clifford.at> # # 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. # import iceboxdb import re, sys class iceconfig: def __init__(self): self.clear() def clear(self): self.max_x = 0 self.max_y = 0 self.device = "" self.warmboot = True self.logic_tiles = dict() self.io_tiles = dict() self.ramb_tiles = dict() self.ramt_tiles = dict() self.ram_data = dict() self.extra_bits = set() self.symbols = dict() def setup_empty_384(self): self.clear() self.device = "384" self.max_x = 7 self.max_y = 9 for x in range(1, self.max_x): for y in range(1, self.max_y): self.logic_tiles[(x, y)] = ["0" * 54 for i in range(16)] for x in range(1, self.max_x): self.io_tiles[(x, 0)] = ["0" * 18 for i in range(16)] self.io_tiles[(x, self.max_y)] = ["0" * 18 for i in range(16)] for y in range(1, self.max_y): self.io_tiles[(0, y)] = ["0" * 18 for i in range(16)] self.io_tiles[(self.max_x, y)] = ["0" * 18 for i in range(16)] def setup_empty_1k(self): self.clear() self.device = "1k" self.max_x = 13 self.max_y = 17 for x in range(1, self.max_x): for y in range(1, self.max_y): if x in (3, 10): if y % 2 == 1: self.ramb_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.ramt_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.logic_tiles[(x, y)] = ["0" * 54 for i in range(16)] for x in range(1, self.max_x): self.io_tiles[(x, 0)] = ["0" * 18 for i in range(16)] self.io_tiles[(x, self.max_y)] = ["0" * 18 for i in range(16)] for y in range(1, self.max_y): self.io_tiles[(0, y)] = ["0" * 18 for i in range(16)] self.io_tiles[(self.max_x, y)] = ["0" * 18 for i in range(16)] def setup_empty_5k(self): self.clear() self.device = "5k" self.max_x = 25 self.max_y = 31 for x in range(1, self.max_x): for y in range(1, self.max_y): if x in (7, 20): if y % 2 == 1: self.ramb_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.ramt_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.logic_tiles[(x, y)] = ["0" * 54 for i in range(16)] for x in range(1, self.max_x): self.io_tiles[(x, 0)] = ["0" * 18 for i in range(16)] self.io_tiles[(x, self.max_y)] = ["0" * 18 for i in range(16)] def setup_empty_8k(self): self.clear() self.device = "8k" self.max_x = 33 self.max_y = 33 for x in range(1, self.max_x): for y in range(1, self.max_y): if x in (8, 25): if y % 2 == 1: self.ramb_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.ramt_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.logic_tiles[(x, y)] = ["0" * 54 for i in range(16)] for x in range(1, self.max_x): self.io_tiles[(x, 0)] = ["0" * 18 for i in range(16)] self.io_tiles[(x, self.max_y)] = ["0" * 18 for i in range(16)] for y in range(1, self.max_y): self.io_tiles[(0, y)] = ["0" * 18 for i in range(16)] self.io_tiles[(self.max_x, y)] = ["0" * 18 for i in range(16)] def lookup_extra_bit(self, bit): assert self.device in extra_bits_db if bit in extra_bits_db[self.device]: return extra_bits_db[self.device][bit] return ("UNKNOWN_FUNCTION",) def tile(self, x, y): if (x, y) in self.io_tiles: return self.io_tiles[(x, y)] if (x, y) in self.logic_tiles: return self.logic_tiles[(x, y)] if (x, y) in self.ramb_tiles: return self.ramb_tiles[(x, y)] if (x, y) in self.ramt_tiles: return self.ramt_tiles[(x, y)] return None def pinloc_db(self): if self.device == "384": return pinloc_db["384-qn32"] if self.device == "1k": return pinloc_db["1k-tq144"] if self.device == "5k": return pinloc_db["5k-sg48"] if self.device == "8k": return pinloc_db["8k-ct256"] assert False def gbufin_db(self): return gbufin_db[self.device] def iolatch_db(self): return iolatch_db[self.device] def padin_pio_db(self): return padin_pio_db[self.device] def extra_bits_db(self): return extra_bits_db[self.device] def ieren_db(self): return ieren_db[self.device] def pll_list(self): if self.device == "1k": return ["1k"] if self.device == "5k": return ["5k"] if self.device == "8k": return ["8k_0", "8k_1"] if self.device == "384": return [ ] assert False def colbuf_db(self): if self.device == "1k": entries = list() for x in range(self.max_x+1): for y in range(self.max_y+1): src_y = None if 0 <= y <= 4: src_y = 4 if 5 <= y <= 8: src_y = 5 if 9 <= y <= 12: src_y = 12 if 13 <= y <= 17: src_y = 13 if x in [3, 10] and src_y == 4: src_y = 3 if x in [3, 10] and src_y == 12: src_y = 11 entries.append((x, src_y, x, y)) return entries if self.device == "8k": entries = list() for x in range(self.max_x+1): for y in range(self.max_y+1): src_y = None if 0 <= y <= 8: src_y = 8 if 9 <= y <= 16: src_y = 9 if 17 <= y <= 24: src_y = 24 if 25 <= y <= 33: src_y = 25 entries.append((x, src_y, x, y)) return entries if self.device == "5k": #Assume same as 8k because same height, is this valid??? entries = list() for x in range(self.max_x+1): for y in range(self.max_y+1): src_y = None if 0 <= y <= 8: src_y = 8 if 9 <= y <= 16: src_y = 9 if 17 <= y <= 24: src_y = 24 if 25 <= y <= 33: src_y = 25 entries.append((x, src_y, x, y)) return entries if self.device == "384": entries = list() for x in range(self.max_x+1): for y in range(self.max_y+1): src_y = None #Is ColBufCtrl relevant? if 0 <= y <= 2: src_y = 2 #384? if 3 <= y <= 4: src_y = 3 #384? if 5 <= y <= 6: src_y = 6 #384? if 7 <= y <= 9: src_y = 7 #384? entries.append((x, src_y, x, y)) return entries assert False def tile_db(self, x, y): # Only these devices have IO on the left and right sides. if self.device in ["384", "1k", "8k"]: if x == 0: return iotile_l_db if x == self.max_x: return iotile_r_db if y == 0: return iotile_b_db if y == self.max_y: return iotile_t_db if self.device == "1k": if (x, y) in self.logic_tiles: return logictile_db if (x, y) in self.ramb_tiles: return rambtile_db if (x, y) in self.ramt_tiles: return ramttile_db elif self.device == "5k": if (x, y) in self.logic_tiles: return logictile_5k_db if (x, y) in self.ramb_tiles: return rambtile_5k_db if (x, y) in self.ramt_tiles: return ramttile_5k_db elif self.device == "8k": if (x, y) in self.logic_tiles: return logictile_8k_db if (x, y) in self.ramb_tiles: return rambtile_8k_db if (x, y) in self.ramt_tiles: return ramttile_8k_db elif self.device == "384": if (x, y) in self.logic_tiles: return logictile_384_db print("Tile type unknown at (%d, %d)" % (x, y)) assert False def tile_type(self, x, y): if x == 0: return "IO" if y == 0: return "IO" if x == self.max_x: return "IO" if y == self.max_y: return "IO" if (x, y) in self.ramb_tiles: return "RAMB" if (x, y) in self.ramt_tiles: return "RAMT" if (x, y) in self.logic_tiles: return "LOGIC" assert False def tile_pos(self, x, y): if x == 0 and 0 < y < self.max_y: return "l" if y == 0 and 0 < x < self.max_x: return "b" if x == self.max_x and 0 < y < self.max_y: return "r" if y == self.max_y and 0 < x < self.max_x: return "t" if 0 < x < self.max_x and 0 < y < self.max_y: return "x" return None def tile_has_entry(self, x, y, entry): if entry[1] in ("routing", "buffer"): return self.tile_has_net(x, y, entry[2]) and self.tile_has_net(x, y, entry[3]) return True def tile_has_net(self, x, y, netname): if netname.startswith("logic_op_"): if netname.startswith("logic_op_bot_"): if y == self.max_y and 0 < x < self.max_x: return True if netname.startswith("logic_op_bnl_"): if x == self.max_x and 1 < y < self.max_y: return True if y == self.max_y and 1 < x < self.max_x: return True if netname.startswith("logic_op_bnr_"): if x == 0 and 1 < y < self.max_y: return True if y == self.max_y and 0 < x < self.max_x-1: return True if netname.startswith("logic_op_top_"): if y == 0 and 0 < x < self.max_x: return True if netname.startswith("logic_op_tnl_"): if x == self.max_x and 0 < y < self.max_y-1: return True if y == 0 and 1 < x < self.max_x: return True if netname.startswith("logic_op_tnr_"): if x == 0 and 0 < y < self.max_y-1: return True if y == 0 and 0 < x < self.max_x-1: return True if netname.startswith("logic_op_lft_"): if x == self.max_x: return True if netname.startswith("logic_op_rgt_"): if x == 0: return True return False if not 0 <= x <= self.max_x: return False if not 0 <= y <= self.max_y: return False return pos_has_net(self.tile_pos(x, y), netname) def tile_follow_net(self, x, y, direction, netname): if x == 1 and y not in (0, self.max_y) and direction == 'l': return pos_follow_net("x", "L", netname) if y == 1 and x not in (0, self.max_x) and direction == 'b': return pos_follow_net("x", "B", netname) if x == self.max_x-1 and y not in (0, self.max_y) and direction == 'r': return pos_follow_net("x", "R", netname) if y == self.max_y-1 and x not in (0, self.max_x) and direction == 't': return pos_follow_net("x", "T", netname) return pos_follow_net(self.tile_pos(x, y), direction, netname) def follow_funcnet(self, x, y, func): neighbours = set() def do_direction(name, nx, ny): if 0 < nx < self.max_x and 0 < ny < self.max_y: neighbours.add((nx, ny, "neigh_op_%s_%d" % (name, func))) if nx in (0, self.max_x) and 0 < ny < self.max_y and nx != x: neighbours.add((nx, ny, "logic_op_%s_%d" % (name, func))) if ny in (0, self.max_y) and 0 < nx < self.max_x and ny != y: neighbours.add((nx, ny, "logic_op_%s_%d" % (name, func))) do_direction("bot", x, y+1) do_direction("bnl", x+1, y+1) do_direction("bnr", x-1, y+1) do_direction("top", x, y-1) do_direction("tnl", x+1, y-1) do_direction("tnr", x-1, y-1) do_direction("lft", x+1, y ) do_direction("rgt", x-1, y ) return neighbours def lookup_funcnet(self, nx, ny, x, y, func): npos = self.tile_pos(nx, ny) pos = self.tile_pos(x, y) if npos is not None and pos is not None: if npos == "x": if (nx, ny) in self.logic_tiles: return (nx, ny, "lutff_%d/out" % func) if (nx, ny) in self.ramb_tiles: if self.device == "1k": return (nx, ny, "ram/RDATA_%d" % func) elif self.device == "5k": return (nx, ny, "ram/RDATA_%d" % (15-func)) elif self.device == "8k": return (nx, ny, "ram/RDATA_%d" % (15-func)) else: assert False if (nx, ny) in self.ramt_tiles: if self.device == "1k": return (nx, ny, "ram/RDATA_%d" % (8+func)) elif self.device == "5k": return (nx, ny, "ram/RDATA_%d" % (7-func)) elif self.device == "8k": return (nx, ny, "ram/RDATA_%d" % (7-func)) else: assert False elif pos == "x" and npos in ("l", "r", "t", "b"): if func in (0, 4): return (nx, ny, "io_0/D_IN_0") if func in (1, 5): return (nx, ny, "io_0/D_IN_1") if func in (2, 6): return (nx, ny, "io_1/D_IN_0") if func in (3, 7): return (nx, ny, "io_1/D_IN_1") return None def rlookup_funcnet(self, x, y, netname): funcnets = set() if netname == "io_0/D_IN_0": for net in self.follow_funcnet(x, y, 0) | self.follow_funcnet(x, y, 4): if self.tile_pos(net[0], net[1]) == "x": funcnets.add(net) if netname == "io_0/D_IN_1": for net in self.follow_funcnet(x, y, 1) | self.follow_funcnet(x, y, 5): if self.tile_pos(net[0], net[1]) == "x": funcnets.add(net) if netname == "io_1/D_IN_0": for net in self.follow_funcnet(x, y, 2) | self.follow_funcnet(x, y, 6): if self.tile_pos(net[0], net[1]) == "x": funcnets.add(net) if netname == "io_1/D_IN_1": for net in self.follow_funcnet(x, y, 3) | self.follow_funcnet(x, y, 7): if self.tile_pos(net[0], net[1]) == "x": funcnets.add(net) match = re.match(r"lutff_(\d+)/out", netname) if match: funcnets |= self.follow_funcnet(x, y, int(match.group(1))) match = re.match(r"ram/RDATA_(\d+)", netname) if match: if self.device == "1k": funcnets |= self.follow_funcnet(x, y, int(match.group(1)) % 8) elif self.device == "5k": funcnets |= self.follow_funcnet(x, y, 7 - int(match.group(1)) % 8) elif self.device == "8k": funcnets |= self.follow_funcnet(x, y, 7 - int(match.group(1)) % 8) else: assert False return funcnets def follow_net(self, netspec): x, y, netname = netspec neighbours = self.rlookup_funcnet(x, y, netname) #print(netspec) #print('\t', neighbours) if netname == "carry_in" and y > 1: neighbours.add((x, y-1, "lutff_7/cout")) if netname == "lutff_7/cout" and y+1 < self.max_y: neighbours.add((x, y+1, "carry_in")) if netname.startswith("glb_netwk_"): for nx in range(self.max_x+1): for ny in range(self.max_y+1): if self.tile_pos(nx, ny) is not None: neighbours.add((nx, ny, netname)) match = re.match(r"sp4_r_v_b_(\d+)", netname) if match and 0 < x < self.max_x-1: neighbours.add((x+1, y, sp4v_normalize("sp4_v_b_" + match.group(1)))) #print('\tafter r_v_b', neighbours) match = re.match(r"sp4_v_[bt]_(\d+)", netname) if match and 1 < x < self.max_x: n = sp4v_normalize(netname, "b") if n is not None: n = n.replace("sp4_", "sp4_r_") neighbours.add((x-1, y, n)) #print('\tafter v_[bt]', neighbours) match = re.match(r"(logic|neigh)_op_(...)_(\d+)", netname) if match: if match.group(2) == "bot": nx, ny = (x, y-1) if match.group(2) == "bnl": nx, ny = (x-1, y-1) if match.group(2) == "bnr": nx, ny = (x+1, y-1) if match.group(2) == "top": nx, ny = (x, y+1) if match.group(2) == "tnl": nx, ny = (x-1, y+1) if match.group(2) == "tnr": nx, ny = (x+1, y+1) if match.group(2) == "lft": nx, ny = (x-1, y ) if match.group(2) == "rgt": nx, ny = (x+1, y ) n = self.lookup_funcnet(nx, ny, x, y, int(match.group(3))) if n is not None: neighbours.add(n) for direction in ["l", "r", "t", "b"]: n = self.tile_follow_net(x, y, direction, netname) if n is not None: if direction == "l": s = (x-1, y, n) if direction == "r": s = (x+1, y, n) if direction == "t": s = (x, y+1, n) if direction == "b": s = (x, y-1, n) if s[0] in (0, self.max_x) and s[1] in (0, self.max_y): if re.match("span4_(vert|horz)_[lrtb]_\d+$", n): vert_net = n.replace("_l_", "_t_").replace("_r_", "_b_").replace("_horz_", "_vert_") horz_net = n.replace("_t_", "_l_").replace("_b_", "_r_").replace("_vert_", "_horz_") if s[0] == 0 and s[1] == 0: if direction == "l": s = (0, 1, vert_net) if direction == "b": s = (1, 0, horz_net) if s[0] == self.max_x and s[1] == self.max_y: if direction == "r": s = (self.max_x, self.max_y-1, vert_net) if direction == "t": s = (self.max_x-1, self.max_y, horz_net) vert_net = netname.replace("_l_", "_t_").replace("_r_", "_b_").replace("_horz_", "_vert_") horz_net = netname.replace("_t_", "_l_").replace("_b_", "_r_").replace("_vert_", "_horz_") if s[0] == 0 and s[1] == self.max_y: if direction == "l": s = (0, self.max_y-1, vert_net) if direction == "t": s = (1, self.max_y, horz_net) if s[0] == self.max_x and s[1] == 0: if direction == "r": s = (self.max_x, 1, vert_net) if direction == "b": s = (self.max_x-1, 0, horz_net) if self.tile_has_net(s[0], s[1], s[2]): neighbours.add((s[0], s[1], s[2])) #print('\tafter directions', neighbours) return neighbours def group_segments(self, all_from_tiles=set(), extra_connections=list(), extra_segments=list(), connect_gb=True): seed_segments = set() seen_segments = set() connected_segments = dict() grouped_segments = set() for seg in extra_segments: seed_segments.add(seg) for conn in extra_connections: s1, s2 = conn connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) for idx, tile in self.io_tiles.items(): tc = tileconfig(tile) pintypes = [ list("000000"), list("000000") ] for entry in self.tile_db(idx[0], idx[1]): if entry[1].startswith("IOB_") and entry[2].startswith("PINTYPE_") and tc.match(entry[0]): pintypes[int(entry[1][-1])][int(entry[2][-1])] = "1" if "".join(pintypes[0][2:6]) != "0000": seed_segments.add((idx[0], idx[1], "io_0/D_OUT_0")) if "".join(pintypes[1][2:6]) != "0000": seed_segments.add((idx[0], idx[1], "io_1/D_OUT_0")) def add_seed_segments(idx, tile, db): tc = tileconfig(tile) for entry in db: if entry[1] in ("routing", "buffer"): config_match = tc.match(entry[0]) if idx in all_from_tiles or config_match: if not self.tile_has_net(idx[0], idx[1], entry[2]): continue if not self.tile_has_net(idx[0], idx[1], entry[3]): continue s1 = (idx[0], idx[1], entry[2]) s2 = (idx[0], idx[1], entry[3]) if config_match: connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) for idx, tile in self.io_tiles.items(): add_seed_segments(idx, tile, self.tile_db(idx[0], idx[1])) for idx, tile in self.logic_tiles.items(): if idx in all_from_tiles: seed_segments.add((idx[0], idx[1], "lutff_7/cout")) if self.device == "1k": add_seed_segments(idx, tile, logictile_db) elif self.device == "5k": add_seed_segments(idx, tile, logictile_5k_db) elif self.device == "8k": add_seed_segments(idx, tile, logictile_8k_db) elif self.device == "384": add_seed_segments(idx, tile, logictile_384_db) else: assert False for idx, tile in self.ramb_tiles.items(): if self.device == "1k": add_seed_segments(idx, tile, rambtile_db) elif self.device == "5k": add_seed_segments(idx, tile, rambtile_5k_db) elif self.device == "8k": add_seed_segments(idx, tile, rambtile_8k_db) else: assert False for idx, tile in self.ramt_tiles.items(): if self.device == "1k": add_seed_segments(idx, tile, ramttile_db) elif self.device == "5k": add_seed_segments(idx, tile, ramttile_5k_db) elif self.device == "8k": add_seed_segments(idx, tile, ramttile_8k_db) else: assert False for padin, pio in enumerate(self.padin_pio_db()): s1 = (pio[0], pio[1], "padin_%d" % pio[2]) s2 = (pio[0], pio[1], "glb_netwk_%d" % padin) if s1 in seed_segments or (pio[0], pio[1]) in all_from_tiles: connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) for entry in self.iolatch_db(): if entry[0] == 0 or entry[0] == self.max_x: iocells = [(entry[0], i) for i in range(1, self.max_y)] if entry[1] == 0 or entry[1] == self.max_y: iocells = [(i, entry[1]) for i in range(1, self.max_x)] for cell in iocells: s1 = (entry[0], entry[1], "fabout") s2 = (cell[0], cell[1], "io_global/latch") if s1 in seed_segments or s2 in seed_segments or \ (entry[0], entry[1]) in all_from_tiles or (cell[0], cell[1]) in all_from_tiles: connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) if connect_gb: for entry in self.gbufin_db(): s1 = (entry[0], entry[1], "fabout") s2 = (entry[0], entry[1], "glb_netwk_%d" % entry[2]) if s1 in seed_segments or (pio[0], pio[1]) in all_from_tiles: connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) while seed_segments: queue = set() segments = set() queue.add(seed_segments.pop()) while queue: next_segment = queue.pop() expanded = self.expand_net(next_segment) for s in expanded: if s not in segments: segments.add(s) if s in seen_segments: print("//", s, "has already been seen. Check your bitmapping.") assert False seen_segments.add(s) seed_segments.discard(s) if s in connected_segments: for cs in connected_segments[s]: if not cs in segments: queue.add(cs) for s in segments: assert s not in seed_segments grouped_segments.add(tuple(sorted(segments))) return grouped_segments def expand_net(self, netspec): queue = set() segments = set() queue.add(netspec) while queue: n = queue.pop() segments.add(n) for k in self.follow_net(n): if k not in segments: queue.add(k) return segments def read_file(self, filename): self.clear() current_data = None expected_data_lines = 0 with open(filename, "r") as f: for linenum, linetext in enumerate(f): # print("DEBUG: input line %d: %s" % (linenum, linetext.strip())) line = linetext.strip().split() if len(line) == 0: assert expected_data_lines == 0 continue if line[0][0] != ".": if expected_data_lines == -1: continue if line[0][0] not in "0123456789abcdef": print("Warning: ignoring data block in line %d: %s" % (linenum, linetext.strip())) expected_data_lines = 0 continue assert expected_data_lines != 0 current_data.append(line[0]) expected_data_lines -= 1 continue assert expected_data_lines <= 0 if line[0] in (".io_tile", ".logic_tile", ".ramb_tile", ".ramt_tile", ".ram_data"): current_data = list() expected_data_lines = 16 self.max_x = max(self.max_x, int(line[1])) self.max_y = max(self.max_y, int(line[2])) if line[0] == ".io_tile": self.io_tiles[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".logic_tile": self.logic_tiles[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".ramb_tile": self.ramb_tiles[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".ramt_tile": self.ramt_tiles[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".ram_data": self.ram_data[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".extra_bit": self.extra_bits.add((int(line[1]), int(line[2]), int(line[3]))) continue if line[0] == ".device": assert line[1] in ["1k", "5k", "8k", "384"] self.device = line[1] continue if line[0] == ".warmboot": assert line[1] in ["disabled", "enabled"] self.warmboot = line[1] == "enabled" continue if line[0] == ".sym": self.symbols.setdefault(int(line[1]), set()).add(line[2]) continue if line[0] == ".comment": expected_data_lines = -1 continue print("Warning: ignoring line %d: %s" % (linenum, linetext.strip())) expected_data_lines = -1 def write_file(self, filename): with open(filename, "w") as f: print(".device %s" % self.device, file=f) if not self.warmboot: print(".warmboot disabled", file=f) for y in range(self.max_y+1): for x in range(self.max_x+1): if self.tile_pos(x, y) is not None: print(".%s_tile %d %d" % (self.tile_type(x, y).lower(), x, y), file=f) for line in self.tile(x, y): print(line, file=f) for x, y in sorted(self.ram_data): print(".ram_data %d %d" % (x, y), file=f) for line in self.ram_data[(x, y)]: print(line, file=f) for extra_bit in sorted(self.extra_bits): print(".extra_bit %d %d %d" % extra_bit, file=f) class tileconfig: def __init__(self, tile): self.bits = set() for k, line in enumerate(tile): for i in range(len(line)): if line[i] == "1": self.bits.add("B%d[%d]" % (k, i)) else: self.bits.add("!B%d[%d]" % (k, i)) def match(self, pattern): for bit in pattern: if not bit in self.bits: return False return True if False: ## Lattice span net name normalization valid_sp4_h_l = set([1, 2, 4, 5, 7, 9, 10, 11, 15, 16, 17, 21, 24, 34, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]) valid_sp4_h_r = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 19, 21, 24, 25, 27, 30, 31, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 45, 46]) valid_sp4_v_t = set([1, 3, 5, 9, 12, 14, 16, 17, 18, 21, 22, 23, 26, 28, 29, 30, 32, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]) valid_sp4_v_b = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 18, 19, 21, 22, 23, 24, 26, 30, 33, 36, 37, 38, 42, 46, 47]) valid_sp12_h_l = set([3, 4, 5, 12, 14, 16, 17, 18, 21, 22, 23]) valid_sp12_h_r = set([0, 1, 2, 3, 5, 8, 9, 10, 11, 12, 13, 14, 16, 20, 23]) valid_sp12_v_t = set([0, 1, 2, 3, 6, 9, 10, 12, 14, 21, 22, 23]) valid_sp12_v_b = set([0, 1, 6, 7, 8, 11, 12, 14, 16, 18, 19, 20, 21, 23]) else: ## IceStorm span net name normalization valid_sp4_h_l = set(range(36, 48)) valid_sp4_h_r = set(range(48)) valid_sp4_v_t = set(range(36, 48)) valid_sp4_v_b = set(range(48)) valid_sp12_h_l = set(range(22, 24)) valid_sp12_h_r = set(range(24)) valid_sp12_v_t = set(range(22, 24)) valid_sp12_v_b = set(range(24)) def sp4h_normalize(netname, edge=""): m = re.match("sp4_h_([lr])_(\d+)$", netname) assert m if not m: return None cur_edge = m.group(1) cur_index = int(m.group(2)) if cur_edge == edge: return netname if cur_edge == "r" and (edge == "l" or (edge == "" and cur_index not in valid_sp4_h_r)): if cur_index < 12: return None return "sp4_h_l_%d" % ((cur_index-12)^1) if cur_edge == "l" and (edge == "r" or (edge == "" and cur_index not in valid_sp4_h_l)): if cur_index >= 36: return None return "sp4_h_r_%d" % ((cur_index+12)^1) return netname def sp4v_normalize(netname, edge=""): m = re.match("sp4_v_([bt])_(\d+)$", netname) assert m if not m: return None cur_edge = m.group(1) cur_index = int(m.group(2)) if cur_edge == edge: return netname if cur_edge == "b" and (edge == "t" or (edge == "" and cur_index not in valid_sp4_v_b)): if cur_index < 12: return None return "sp4_v_t_%d" % ((cur_index-12)^1) if cur_edge == "t" and (edge == "b" or (edge == "" and cur_index not in valid_sp4_v_t)): if cur_index >= 36: return None return "sp4_v_b_%d" % ((cur_index+12)^1) return netname def sp12h_normalize(netname, edge=""): m = re.match("sp12_h_([lr])_(\d+)$", netname) assert m if not m: return None cur_edge = m.group(1) cur_index = int(m.group(2)) if cur_edge == edge: return netname if cur_edge == "r" and (edge == "l" or (edge == "" and cur_index not in valid_sp12_h_r)): if cur_index < 2: return None return "sp12_h_l_%d" % ((cur_index-2)^1) if cur_edge == "l" and (edge == "r" or (edge == "" and cur_index not in valid_sp12_h_l)): if cur_index >= 22: return None return "sp12_h_r_%d" % ((cur_index+2)^1) return netname def sp12v_normalize(netname, edge=""): m = re.match("sp12_v_([bt])_(\d+)$", netname) assert m if not m: return None cur_edge = m.group(1) cur_index = int(m.group(2)) if cur_edge == edge: return netname if cur_edge == "b" and (edge == "t" or (edge == "" and cur_index not in valid_sp12_v_b)): if cur_index < 2: return None return "sp12_v_t_%d" % ((cur_index-2)^1) if cur_edge == "t" and (edge == "b" or (edge == "" and cur_index not in valid_sp12_v_t)): if cur_index >= 22: return None return "sp12_v_b_%d" % ((cur_index+2)^1) return netname def netname_normalize(netname, edge="", ramb=False, ramt=False, ramb_8k=False, ramt_8k=False): if netname.startswith("sp4_v_"): return sp4v_normalize(netname, edge) if netname.startswith("sp4_h_"): return sp4h_normalize(netname, edge) if netname.startswith("sp12_v_"): return sp12v_normalize(netname, edge) if netname.startswith("sp12_h_"): return sp12h_normalize(netname, edge) if netname.startswith("input_2_"): netname = netname.replace("input_2_", "wire_logic_cluster/lc_") + "/in_2" netname = netname.replace("lc_trk_", "local_") netname = netname.replace("lc_", "lutff_") netname = netname.replace("wire_logic_cluster/", "") netname = netname.replace("wire_io_cluster/", "") netname = netname.replace("wire_bram/", "") if (ramb or ramt or ramb_8k or ramt_8k) and netname.startswith("input"): match = re.match(r"input(\d)_(\d)", netname) idx1, idx2 = (int(match.group(1)), int(match.group(2))) if ramb: netname="ram/WADDR_%d" % (idx1*4 + idx2) if ramt: netname="ram/RADDR_%d" % (idx1*4 + idx2) if ramb_8k: netname="ram/RADDR_%d" % ([7, 6, 5, 4, 3, 2, 1, 0, -1, -1, -1, -1, -1, 10, 9, 8][idx1*4 + idx2]) if ramt_8k: netname="ram/WADDR_%d" % ([7, 6, 5, 4, 3, 2, 1, 0, -1, -1, -1, -1, -1, 10, 9, 8][idx1*4 + idx2]) match = re.match(r"(...)_op_(.*)", netname) if match: netname = "neigh_op_%s_%s" % (match.group(1), match.group(2)) if re.match(r"lutff_7/(cen|clk|s_r)", netname): netname = netname.replace("lutff_7/", "lutff_global/") if re.match(r"io_1/(cen|inclk|outclk)", netname): netname = netname.replace("io_1/", "io_global/") if netname == "carry_in_mux/cout": return "carry_in_mux" return netname def pos_has_net(pos, netname): if pos in ("l", "r"): if re.search(r"_vert_\d+$", netname): return False if re.search(r"_horz_[rl]_\d+$", netname): return False if pos in ("t", "b"): if re.search(r"_horz_\d+$", netname): return False if re.search(r"_vert_[bt]_\d+$", netname): return False return True def pos_follow_net(pos, direction, netname): if pos == "x": m = re.match("sp4_h_[lr]_(\d+)$", netname) if m and direction in ("l", "L"): n = sp4h_normalize(netname, "l") if n is not None: if direction == "l": n = re.sub("_l_", "_r_", n) n = sp4h_normalize(n) else: n = re.sub("_l_", "_", n) n = re.sub("sp4_h_", "span4_horz_", n) return n if m and direction in ("r", "R"): n = sp4h_normalize(netname, "r") if n is not None: if direction == "r": n = re.sub("_r_", "_l_", n) n = sp4h_normalize(n) else: n = re.sub("_r_", "_", n) n = re.sub("sp4_h_", "span4_horz_", n) return n m = re.match("sp4_v_[tb]_(\d+)$", netname) if m and direction in ("t", "T"): n = sp4v_normalize(netname, "t") if n is not None: if direction == "t": n = re.sub("_t_", "_b_", n) n = sp4v_normalize(n) else: n = re.sub("_t_", "_", n) n = re.sub("sp4_v_", "span4_vert_", n) return n if m and direction in ("b", "B"): n = sp4v_normalize(netname, "b") if n is not None: if direction == "b": n = re.sub("_b_", "_t_", n) n = sp4v_normalize(n) else: n = re.sub("_b_", "_", n) n = re.sub("sp4_v_", "span4_vert_", n) return n m = re.match("sp12_h_[lr]_(\d+)$", netname) if m and direction in ("l", "L"): n = sp12h_normalize(netname, "l") if n is not None: if direction == "l": n = re.sub("_l_", "_r_", n) n = sp12h_normalize(n) else: n = re.sub("_l_", "_", n) n = re.sub("sp12_h_", "span12_horz_", n) return n if m and direction in ("r", "R"): n = sp12h_normalize(netname, "r") if n is not None: if direction == "r": n = re.sub("_r_", "_l_", n) n = sp12h_normalize(n) else: n = re.sub("_r_", "_", n) n = re.sub("sp12_h_", "span12_horz_", n) return n m = re.match("sp12_v_[tb]_(\d+)$", netname) if m and direction in ("t", "T"): n = sp12v_normalize(netname, "t") if n is not None: if direction == "t": n = re.sub("_t_", "_b_", n) n = sp12v_normalize(n) else: n = re.sub("_t_", "_", n) n = re.sub("sp12_v_", "span12_vert_", n) return n if m and direction in ("b", "B"): n = sp12v_normalize(netname, "b") if n is not None: if direction == "b": n = re.sub("_b_", "_t_", n) n = sp12v_normalize(n) else: n = re.sub("_b_", "_", n) n = re.sub("sp12_v_", "span12_vert_", n) return n if pos in ("l", "r" ): m = re.match("span4_vert_([bt])_(\d+)$", netname) if m: case, idx = direction + m.group(1), int(m.group(2)) if case == "tt": return "span4_vert_b_%d" % idx if case == "tb" and idx >= 4: return "span4_vert_b_%d" % (idx-4) if case == "bb" and idx < 12: return "span4_vert_b_%d" % (idx+4) if case == "bb" and idx >= 12: return "span4_vert_t_%d" % idx if pos in ("t", "b" ): m = re.match("span4_horz_([rl])_(\d+)$", netname) if m: case, idx = direction + m.group(1), int(m.group(2)) if case == "ll": return "span4_horz_r_%d" % idx if case == "lr" and idx >= 4: return "span4_horz_r_%d" % (idx-4) if case == "rr" and idx < 12: return "span4_horz_r_%d" % (idx+4) if case == "rr" and idx >= 12: return "span4_horz_l_%d" % idx if pos == "l" and direction == "r": m = re.match("span4_horz_(\d+)$", netname) if m: return sp4h_normalize("sp4_h_l_%s" % m.group(1)) m = re.match("span12_horz_(\d+)$", netname) if m: return sp12h_normalize("sp12_h_l_%s" % m.group(1)) if pos == "r" and direction == "l": m = re.match("span4_horz_(\d+)$", netname) if m: return sp4h_normalize("sp4_h_r_%s" % m.group(1)) m = re.match("span12_horz_(\d+)$", netname) if m: return sp12h_normalize("sp12_h_r_%s" % m.group(1)) if pos == "t" and direction == "b": m = re.match("span4_vert_(\d+)$", netname) if m: return sp4v_normalize("sp4_v_t_%s" % m.group(1)) m = re.match("span12_vert_(\d+)$", netname) if m: return sp12v_normalize("sp12_v_t_%s" % m.group(1)) if pos == "b" and direction == "t": m = re.match("span4_vert_(\d+)$", netname) if m: return sp4v_normalize("sp4_v_b_%s" % m.group(1)) m = re.match("span12_vert_(\d+)$", netname) if m: return sp12v_normalize("sp12_v_b_%s" % m.group(1)) return None def get_lutff_bits(tile, index): bits = list("--------------------") for k, line in enumerate(tile): for i in range(36, 46): lutff_idx = k // 2 lutff_bitnum = (i-36) + 10*(k%2) if lutff_idx == index: bits[lutff_bitnum] = line[i]; return bits def get_lutff_lut_bits(tile, index): lutff_bits = get_lutff_bits(tile, index) return [lutff_bits[i] for i in [4, 14, 15, 5, 6, 16, 17, 7, 3, 13, 12, 2, 1, 11, 10, 0]] def get_lutff_seq_bits(tile, index): lutff_bits = get_lutff_bits(tile, index) return [lutff_bits[i] for i in [8, 9, 18, 19]] def get_carry_cascade_bit(tile): return tile[1][49] def get_carry_bit(tile): return tile[1][50] def get_negclk_bit(tile): return tile[0][0] def key_netname(netname): return re.sub(r"\d+", lambda m: "%09d" % int(m.group(0)), netname) def run_checks_neigh(): print("Running consistency checks on neighbour finder..") ic = iceconfig() # ic.setup_empty_1k() ic.setup_empty_5k() # ic.setup_empty_8k() # ic.setup_empty_384() all_segments = set() def add_segments(idx, db): for entry in db: if entry[1] in ("routing", "buffer"): if not ic.tile_has_net(idx[0], idx[1], entry[2]): continue if not ic.tile_has_net(idx[0], idx[1], entry[3]): continue all_segments.add((idx[0], idx[1], entry[2])) all_segments.add((idx[0], idx[1], entry[3])) for x in range(ic.max_x+1): for y in range(ic.max_x+1): # Skip the corners. if x in (0, ic.max_x) and y in (0, ic.max_y): continue # Skip the sides of a 5k device. if ic.device == "5k" and x in (0, ic.max_x): continue add_segments((x, y), ic.tile_db(x, y)) if (x, y) in ic.logic_tiles: all_segments.add((x, y, "lutff_7/cout")) for s1 in all_segments: for s2 in ic.follow_net(s1): # if s1[1] > 4: continue if s1 not in ic.follow_net(s2): print("ERROR: %s -> %s, but not vice versa!" % (s1, s2)) print("Neighbours of %s:" % (s1,)) for s in ic.follow_net(s1): print(" ", s) print("Neighbours of %s:" % (s2,)) for s in ic.follow_net(s2): print(" ", s) print() def run_checks(): run_checks_neigh() def parse_db(text, device="1k"): db = list() for line in text.split("\n"): line_384 = line.replace("384_glb_netwk_", "glb_netwk_") line_1k = line.replace("1k_glb_netwk_", "glb_netwk_") line_5k = line.replace("5k_glb_netwk_", "glb_netwk_") line_8k = line.replace("8k_glb_netwk_", "glb_netwk_") if line_1k != line: if device != "1k": continue line = line_1k elif line_8k != line: if device != "8k": continue line = line_8k elif line_5k != line: if device != "5k": continue line = line_5k elif line_384 != line: if device != "384": continue line = line_384 line = line.split("\t") if len(line) == 0 or line[0] == "": continue line[0] = line[0].split(",") db.append(line) return db extra_bits_db = { "1k": { (0, 330, 142): ("padin_glb_netwk", "0"), (0, 331, 142): ("padin_glb_netwk", "1"), (1, 330, 143): ("padin_glb_netwk", "2"), (1, 331, 143): ("padin_glb_netwk", "3"), # (1 3) (331 144) (331 144) routing T_0_0.padin_3 <X> T_0_0.glb_netwk_3 (1, 330, 142): ("padin_glb_netwk", "4"), (1, 331, 142): ("padin_glb_netwk", "5"), (0, 330, 143): ("padin_glb_netwk", "6"), # (0 0) (330 143) (330 143) routing T_0_0.padin_6 <X> T_0_0.glb_netwk_6 (0, 331, 143): ("padin_glb_netwk", "7"), }, "5k": { (0, 690, 334): ("padin_glb_netwk", "0"), # (0 1) (690 334) (690 334) routing T_0_0.padin_0 <X> T_0_0.glb_netwk_0 (1, 691, 334): ("padin_glb_netwk", "1"), # (1 1) (691 334) (691 334) routing T_0_0.padin_1 <X> T_0_0.glb_netwk_1 (0, 690, 336): ("padin_glb_netwk", "2"), # (0 3) (690 336) (690 336) routing T_0_0.padin_2 <X> T_0_0.glb_netwk_2 (1, 871, 271): ("padin_glb_netwk", "3"), (1, 870, 270): ("padin_glb_netwk", "4"), (1, 871, 270): ("padin_glb_netwk", "5"), (0, 870, 271): ("padin_glb_netwk", "6"), (1, 691, 335): ("padin_glb_netwk", "7"), # (1 0) (691 335) (691 335) routing T_0_0.padin_7 <X> T_0_0.glb_netwk_7 }, "8k": { (0, 870, 270): ("padin_glb_netwk", "0"), (0, 871, 270): ("padin_glb_netwk", "1"), (1, 870, 271): ("padin_glb_netwk", "2"), (1, 871, 271): ("padin_glb_netwk", "3"), (1, 870, 270): ("padin_glb_netwk", "4"), (1, 871, 270): ("padin_glb_netwk", "5"), (0, 870, 271): ("padin_glb_netwk", "6"), (0, 871, 271): ("padin_glb_netwk", "7"), }, "384": { (0, 180, 78): ("padin_glb_netwk", "0"), (0, 181, 78): ("padin_glb_netwk", "1"), (1, 180, 79): ("padin_glb_netwk", "2"), (1, 181, 79): ("padin_glb_netwk", "3"), (1, 180, 78): ("padin_glb_netwk", "4"), (1, 181, 78): ("padin_glb_netwk", "5"), (0, 180, 79): ("padin_glb_netwk", "6"), (0, 181, 79): ("padin_glb_netwk", "7"), } } gbufin_db = { "1k": [ (13, 8, 7), ( 0, 8, 6), ( 7, 17, 1), ( 7, 0, 0), ( 0, 9, 3), (13, 9, 2), ( 6, 0, 5), ( 6, 17, 4), ], "5k": [ # not sure how to get the third column, currently based on diagram in pdf. ( 6, 0, 0), (12, 0, 1), (13, 0, 3), (19, 0, 6), ( 6, 31, 5), (12, 31, 2), (13, 31, 7), (19, 31, 4), ], "8k": [ (33, 16, 7), ( 0, 16, 6), (17, 33, 1), (17, 0, 0), ( 0, 17, 3), (33, 17, 2), (16, 0, 5), (16, 33, 4), ], "384": [ ( 7, 4, 7), ( 0, 4, 6), ( 4, 9, 1), ( 4, 0, 0), ( 0, 5, 3), ( 7, 5, 2), ( 3, 0, 5), ( 3, 9, 4), ] } # To figure these out: # 1. Copy io_latched.sh and convert it for your pinout (like io_latched_5k.sh). # 2. Run it. It will create an io_latched_<device>.work directory with a bunch of files. # 3. Grep the *.ve files in that directory for "'fabout')". The coordinates # before it are where the io latches are. # # Note: This may not work if your icepack configuration of cell sizes is incorrect because # icebox_vlog.py won't correctly interpret the meaning of particular bits. iolatch_db = { "1k": [ ( 0, 7), (13, 10), ( 5, 0), ( 8, 17), ], "5k": [ (14, 0), (14, 31), ], "8k": [ ( 0, 15), (33, 18), (18, 0), (15, 33), ], "384": [ ( 0, 3), #384? ( 7, 5), #384? ( 2, 0), #384? ( 5, 9), #384? ], } # The x, y cell locations of the WARMBOOT controls. Run tests/sb_warmboot.v # through icecube.sh to determine these values. warmbootinfo_db = { "1k": { "BOOT": ( 12, 0, "fabout" ), "S0": ( 13, 1, "fabout" ), "S1": ( 13, 2, "fabout" ), }, "5k": { # These are the right locations but may be the wrong order. "BOOT": ( 22, 0, "fabout" ), "S0": ( 23, 0, "fabout" ), "S1": ( 24, 0, "fabout" ), }, "8k": { "BOOT": ( 31, 0, "fabout" ), "S0": ( 33, 1, "fabout" ), "S1": ( 33, 2, "fabout" ), }, "384": { "BOOT": ( 6, 0, "fabout" ), #384? "S0": ( 7, 1, "fabout" ), "S1": ( 7, 2, "fabout" ), } } noplls_db = { "1k-swg16tr": [ "1k" ], "1k-cm36": [ "1k" ], "1k-cm49": [ "1k" ], "8k-cm81": [ "8k_1" ], "8k-cm81:4k": [ "8k_1" ], "1k-qn48": [ "1k" ], "1k-cb81": [ "1k" ], "1k-cb121": [ "1k" ], "1k-vq100": [ "1k" ], "384-qn32": [ "384" ], "5k-sg48": [ "5k" ], } pllinfo_db = { "1k": { "LOC" : (6, 0), # 3'b000 = "DISABLED" # 3'b010 = "SB_PLL40_PAD" # 3'b100 = "SB_PLL40_2_PAD" # 3'b110 = "SB_PLL40_2F_PAD" # 3'b011 = "SB_PLL40_CORE" # 3'b111 = "SB_PLL40_2F_CORE" "PLLTYPE_0": ( 0, 3, "PLLCONFIG_5"), "PLLTYPE_1": ( 0, 5, "PLLCONFIG_1"), "PLLTYPE_2": ( 0, 5, "PLLCONFIG_3"), # 3'b000 = "DELAY" # 3'b001 = "SIMPLE" # 3'b010 = "PHASE_AND_DELAY" # 3'b110 = "EXTERNAL" "FEEDBACK_PATH_0": ( 0, 5, "PLLCONFIG_5"), "FEEDBACK_PATH_1": ( 0, 2, "PLLCONFIG_9"), "FEEDBACK_PATH_2": ( 0, 3, "PLLCONFIG_1"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_FEEDBACK=4'b1111) "DELAY_ADJMODE_FB": ( 0, 4, "PLLCONFIG_4"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_RELATIVE=4'b1111) "DELAY_ADJMODE_REL": ( 0, 4, "PLLCONFIG_9"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_A_0": ( 0, 3, "PLLCONFIG_6"), "PLLOUT_SELECT_A_1": ( 0, 3, "PLLCONFIG_7"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_B_0": ( 0, 3, "PLLCONFIG_2"), "PLLOUT_SELECT_B_1": ( 0, 3, "PLLCONFIG_3"), # Numeric Parameters "SHIFTREG_DIV_MODE": ( 0, 3, "PLLCONFIG_4"), "FDA_FEEDBACK_0": ( 0, 3, "PLLCONFIG_9"), "FDA_FEEDBACK_1": ( 0, 4, "PLLCONFIG_1"), "FDA_FEEDBACK_2": ( 0, 4, "PLLCONFIG_2"), "FDA_FEEDBACK_3": ( 0, 4, "PLLCONFIG_3"), "FDA_RELATIVE_0": ( 0, 4, "PLLCONFIG_5"), "FDA_RELATIVE_1": ( 0, 4, "PLLCONFIG_6"), "FDA_RELATIVE_2": ( 0, 4, "PLLCONFIG_7"), "FDA_RELATIVE_3": ( 0, 4, "PLLCONFIG_8"), "DIVR_0": ( 0, 1, "PLLCONFIG_1"), "DIVR_1": ( 0, 1, "PLLCONFIG_2"), "DIVR_2": ( 0, 1, "PLLCONFIG_3"), "DIVR_3": ( 0, 1, "PLLCONFIG_4"), "DIVF_0": ( 0, 1, "PLLCONFIG_5"), "DIVF_1": ( 0, 1, "PLLCONFIG_6"), "DIVF_2": ( 0, 1, "PLLCONFIG_7"), "DIVF_3": ( 0, 1, "PLLCONFIG_8"), "DIVF_4": ( 0, 1, "PLLCONFIG_9"), "DIVF_5": ( 0, 2, "PLLCONFIG_1"), "DIVF_6": ( 0, 2, "PLLCONFIG_2"), "DIVQ_0": ( 0, 2, "PLLCONFIG_3"), "DIVQ_1": ( 0, 2, "PLLCONFIG_4"), "DIVQ_2": ( 0, 2, "PLLCONFIG_5"), "FILTER_RANGE_0": ( 0, 2, "PLLCONFIG_6"), "FILTER_RANGE_1": ( 0, 2, "PLLCONFIG_7"), "FILTER_RANGE_2": ( 0, 2, "PLLCONFIG_8"), "TEST_MODE": ( 0, 3, "PLLCONFIG_8"), # PLL Ports "PLLOUT_A": ( 6, 0, 1), "PLLOUT_B": ( 7, 0, 0), "REFERENCECLK": ( 0, 1, "fabout"), "EXTFEEDBACK": ( 0, 2, "fabout"), "DYNAMICDELAY_0": ( 0, 4, "fabout"), "DYNAMICDELAY_1": ( 0, 5, "fabout"), "DYNAMICDELAY_2": ( 0, 6, "fabout"), "DYNAMICDELAY_3": ( 0, 10, "fabout"), "DYNAMICDELAY_4": ( 0, 11, "fabout"), "DYNAMICDELAY_5": ( 0, 12, "fabout"), "DYNAMICDELAY_6": ( 0, 13, "fabout"), "DYNAMICDELAY_7": ( 0, 14, "fabout"), "LOCK": ( 1, 1, "neigh_op_bnl_1"), "BYPASS": ( 1, 0, "fabout"), "RESETB": ( 2, 0, "fabout"), "LATCHINPUTVALUE": ( 5, 0, "fabout"), "SDO": (12, 1, "neigh_op_bnr_3"), "SDI": ( 4, 0, "fabout"), "SCLK": ( 3, 0, "fabout"), }, "5k": { "LOC" : (12, 31), # 3'b000 = "DISABLED" # 3'b010 = "SB_PLL40_PAD" # 3'b100 = "SB_PLL40_2_PAD" # 3'b110 = "SB_PLL40_2F_PAD" # 3'b011 = "SB_PLL40_CORE" # 3'b111 = "SB_PLL40_2F_CORE" "PLLTYPE_0": ( 16, 0, "PLLCONFIG_5"), "PLLTYPE_1": ( 18, 0, "PLLCONFIG_1"), "PLLTYPE_2": ( 18, 0, "PLLCONFIG_3"), # 3'b000 = "DELAY" # 3'b001 = "SIMPLE" # 3'b010 = "PHASE_AND_DELAY" # 3'b110 = "EXTERNAL" "FEEDBACK_PATH_0": ( 18, 0, "PLLCONFIG_5"), "FEEDBACK_PATH_1": ( 15, 0, "PLLCONFIG_9"), "FEEDBACK_PATH_2": ( 16, 0, "PLLCONFIG_1"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_FEEDBACK=4'b1111) "DELAY_ADJMODE_FB": ( 17, 0, "PLLCONFIG_4"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_RELATIVE=4'b1111) "DELAY_ADJMODE_REL": ( 17, 0, "PLLCONFIG_9"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_A_0": ( 16, 0, "PLLCONFIG_6"), "PLLOUT_SELECT_A_1": ( 16, 0, "PLLCONFIG_7"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_B_0": ( 16, 0, "PLLCONFIG_2"), "PLLOUT_SELECT_B_1": ( 16, 0, "PLLCONFIG_3"), # Numeric Parameters "SHIFTREG_DIV_MODE": ( 16, 0, "PLLCONFIG_4"), "FDA_FEEDBACK_0": ( 16, 0, "PLLCONFIG_9"), "FDA_FEEDBACK_1": ( 17, 0, "PLLCONFIG_1"), "FDA_FEEDBACK_2": ( 17, 0, "PLLCONFIG_2"), "FDA_FEEDBACK_3": ( 17, 0, "PLLCONFIG_3"), "FDA_RELATIVE_0": ( 17, 0, "PLLCONFIG_5"), "FDA_RELATIVE_1": ( 17, 0, "PLLCONFIG_6"), "FDA_RELATIVE_2": ( 17, 0, "PLLCONFIG_7"), "FDA_RELATIVE_3": ( 17, 0, "PLLCONFIG_8"), "DIVR_0": ( 14, 0, "PLLCONFIG_1"), "DIVR_1": ( 14, 0, "PLLCONFIG_2"), "DIVR_2": ( 14, 0, "PLLCONFIG_3"), "DIVR_3": ( 14, 0, "PLLCONFIG_4"), "DIVF_0": ( 14, 0, "PLLCONFIG_5"), "DIVF_1": ( 14, 0, "PLLCONFIG_6"), "DIVF_2": ( 14, 0, "PLLCONFIG_7"), "DIVF_3": ( 14, 0, "PLLCONFIG_8"), "DIVF_4": ( 14, 0, "PLLCONFIG_9"), "DIVF_5": ( 15, 0, "PLLCONFIG_1"), "DIVF_6": ( 15, 0, "PLLCONFIG_2"), "DIVQ_0": ( 15, 0, "PLLCONFIG_3"), "DIVQ_1": ( 15, 0, "PLLCONFIG_4"), "DIVQ_2": ( 15, 0, "PLLCONFIG_5"), "FILTER_RANGE_0": ( 15, 0, "PLLCONFIG_6"), "FILTER_RANGE_1": ( 15, 0, "PLLCONFIG_7"), "FILTER_RANGE_2": ( 15, 0, "PLLCONFIG_8"), "TEST_MODE": ( 16, 0, "PLLCONFIG_8"), # PLL Ports "PLLOUT_A": ( 16, 0, 1), "PLLOUT_B": ( 17, 0, 0), "REFERENCECLK": ( 13, 0, "fabout"), "EXTFEEDBACK": ( 14, 0, "fabout"), "DYNAMICDELAY_0": ( 5, 0, "fabout"), "DYNAMICDELAY_1": ( 6, 0, "fabout"), "DYNAMICDELAY_2": ( 7, 0, "fabout"), "DYNAMICDELAY_3": ( 8, 0, "fabout"), "DYNAMICDELAY_4": ( 9, 0, "fabout"), "DYNAMICDELAY_5": ( 10, 0, "fabout"), "DYNAMICDELAY_6": ( 11, 0, "fabout"), "DYNAMICDELAY_7": ( 12, 0, "fabout"), "LOCK": ( 1, 1, "neigh_op_bnl_1"), "BYPASS": ( 19, 0, "fabout"), "RESETB": ( 20, 0, "fabout"), "LATCHINPUTVALUE": ( 15, 0, "fabout"), "SDO": ( 32, 1, "neigh_op_bnr_3"), "SDI": ( 22, 0, "fabout"), "SCLK": ( 21, 0, "fabout"), }, "8k_0": { "LOC" : (16, 0), # 3'b000 = "DISABLED" # 3'b010 = "SB_PLL40_PAD" # 3'b100 = "SB_PLL40_2_PAD" # 3'b110 = "SB_PLL40_2F_PAD" # 3'b011 = "SB_PLL40_CORE" # 3'b111 = "SB_PLL40_2F_CORE" "PLLTYPE_0": ( 16, 0, "PLLCONFIG_5"), "PLLTYPE_1": ( 18, 0, "PLLCONFIG_1"), "PLLTYPE_2": ( 18, 0, "PLLCONFIG_3"), # 3'b000 = "DELAY" # 3'b001 = "SIMPLE" # 3'b010 = "PHASE_AND_DELAY" # 3'b110 = "EXTERNAL" "FEEDBACK_PATH_0": ( 18, 0, "PLLCONFIG_5"), "FEEDBACK_PATH_1": ( 15, 0, "PLLCONFIG_9"), "FEEDBACK_PATH_2": ( 16, 0, "PLLCONFIG_1"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_FEEDBACK=4'b1111) "DELAY_ADJMODE_FB": ( 17, 0, "PLLCONFIG_4"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_RELATIVE=4'b1111) "DELAY_ADJMODE_REL": ( 17, 0, "PLLCONFIG_9"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_A_0": ( 16, 0, "PLLCONFIG_6"), "PLLOUT_SELECT_A_1": ( 16, 0, "PLLCONFIG_7"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_B_0": ( 16, 0, "PLLCONFIG_2"), "PLLOUT_SELECT_B_1": ( 16, 0, "PLLCONFIG_3"), # Numeric Parameters "SHIFTREG_DIV_MODE": ( 16, 0, "PLLCONFIG_4"), "FDA_FEEDBACK_0": ( 16, 0, "PLLCONFIG_9"), "FDA_FEEDBACK_1": ( 17, 0, "PLLCONFIG_1"), "FDA_FEEDBACK_2": ( 17, 0, "PLLCONFIG_2"), "FDA_FEEDBACK_3": ( 17, 0, "PLLCONFIG_3"), "FDA_RELATIVE_0": ( 17, 0, "PLLCONFIG_5"), "FDA_RELATIVE_1": ( 17, 0, "PLLCONFIG_6"), "FDA_RELATIVE_2": ( 17, 0, "PLLCONFIG_7"), "FDA_RELATIVE_3": ( 17, 0, "PLLCONFIG_8"), "DIVR_0": ( 14, 0, "PLLCONFIG_1"), "DIVR_1": ( 14, 0, "PLLCONFIG_2"), "DIVR_2": ( 14, 0, "PLLCONFIG_3"), "DIVR_3": ( 14, 0, "PLLCONFIG_4"), "DIVF_0": ( 14, 0, "PLLCONFIG_5"), "DIVF_1": ( 14, 0, "PLLCONFIG_6"), "DIVF_2": ( 14, 0, "PLLCONFIG_7"), "DIVF_3": ( 14, 0, "PLLCONFIG_8"), "DIVF_4": ( 14, 0, "PLLCONFIG_9"), "DIVF_5": ( 15, 0, "PLLCONFIG_1"), "DIVF_6": ( 15, 0, "PLLCONFIG_2"), "DIVQ_0": ( 15, 0, "PLLCONFIG_3"), "DIVQ_1": ( 15, 0, "PLLCONFIG_4"), "DIVQ_2": ( 15, 0, "PLLCONFIG_5"), "FILTER_RANGE_0": ( 15, 0, "PLLCONFIG_6"), "FILTER_RANGE_1": ( 15, 0, "PLLCONFIG_7"), "FILTER_RANGE_2": ( 15, 0, "PLLCONFIG_8"), "TEST_MODE": ( 16, 0, "PLLCONFIG_8"), # PLL Ports "PLLOUT_A": ( 16, 0, 1), "PLLOUT_B": ( 17, 0, 0), "REFERENCECLK": ( 13, 0, "fabout"), "EXTFEEDBACK": ( 14, 0, "fabout"), "DYNAMICDELAY_0": ( 5, 0, "fabout"), "DYNAMICDELAY_1": ( 6, 0, "fabout"), "DYNAMICDELAY_2": ( 7, 0, "fabout"), "DYNAMICDELAY_3": ( 8, 0, "fabout"), "DYNAMICDELAY_4": ( 9, 0, "fabout"), "DYNAMICDELAY_5": ( 10, 0, "fabout"), "DYNAMICDELAY_6": ( 11, 0, "fabout"), "DYNAMICDELAY_7": ( 12, 0, "fabout"), "LOCK": ( 1, 1, "neigh_op_bnl_1"), "BYPASS": ( 19, 0, "fabout"), "RESETB": ( 20, 0, "fabout"), "LATCHINPUTVALUE": ( 15, 0, "fabout"), "SDO": ( 32, 1, "neigh_op_bnr_3"), "SDI": ( 22, 0, "fabout"), "SCLK": ( 21, 0, "fabout"), }, "8k_1": { "LOC" : (16, 33), # 3'b000 = "DISABLED" # 3'b010 = "SB_PLL40_PAD" # 3'b100 = "SB_PLL40_2_PAD" # 3'b110 = "SB_PLL40_2F_PAD" # 3'b011 = "SB_PLL40_CORE" # 3'b111 = "SB_PLL40_2F_CORE" "PLLTYPE_0": ( 16, 33, "PLLCONFIG_5"), "PLLTYPE_1": ( 18, 33, "PLLCONFIG_1"), "PLLTYPE_2": ( 18, 33, "PLLCONFIG_3"), # 3'b000 = "DELAY" # 3'b001 = "SIMPLE" # 3'b010 = "PHASE_AND_DELAY" # 3'b110 = "EXTERNAL" "FEEDBACK_PATH_0": ( 18, 33, "PLLCONFIG_5"), "FEEDBACK_PATH_1": ( 15, 33, "PLLCONFIG_9"), "FEEDBACK_PATH_2": ( 16, 33, "PLLCONFIG_1"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_FEEDBACK=4'b1111) "DELAY_ADJMODE_FB": ( 17, 33, "PLLCONFIG_4"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_RELATIVE=4'b1111) "DELAY_ADJMODE_REL": ( 17, 33, "PLLCONFIG_9"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_A_0": ( 16, 33, "PLLCONFIG_6"), "PLLOUT_SELECT_A_1": ( 16, 33, "PLLCONFIG_7"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_B_0": ( 16, 33, "PLLCONFIG_2"), "PLLOUT_SELECT_B_1": ( 16, 33, "PLLCONFIG_3"), # Numeric Parameters "SHIFTREG_DIV_MODE": ( 16, 33, "PLLCONFIG_4"), "FDA_FEEDBACK_0": ( 16, 33, "PLLCONFIG_9"), "FDA_FEEDBACK_1": ( 17, 33, "PLLCONFIG_1"), "FDA_FEEDBACK_2": ( 17, 33, "PLLCONFIG_2"), "FDA_FEEDBACK_3": ( 17, 33, "PLLCONFIG_3"), "FDA_RELATIVE_0": ( 17, 33, "PLLCONFIG_5"), "FDA_RELATIVE_1": ( 17, 33, "PLLCONFIG_6"), "FDA_RELATIVE_2": ( 17, 33, "PLLCONFIG_7"), "FDA_RELATIVE_3": ( 17, 33, "PLLCONFIG_8"), "DIVR_0": ( 14, 33, "PLLCONFIG_1"), "DIVR_1": ( 14, 33, "PLLCONFIG_2"), "DIVR_2": ( 14, 33, "PLLCONFIG_3"), "DIVR_3": ( 14, 33, "PLLCONFIG_4"), "DIVF_0": ( 14, 33, "PLLCONFIG_5"), "DIVF_1": ( 14, 33, "PLLCONFIG_6"), "DIVF_2": ( 14, 33, "PLLCONFIG_7"), "DIVF_3": ( 14, 33, "PLLCONFIG_8"), "DIVF_4": ( 14, 33, "PLLCONFIG_9"), "DIVF_5": ( 15, 33, "PLLCONFIG_1"), "DIVF_6": ( 15, 33, "PLLCONFIG_2"), "DIVQ_0": ( 15, 33, "PLLCONFIG_3"), "DIVQ_1": ( 15, 33, "PLLCONFIG_4"), "DIVQ_2": ( 15, 33, "PLLCONFIG_5"), "FILTER_RANGE_0": ( 15, 33, "PLLCONFIG_6"), "FILTER_RANGE_1": ( 15, 33, "PLLCONFIG_7"), "FILTER_RANGE_2": ( 15, 33, "PLLCONFIG_8"), "TEST_MODE": ( 16, 33, "PLLCONFIG_8"), # PLL Ports "PLLOUT_A": ( 16, 33, 1), "PLLOUT_B": ( 17, 33, 0), "REFERENCECLK": ( 13, 33, "fabout"), "EXTFEEDBACK": ( 14, 33, "fabout"), "DYNAMICDELAY_0": ( 5, 33, "fabout"), "DYNAMICDELAY_1": ( 6, 33, "fabout"), "DYNAMICDELAY_2": ( 7, 33, "fabout"), "DYNAMICDELAY_3": ( 8, 33, "fabout"), "DYNAMICDELAY_4": ( 9, 33, "fabout"), "DYNAMICDELAY_5": ( 10, 33, "fabout"), "DYNAMICDELAY_6": ( 11, 33, "fabout"), "DYNAMICDELAY_7": ( 12, 33, "fabout"), "LOCK": ( 1, 32, "neigh_op_tnl_1"), "BYPASS": ( 19, 33, "fabout"), "RESETB": ( 20, 33, "fabout"), "LATCHINPUTVALUE": ( 15, 33, "fabout"), "SDO": ( 32, 32, "neigh_op_tnr_1"), "SDI": ( 22, 33, "fabout"), "SCLK": ( 21, 33, "fabout"), }, } padin_pio_db = { "1k": [ (13, 8, 1), # glb_netwk_0 ( 0, 8, 1), # glb_netwk_1 ( 7, 17, 0), # glb_netwk_2 ( 7, 0, 0), # glb_netwk_3 ( 0, 9, 0), # glb_netwk_4 (13, 9, 0), # glb_netwk_5 ( 6, 0, 1), # glb_netwk_6 ( 6, 17, 1), # glb_netwk_7 ], "5k": [ ( 6, 0, 1), (19, 0, 1), ( 6, 31, 0), (12, 31, 1), (13, 31, 0), ], "8k": [ (33, 16, 1), ( 0, 16, 1), (17, 33, 0), (17, 0, 0), ( 0, 17, 0), (33, 17, 0), (16, 0, 1), (16, 33, 1), ], "384": [ ( 7, 4, 1), ( 0, 4, 1), ( 4, 9, 0), ( 4, 0, 0), #QFN32: no pin?! ( 0, 5, 0), ( 7, 5, 0), ( 3, 0, 1), #QFN32: no pin?! ( 3, 9, 1), ] } ieren_db = { "1k": [ # IO-block (X, Y, Z) <-> IeRen-block (X, Y, Z) ( 0, 2, 0, 0, 2, 1), ( 0, 2, 1, 0, 2, 0), ( 0, 3, 0, 0, 3, 1), ( 0, 3, 1, 0, 3, 0), ( 0, 4, 0, 0, 4, 1), ( 0, 4, 1, 0, 4, 0), ( 0, 5, 0, 0, 5, 1), ( 0, 5, 1, 0, 5, 0), ( 0, 6, 0, 0, 6, 1), ( 0, 6, 1, 0, 6, 0), ( 0, 8, 0, 0, 8, 1), ( 0, 8, 1, 0, 8, 0), ( 0, 9, 0, 0, 9, 1), ( 0, 9, 1, 0, 9, 0), ( 0, 10, 0, 0, 10, 1), ( 0, 10, 1, 0, 10, 0), ( 0, 11, 0, 0, 11, 1), ( 0, 11, 1, 0, 11, 0), ( 0, 12, 0, 0, 12, 1), ( 0, 12, 1, 0, 12, 0), ( 0, 13, 0, 0, 13, 1), ( 0, 13, 1, 0, 13, 0), ( 0, 14, 0, 0, 14, 1), ( 0, 14, 1, 0, 14, 0), ( 1, 0, 0, 1, 0, 0), ( 1, 0, 1, 1, 0, 1), ( 1, 17, 0, 1, 17, 0), ( 1, 17, 1, 1, 17, 1), ( 2, 0, 0, 2, 0, 0), ( 2, 0, 1, 2, 0, 1), ( 2, 17, 0, 2, 17, 0), ( 2, 17, 1, 2, 17, 1), ( 3, 0, 0, 3, 0, 0), ( 3, 0, 1, 3, 0, 1), ( 3, 17, 0, 3, 17, 0), ( 3, 17, 1, 3, 17, 1), ( 4, 0, 0, 4, 0, 0), ( 4, 0, 1, 4, 0, 1), ( 4, 17, 0, 4, 17, 0), ( 4, 17, 1, 4, 17, 1), ( 5, 0, 0, 5, 0, 0), ( 5, 0, 1, 5, 0, 1), ( 5, 17, 0, 5, 17, 0), ( 5, 17, 1, 5, 17, 1), ( 6, 0, 0, 7, 0, 0), ( 6, 0, 1, 6, 0, 0), ( 6, 17, 0, 6, 17, 0), ( 6, 17, 1, 6, 17, 1), ( 7, 0, 0, 6, 0, 1), ( 7, 0, 1, 7, 0, 1), ( 7, 17, 0, 7, 17, 0), ( 7, 17, 1, 7, 17, 1), ( 8, 0, 0, 8, 0, 0), ( 8, 0, 1, 8, 0, 1), ( 8, 17, 0, 8, 17, 0), ( 8, 17, 1, 8, 17, 1), ( 9, 0, 0, 9, 0, 0), ( 9, 0, 1, 9, 0, 1), ( 9, 17, 0, 10, 17, 0), ( 9, 17, 1, 10, 17, 1), (10, 0, 0, 10, 0, 0), (10, 0, 1, 10, 0, 1), (10, 17, 0, 9, 17, 0), (10, 17, 1, 9, 17, 1), (11, 0, 0, 11, 0, 0), (11, 0, 1, 11, 0, 1), (11, 17, 0, 11, 17, 0), (11, 17, 1, 11, 17, 1), (12, 0, 0, 12, 0, 0), (12, 0, 1, 12, 0, 1), (12, 17, 0, 12, 17, 0), (12, 17, 1, 12, 17, 1), (13, 1, 0, 13, 1, 0), (13, 1, 1, 13, 1, 1), (13, 2, 0, 13, 2, 0), (13, 2, 1, 13, 2, 1), (13, 3, 1, 13, 3, 1), (13, 4, 0, 13, 4, 0), (13, 4, 1, 13, 4, 1), (13, 6, 0, 13, 6, 0), (13, 6, 1, 13, 6, 1), (13, 7, 0, 13, 7, 0), (13, 7, 1, 13, 7, 1), (13, 8, 0, 13, 8, 0), (13, 8, 1, 13, 8, 1), (13, 9, 0, 13, 9, 0), (13, 9, 1, 13, 9, 1), (13, 11, 0, 13, 10, 0), (13, 11, 1, 13, 10, 1), (13, 12, 0, 13, 11, 0), (13, 12, 1, 13, 11, 1), (13, 13, 0, 13, 13, 0), (13, 13, 1, 13, 13, 1), (13, 14, 0, 13, 14, 0), (13, 14, 1, 13, 14, 1), (13, 15, 0, 13, 15, 0), (13, 15, 1, 13, 15, 1), ], "8k": [ ( 0, 3, 0, 0, 3, 0), ( 0, 3, 1, 0, 3, 1), ( 0, 4, 0, 0, 4, 0), ( 0, 4, 1, 0, 4, 1), ( 0, 5, 0, 0, 5, 0), ( 0, 5, 1, 0, 5, 1), ( 0, 6, 0, 0, 6, 0), ( 0, 6, 1, 0, 6, 1), ( 0, 7, 0, 0, 7, 0), ( 0, 7, 1, 0, 7, 1), ( 0, 8, 0, 0, 8, 0), ( 0, 8, 1, 0, 8, 1), ( 0, 9, 0, 0, 9, 0), ( 0, 9, 1, 0, 9, 1), ( 0, 10, 0, 0, 10, 0), ( 0, 10, 1, 0, 10, 1), ( 0, 11, 0, 0, 11, 0), ( 0, 11, 1, 0, 11, 1), ( 0, 12, 0, 0, 12, 0), ( 0, 12, 1, 0, 12, 1), ( 0, 13, 0, 0, 13, 0), ( 0, 13, 1, 0, 13, 1), ( 0, 14, 0, 0, 14, 0), ( 0, 14, 1, 0, 14, 1), ( 0, 16, 0, 0, 16, 0), ( 0, 16, 1, 0, 16, 1), ( 0, 17, 0, 0, 17, 0), ( 0, 17, 1, 0, 17, 1), ( 0, 18, 0, 0, 18, 0), ( 0, 18, 1, 0, 18, 1), ( 0, 19, 0, 0, 19, 0), ( 0, 19, 1, 0, 19, 1), ( 0, 20, 0, 0, 20, 0), ( 0, 20, 1, 0, 20, 1), ( 0, 21, 0, 0, 21, 0), ( 0, 21, 1, 0, 21, 1), ( 0, 22, 0, 0, 22, 0), ( 0, 22, 1, 0, 22, 1), ( 0, 23, 0, 0, 23, 0), ( 0, 23, 1, 0, 23, 1), ( 0, 24, 0, 0, 24, 0), ( 0, 24, 1, 0, 24, 1), ( 0, 25, 0, 0, 25, 0), ( 0, 25, 1, 0, 25, 1), ( 0, 27, 0, 0, 27, 0), ( 0, 27, 1, 0, 27, 1), ( 0, 28, 0, 0, 28, 0), ( 0, 28, 1, 0, 28, 1), ( 0, 30, 0, 0, 30, 0), ( 0, 30, 1, 0, 30, 1), ( 0, 31, 0, 0, 31, 0), ( 0, 31, 1, 0, 31, 1), ( 1, 33, 0, 1, 33, 0), ( 1, 33, 1, 1, 33, 1), ( 2, 0, 0, 2, 0, 0), ( 2, 0, 1, 2, 0, 1), ( 2, 33, 0, 2, 33, 0), ( 2, 33, 1, 2, 33, 1), ( 3, 0, 0, 3, 0, 0), ( 3, 0, 1, 3, 0, 1), ( 3, 33, 0, 3, 33, 0), ( 3, 33, 1, 3, 33, 1), ( 4, 0, 0, 4, 0, 0), ( 4, 0, 1, 4, 0, 1), ( 4, 33, 0, 4, 33, 0), ( 4, 33, 1, 4, 33, 1), ( 5, 0, 0, 5, 0, 0), ( 5, 0, 1, 5, 0, 1), ( 5, 33, 0, 5, 33, 0), ( 5, 33, 1, 5, 33, 1), ( 6, 0, 0, 6, 0, 0), ( 6, 0, 1, 6, 0, 1), ( 6, 33, 0, 6, 33, 0), ( 6, 33, 1, 6, 33, 1), ( 7, 0, 0, 7, 0, 0), ( 7, 0, 1, 7, 0, 1), ( 7, 33, 0, 7, 33, 0), ( 7, 33, 1, 7, 33, 1), ( 8, 0, 0, 8, 0, 0), ( 8, 0, 1, 8, 0, 1), ( 8, 33, 0, 8, 33, 0), ( 8, 33, 1, 8, 33, 1), ( 9, 0, 0, 9, 0, 0), ( 9, 0, 1, 9, 0, 1), ( 9, 33, 0, 9, 33, 0), ( 9, 33, 1, 9, 33, 1), (10, 0, 0, 10, 0, 0), (10, 0, 1, 10, 0, 1), (10, 33, 0, 10, 33, 0), (10, 33, 1, 10, 33, 1), (11, 0, 0, 11, 0, 0), (11, 0, 1, 11, 0, 1), (11, 33, 0, 11, 33, 0), (11, 33, 1, 11, 33, 1), (12, 0, 0, 12, 0, 0), (12, 0, 1, 12, 0, 1), (12, 33, 0, 12, 33, 0), (13, 0, 0, 13, 0, 0), (13, 0, 1, 13, 0, 1), (13, 33, 0, 13, 33, 0), (13, 33, 1, 13, 33, 1), (14, 0, 0, 14, 0, 0), (14, 0, 1, 14, 0, 1), (14, 33, 0, 14, 33, 0), (14, 33, 1, 14, 33, 1), (15, 0, 0, 15, 0, 0), (15, 0, 1, 15, 0, 1), (16, 0, 0, 16, 0, 0), (16, 0, 1, 16, 0, 1), (16, 33, 0, 16, 33, 0), (16, 33, 1, 16, 33, 1), (17, 0, 0, 17, 0, 0), (17, 0, 1, 17, 0, 1), (17, 33, 0, 17, 33, 0), (17, 33, 1, 17, 33, 1), (18, 33, 0, 18, 33, 0), (18, 33, 1, 18, 33, 1), (19, 0, 0, 19, 0, 0), (19, 0, 1, 19, 0, 1), (19, 33, 0, 19, 33, 0), (19, 33, 1, 19, 33, 1), (20, 0, 0, 20, 0, 0), (20, 0, 1, 20, 0, 1), (20, 33, 0, 20, 33, 0), (20, 33, 1, 20, 33, 1), (21, 0, 0, 21, 0, 0), (21, 0, 1, 21, 0, 1), (21, 33, 0, 21, 33, 0), (21, 33, 1, 21, 33, 1), (22, 0, 0, 22, 0, 0), (22, 0, 1, 22, 0, 1), (22, 33, 0, 22, 33, 0), (22, 33, 1, 22, 33, 1), (23, 0, 0, 23, 0, 0), (23, 0, 1, 23, 0, 1), (23, 33, 0, 23, 33, 0), (23, 33, 1, 23, 33, 1), (24, 0, 0, 24, 0, 0), (24, 0, 1, 24, 0, 1), (24, 33, 0, 24, 33, 0), (24, 33, 1, 24, 33, 1), (25, 0, 0, 25, 0, 0), (25, 33, 0, 25, 33, 0), (25, 33, 1, 25, 33, 1), (26, 0, 0, 26, 0, 0), (26, 0, 1, 26, 0, 1), (26, 33, 0, 26, 33, 0), (26, 33, 1, 26, 33, 1), (27, 0, 0, 27, 0, 0), (27, 0, 1, 27, 0, 1), (27, 33, 0, 27, 33, 0), (27, 33, 1, 27, 33, 1), (28, 0, 0, 28, 0, 0), (28, 33, 1, 28, 33, 1), (29, 0, 0, 29, 0, 0), (29, 0, 1, 29, 0, 1), (29, 33, 0, 29, 33, 0), (29, 33, 1, 29, 33, 1), (30, 0, 0, 30, 0, 0), (30, 0, 1, 30, 0, 1), (30, 33, 0, 30, 33, 0), (30, 33, 1, 30, 33, 1), (31, 0, 0, 31, 0, 0), (31, 0, 1, 31, 0, 1), (31, 33, 0, 31, 33, 0), (31, 33, 1, 31, 33, 1), (33, 1, 0, 33, 1, 0), (33, 1, 1, 33, 1, 1), (33, 2, 0, 33, 2, 0), (33, 2, 1, 33, 2, 1), (33, 3, 0, 33, 3, 0), (33, 3, 1, 33, 3, 1), (33, 4, 0, 33, 4, 0), (33, 4, 1, 33, 4, 1), (33, 5, 0, 33, 5, 0), (33, 5, 1, 33, 5, 1), (33, 6, 0, 33, 6, 0), (33, 6, 1, 33, 6, 1), (33, 7, 0, 33, 7, 0), (33, 7, 1, 33, 7, 1), (33, 8, 0, 33, 8, 0), (33, 9, 0, 33, 9, 0), (33, 9, 1, 33, 9, 1), (33, 10, 0, 33, 10, 0), (33, 10, 1, 33, 10, 1), (33, 11, 0, 33, 11, 0), (33, 11, 1, 33, 11, 1), (33, 12, 0, 33, 12, 0), (33, 13, 0, 33, 13, 0), (33, 13, 1, 33, 13, 1), (33, 14, 0, 33, 14, 0), (33, 14, 1, 33, 14, 1), (33, 15, 0, 33, 15, 0), (33, 15, 1, 33, 15, 1), (33, 16, 0, 33, 16, 0), (33, 16, 1, 33, 16, 1), (33, 17, 0, 33, 17, 0), (33, 17, 1, 33, 17, 1), (33, 19, 0, 33, 19, 0), (33, 19, 1, 33, 19, 1), (33, 20, 0, 33, 20, 0), (33, 20, 1, 33, 20, 1), (33, 21, 0, 33, 21, 0), (33, 21, 1, 33, 21, 1), (33, 22, 0, 33, 22, 0), (33, 22, 1, 33, 22, 1), (33, 23, 0, 33, 23, 0), (33, 23, 1, 33, 23, 1), (33, 24, 0, 33, 24, 0), (33, 24, 1, 33, 24, 1), (33, 25, 0, 33, 25, 0), (33, 25, 1, 33, 25, 1), (33, 26, 0, 33, 26, 0), (33, 26, 1, 33, 26, 1), (33, 27, 0, 33, 27, 0), (33, 27, 1, 33, 27, 1), (33, 28, 0, 33, 28, 0), (33, 28, 1, 33, 28, 1), (33, 29, 1, 33, 29, 1), (33, 30, 0, 33, 30, 0), (33, 30, 1, 33, 30, 1), (33, 31, 0, 33, 31, 0), ], "384": [ ( 0, 1, 0, 0, 1, 1), ( 0, 1, 1, 0, 1, 0), ( 0, 2, 0, 0, 2, 1), ( 0, 2, 1, 0, 2, 0), ( 0, 4, 0, 0, 4, 1), ( 0, 4, 1, 0, 4, 0), ( 0, 5, 0, 0, 5, 1), ( 0, 5, 1, 0, 5, 0), ( 0, 6, 0, 0, 6, 1), ( 0, 6, 1, 0, 6, 0), ( 0, 7, 0, 0, 7, 1), ( 0, 7, 1, 0, 7, 0), ( 2, 9, 0, 2, 9, 1), ( 2, 9, 1, 2, 9, 0), ( 3, 0, 0, 3, 0, 1), ( 3, 0, 1, 3, 0, 0), ( 3, 9, 0, 3, 9, 1), ( 3, 9, 1, 3, 9, 0), ( 4, 0, 0, 4, 0, 1), ( 4, 0, 1, 4, 0, 0), ( 4, 9, 0, 4, 9, 1), ( 4, 9, 1, 4, 9, 0), ( 5, 0, 0, 5, 0, 1), ( 5, 0, 1, 5, 0, 0), ( 5, 9, 0, 5, 9, 1), ( 5, 9, 1, 5, 9, 0), ( 6, 0, 0, 6, 0, 1), ( 6, 0, 1, 6, 0, 0), ( 6, 9, 0, 6, 9, 1), ( 6, 9, 1, 6, 9, 0), ( 7, 3, 1, 7, 3, 0), ( 7, 4, 0, 7, 4, 1), ( 7, 4, 1, 7, 4, 0), ( 7, 5, 0, 7, 5, 1), ( 7, 5, 1, 7, 5, 0), ( 7, 6, 0, 7, 6, 1), ( 7, 6, 1, 7, 6, 0), ], "5k": [ #TODO: is this correct? (1 , 0, 0, 1 , 0, 0), (1 , 0, 1, 1 , 0, 1), (1 , 31, 0, 1 , 31, 0), (1 , 31, 1, 1 , 31, 1), (2 , 0, 0, 2 , 0, 0), (2 , 0, 1, 2 , 0, 1), (2 , 31, 0, 2 , 31, 0), (2 , 31, 1, 2 , 31, 1), (3 , 0, 0, 3 , 0, 0), (3 , 0, 1, 3 , 0, 1), (3 , 31, 0, 3 , 31, 0), (3 , 31, 1, 3 , 31, 1), (4 , 0, 0, 4 , 0, 0), (4 , 0, 1, 4 , 0, 1), (4 , 31, 0, 4 , 31, 0), (4 , 31, 1, 4 , 31, 1), (5 , 0, 0, 5 , 0, 0), (5 , 0, 1, 5 , 0, 1), (5 , 31, 0, 5 , 31, 0), (5 , 31, 1, 5 , 31, 1), (6 , 0, 0, 6 , 0, 0), (6 , 0, 1, 6 , 0, 1), (6 , 31, 0, 6 , 31, 0), (6 , 31, 1, 6 , 31, 1), (7 , 0, 0, 7 , 0, 0), (7 , 0, 1, 7 , 0, 1), (7 , 31, 0, 7 , 31, 0), (7 , 31, 1, 7 , 31, 1), (8 , 0, 0, 8 , 0, 0), (8 , 0, 1, 8 , 0, 1), (8 , 31, 0, 8 , 31, 0), (8 , 31, 1, 8 , 31, 1), (9 , 0, 0, 9 , 0, 0), (9 , 0, 1, 9 , 0, 1), (9 , 31, 0, 9 , 31, 0), (9 , 31, 1, 9 , 31, 1), (10, 0, 0, 10, 0, 0), (10, 0, 1, 10, 0, 1), (10, 31, 0, 10, 31, 0), (10, 31, 1, 10, 31, 1), (11, 0, 0, 11, 0, 0), (11, 0, 1, 11, 0, 1), (11, 31, 0, 11, 31, 0), (11, 31, 1, 11, 31, 1), (12, 0, 0, 12, 0, 0), (12, 0, 1, 12, 0, 1), (12, 31, 0, 12, 31, 0), (12, 31, 1, 12, 31, 1), (13, 0, 0, 13, 0, 0), (13, 0, 1, 13, 0, 1), (13, 31, 0, 13, 31, 0), (13, 31, 1, 13, 31, 1), (14, 0, 0, 14, 0, 0), (14, 0, 1, 14, 0, 1), (14, 31, 0, 14, 31, 0), (14, 31, 1, 14, 31, 1), (15, 0, 0, 15, 0, 0), (15, 0, 1, 15, 0, 1), (15, 31, 0, 15, 31, 0), (15, 31, 1, 15, 31, 1), (16, 0, 0, 16, 0, 0), (16, 0, 1, 16, 0, 1), (16, 31, 0, 16, 31, 0), (16, 31, 1, 16, 31, 1), (17, 0, 0, 17, 0, 0), (17, 0, 1, 17, 0, 1), (17, 31, 0, 17, 31, 0), (17, 31, 1, 17, 31, 1), (18, 0, 0, 18, 0, 0), (18, 0, 1, 18, 0, 1), (18, 31, 0, 18, 31, 0), (18, 31, 1, 18, 31, 1), (19, 0, 0, 19, 0, 0), (19, 0, 1, 19, 0, 1), (19, 31, 0, 19, 31, 0), (19, 31, 1, 19, 31, 1), (20, 0, 0, 20, 0, 0), (20, 0, 1, 20, 0, 1), (20, 31, 0, 20, 31, 0), (20, 31, 1, 20, 31, 1), (21, 0, 0, 21, 0, 0), (21, 0, 1, 21, 0, 1), (21, 31, 0, 21, 31, 0), (21, 31, 1, 21, 31, 1), (22, 0, 0, 22, 0, 0), (22, 0, 1, 22, 0, 1), (22, 31, 0, 22, 31, 0), (22, 31, 1, 22, 31, 1), (23, 0, 0, 23, 0, 0), (23, 0, 1, 23, 0, 1), (23, 31, 0, 23, 31, 0), (23, 31, 1, 23, 31, 1), (24, 0, 0, 24, 0, 0), (24, 0, 1, 24, 0, 1), (24, 31, 0, 24, 31, 0), (24, 31, 1, 24, 31, 1) ] } # This dictionary maps package variants to a table of pin names and their # corresponding grid location (x, y, block). This is most easily found through # the package view in iCEcube2 by hovering the mouse over each pin. pinloc_db = { "1k-swg16tr": [ ( "A2", 6, 17, 1), ( "A4", 2, 17, 0), ( "B1", 11, 17, 1), ( "B2", 0, 8, 1), ( "B3", 0, 9, 0), ( "C1", 12, 0, 0), ( "C2", 11, 0, 1), ( "C3", 11, 0, 0), ( "D1", 12, 0, 1), ( "D3", 6, 0, 1), ], "1k-cm36": [ ( "A1", 0, 13, 0), ( "A2", 4, 17, 1), ( "A3", 7, 17, 0), ( "B1", 0, 13, 1), ( "B3", 6, 17, 1), ( "B4", 13, 9, 0), ( "B5", 13, 11, 0), ( "B6", 13, 11, 1), ( "C1", 0, 9, 0), ( "C2", 0, 9, 1), ( "C3", 4, 17, 0), ( "C5", 13, 8, 1), ( "C6", 13, 12, 0), ( "D1", 0, 8, 1), ( "D5", 12, 0, 1), ( "D6", 13, 6, 0), ( "E1", 0, 8, 0), ( "E2", 6, 0, 0), ( "E3", 10, 0, 0), ( "E4", 11, 0, 0), ( "E5", 12, 0, 0), ( "E6", 13, 4, 1), ( "F2", 6, 0, 1), ( "F3", 10, 0, 1), ( "F5", 11, 0, 1), ], "1k-cm49": [ ( "A1", 0, 11, 1), ( "A2", 3, 17, 1), ( "A3", 8, 17, 1), ( "A4", 8, 17, 0), ( "A5", 9, 17, 1), ( "A6", 10, 17, 0), ( "A7", 9, 17, 0), ( "B1", 0, 11, 0), ( "B2", 0, 13, 0), ( "B3", 4, 17, 0), ( "B4", 6, 17, 1), ( "C1", 0, 5, 0), ( "C2", 0, 13, 1), ( "C4", 7, 17, 0), ( "C5", 13, 12, 0), ( "C6", 13, 11, 1), ( "C7", 13, 11, 0), ( "D1", 0, 5, 1), ( "D2", 0, 9, 0), ( "D3", 0, 9, 1), ( "D4", 4, 17, 1), ( "D6", 13, 8, 1), ( "D7", 13, 9, 0), ( "E2", 0, 8, 1), ( "E6", 12, 0, 1), ( "E7", 13, 4, 1), ( "F2", 0, 8, 0), ( "F3", 6, 0, 0), ( "F4", 10, 0, 0), ( "F5", 11, 0, 0), ( "F6", 12, 0, 0), ( "F7", 13, 6, 0), ( "G3", 6, 0, 1), ( "G4", 10, 0, 1), ( "G6", 11, 0, 1), ], "1k-cm81": [ ( "A1", 1, 17, 1), ( "A2", 4, 17, 0), ( "A3", 5, 17, 0), ( "A4", 6, 17, 0), ( "A6", 8, 17, 1), ( "A7", 9, 17, 0), ( "A8", 10, 17, 0), ( "A9", 13, 14, 1), ( "B1", 0, 13, 0), ( "B2", 0, 14, 0), ( "B3", 2, 17, 1), ( "B4", 4, 17, 1), ( "B5", 8, 17, 0), ( "B6", 9, 17, 1), ( "B7", 10, 17, 1), ( "B8", 11, 17, 0), ( "B9", 13, 11, 1), ( "C1", 0, 13, 1), ( "C2", 0, 14, 1), ( "C3", 0, 12, 1), ( "C4", 6, 17, 1), ( "C5", 7, 17, 0), ( "C9", 13, 12, 0), ( "D1", 0, 11, 1), ( "D2", 0, 12, 0), ( "D3", 0, 9, 0), ( "D5", 3, 17, 1), ( "D6", 13, 6, 0), ( "D7", 13, 7, 0), ( "D8", 13, 9, 0), ( "D9", 13, 11, 0), ( "E1", 0, 10, 1), ( "E2", 0, 10, 0), ( "E3", 0, 8, 1), ( "E4", 0, 11, 0), ( "E5", 5, 17, 1), ( "E7", 13, 6, 1), ( "E8", 13, 8, 1), ( "F1", 0, 8, 0), ( "F3", 0, 9, 1), ( "F7", 12, 0, 1), ( "F8", 13, 4, 0), ( "G1", 0, 5, 1), ( "G3", 0, 5, 0), ( "G4", 6, 0, 0), ( "G5", 10, 0, 0), ( "G6", 11, 0, 0), ( "G7", 12, 0, 0), ( "G8", 13, 4, 1), ( "G9", 13, 2, 1), ( "H1", 2, 0, 0), ( "H4", 6, 0, 1), ( "H5", 10, 0, 1), ( "H7", 11, 0, 1), ( "H9", 13, 2, 0), ( "J1", 3, 0, 0), ( "J2", 2, 0, 1), ( "J3", 3, 0, 1), ( "J4", 5, 0, 0), ( "J6", 7, 0, 0), ( "J7", 9, 0, 1), ( "J8", 13, 1, 0), ( "J9", 13, 1, 1), ], "1k-cm121": [ ( "A1", 0, 14, 0), ( "A2", 2, 17, 1), ( "A3", 3, 17, 0), ( "A5", 5, 17, 1), ( "A7", 8, 17, 0), ( "A8", 10, 17, 1), ( "A9", 11, 17, 0), ("A10", 12, 17, 0), ("A11", 13, 15, 0), ( "B1", 0, 13, 0), ( "B2", 1, 17, 1), ( "B3", 2, 17, 0), ( "B4", 3, 17, 1), ( "B5", 4, 17, 1), ( "B7", 9, 17, 0), ( "B8", 11, 17, 1), ( "B9", 12, 17, 1), ("B10", 13, 15, 1), ("B11", 13, 14, 1), ( "C1", 0, 12, 0), ( "C2", 0, 13, 1), ( "C3", 0, 14, 1), ( "C4", 1, 17, 0), ( "C5", 4, 17, 0), ( "C6", 7, 17, 1), ( "C7", 8, 17, 1), ( "C8", 9, 17, 1), ( "C9", 10, 17, 0), ("C10", 13, 14, 0), ("C11", 13, 13, 1), ( "D1", 0, 11, 0), ( "D2", 0, 12, 1), ( "D3", 0, 11, 1), ( "D4", 0, 10, 1), ( "D5", 6, 17, 1), ( "D6", 7, 17, 0), ("D10", 13, 12, 1), ("D11", 13, 11, 1), ( "E2", 0, 10, 0), ( "E3", 0, 9, 1), ( "E4", 0, 9, 0), ( "E6", 5, 17, 0), ( "E7", 13, 12, 0), ( "E8", 13, 13, 0), ( "E9", 13, 9, 0), ("E10", 13, 9, 1), ( "F2", 0, 6, 0), ( "F3", 0, 5, 0), ( "F4", 0, 8, 1), ( "F5", 0, 8, 0), ( "F6", 6, 17, 0), ( "F8", 13, 11, 0), ( "F9", 13, 8, 1), ("F11", 13, 7, 1), ( "G2", 0, 5, 1), ( "G4", 0, 3, 0), ( "G8", 12, 0, 1), ( "G9", 13, 8, 0), ("G11", 13, 7, 0), ( "H1", 0, 6, 1), ( "H2", 0, 4, 1), ( "H4", 0, 2, 0), ( "H5", 6, 0, 0), ( "H6", 10, 0, 0), ( "H7", 11, 0, 0), ( "H8", 12, 0, 0), ( "H9", 13, 6, 1), ("H10", 13, 2, 1), ("H11", 13, 4, 1), ( "J1", 0, 4, 0), ( "J2", 1, 0, 1), ( "J5", 6, 0, 1), ( "J6", 10, 0, 1), ( "J8", 11, 0, 1), ("J10", 13, 2, 0), ("J11", 13, 6, 0), ( "K1", 0, 3, 1), ( "K2", 2, 0, 0), ( "K3", 2, 0, 1), ( "K4", 4, 0, 0), ( "K5", 5, 0, 0), ( "K7", 7, 0, 1), ( "K8", 9, 0, 0), ( "K9", 13, 1, 0), ("K10", 13, 1, 1), ("K11", 13, 3, 1), ( "L1", 0, 2, 1), ( "L2", 3, 0, 0), ( "L3", 3, 0, 1), ( "L4", 4, 0, 1), ( "L5", 7, 0, 0), ( "L7", 8, 0, 0), ( "L9", 8, 0, 1), ("L10", 9, 0, 1), ("L11", 13, 4, 0), ], "1k-cb81": [ ( "A2", 2, 17, 1), ( "A3", 3, 17, 1), ( "A4", 6, 17, 1), ( "A7", 11, 17, 0), ( "A8", 12, 17, 1), ( "B1", 0, 13, 1), ( "B2", 0, 14, 0), ( "B3", 0, 13, 0), ( "B4", 5, 17, 1), ( "B5", 8, 17, 1), ( "B6", 9, 17, 1), ( "B7", 11, 17, 1), ( "B8", 12, 17, 0), ( "C1", 0, 12, 0), ( "C2", 0, 10, 0), ( "C3", 0, 14, 1), ( "C4", 1, 17, 1), ( "C5", 8, 17, 0), ( "C6", 10, 17, 0), ( "C7", 13, 15, 0), ( "C8", 13, 15, 1), ( "C9", 13, 14, 1), ( "D1", 0, 9, 0), ( "D2", 0, 10, 1), ( "D3", 0, 12, 1), ( "D4", 5, 17, 0), ( "D5", 4, 17, 0), ( "D6", 7, 17, 0), ( "D7", 13, 13, 0), ( "D8", 13, 13, 1), ( "E1", 0, 8, 1), ( "E2", 0, 8, 0), ( "E3", 0, 9, 1), ( "E6", 10, 17, 1), ( "E7", 13, 12, 0), ( "E8", 13, 11, 0), ( "E9", 13, 11, 1), ( "F2", 0, 6, 1), ( "F3", 0, 6, 0), ( "F6", 13, 8, 0), ( "F7", 13, 9, 0), ( "F8", 13, 8, 1), ( "F9", 13, 7, 1), ( "G1", 0, 4, 1), ( "G2", 0, 2, 1), ( "G3", 3, 0, 1), ( "G4", 4, 0, 0), ( "G5", 10, 0, 0), ( "G6", 13, 4, 0), ( "G7", 13, 4, 1), ( "G8", 13, 6, 1), ( "G9", 13, 7, 0), ( "H2", 0, 4, 0), ( "H3", 2, 0, 1), ( "H4", 6, 0, 0), ( "H5", 10, 0, 1), ( "H7", 11, 0, 0), ( "H8", 12, 0, 1), ( "J2", 2, 0, 0), ( "J3", 6, 0, 1), ( "J7", 11, 0, 1), ( "J8", 12, 0, 0), ], "1k-cb121": [ ( "A2", 1, 17, 1), ( "A3", 2, 17, 0), ( "A4", 4, 17, 0), ( "A5", 3, 17, 1), ( "A6", 4, 17, 1), ( "A8", 10, 17, 0), ("A10", 12, 17, 1), ("A11", 13, 15, 0), ( "B1", 0, 14, 0), ( "B3", 1, 17, 0), ( "B4", 2, 17, 1), ( "B5", 3, 17, 0), ( "B8", 10, 17, 1), ( "B9", 12, 17, 0), ("B11", 13, 15, 1), ( "C1", 0, 14, 1), ( "C2", 0, 11, 1), ( "C3", 0, 13, 1), ( "C4", 0, 13, 0), ( "C5", 5, 17, 0), ( "C6", 7, 17, 0), ( "C7", 8, 17, 1), ( "C8", 11, 17, 0), ( "C9", 11, 17, 1), ("C11", 13, 14, 1), ( "D1", 0, 10, 1), ( "D2", 0, 11, 0), ( "D3", 0, 9, 0), ( "D4", 0, 12, 0), ( "D5", 5, 17, 1), ( "D6", 6, 17, 1), ( "D7", 8, 17, 0), ( "D8", 13, 12, 0), ( "D9", 13, 13, 0), ("D10", 13, 13, 1), ("D11", 13, 14, 0), ( "E2", 0, 10, 0), ( "E3", 0, 9, 1), ( "E4", 0, 12, 1), ( "E5", 6, 17, 0), ( "E6", 7, 17, 1), ( "E7", 9, 17, 0), ( "E8", 13, 11, 0), ( "E9", 13, 11, 1), ("E11", 13, 12, 1), ( "F2", 0, 6, 1), ( "F3", 0, 5, 1), ( "F4", 0, 8, 1), ( "F7", 9, 17, 1), ( "F8", 13, 8, 1), ( "F9", 13, 9, 0), ("F10", 13, 9, 1), ( "G1", 0, 6, 0), ( "G3", 0, 5, 0), ( "G4", 0, 8, 0), ( "G7", 13, 6, 1), ( "G8", 13, 7, 0), ( "G9", 13, 7, 1), ("G10", 13, 8, 0), ( "H1", 0, 3, 1), ( "H2", 0, 4, 1), ( "H3", 0, 4, 0), ( "H4", 4, 0, 0), ( "H5", 4, 0, 1), ( "H6", 10, 0, 0), ( "H7", 13, 4, 1), ( "H8", 13, 6, 0), ( "H9", 13, 4, 0), ("H10", 13, 3, 1), ("H11", 9, 0, 1), ( "J1", 0, 3, 0), ( "J2", 0, 2, 0), ( "J3", 0, 2, 1), ( "J4", 2, 0, 1), ( "J5", 3, 0, 0), ( "J6", 10, 0, 1), ( "J8", 11, 0, 0), ( "J9", 12, 0, 1), ("J11", 8, 0, 1), ( "K3", 1, 0, 0), ( "K4", 1, 0, 1), ( "K8", 11, 0, 1), ( "K9", 12, 0, 0), ("K11", 9, 0, 0), ( "L2", 2, 0, 0), ( "L3", 3, 0, 1), ( "L4", 5, 0, 0), ( "L5", 5, 0, 1), ( "L8", 7, 0, 0), ( "L9", 6, 0, 1), ("L10", 7, 0, 1), ("L11", 8, 0, 0), ], "1k-cb132": [ ( "A1", 1, 17, 1), ( "A2", 2, 17, 1), ( "A4", 4, 17, 0), ( "A5", 4, 17, 1), ( "A6", 6, 17, 1), ( "A7", 7, 17, 0), ("A10", 10, 17, 0), ("A12", 12, 17, 0), ( "B1", 0, 14, 1), ("B14", 13, 15, 0), ( "C1", 0, 14, 0), ( "C3", 0, 13, 1), ( "C4", 1, 17, 0), ( "C5", 3, 17, 0), ( "C6", 5, 17, 0), ( "C7", 6, 17, 0), ( "C8", 8, 17, 0), ( "C9", 9, 17, 0), ("C10", 11, 17, 0), ("C11", 11, 17, 1), ("C12", 12, 17, 1), ("C14", 13, 14, 0), ( "D1", 0, 11, 1), ( "D3", 0, 13, 0), ( "D4", 0, 12, 1), ( "D5", 2, 17, 0), ( "D6", 3, 17, 1), ( "D7", 5, 17, 1), ( "D8", 7, 17, 1), ( "D9", 8, 17, 1), ("D10", 9, 17, 1), ("D11", 10, 17, 1), ("D12", 13, 15, 1), ("D14", 13, 13, 1), ( "E1", 0, 11, 0), ( "E4", 0, 12, 0), ("E11", 13, 14, 1), ("E12", 13, 13, 0), ("E14", 13, 12, 0), ( "F3", 0, 10, 0), ( "F4", 0, 10, 1), ("F11", 13, 12, 1), ("F12", 13, 11, 1), ("F14", 13, 8, 1), ( "G1", 0, 8, 1), ( "G3", 0, 8, 0), ( "G4", 0, 6, 1), ("G11", 13, 11, 0), ("G12", 13, 9, 1), ("G14", 13, 9, 0), ( "H1", 0, 9, 0), ( "H3", 0, 9, 1), ( "H4", 0, 6, 0), ("H11", 13, 8, 0), ("H12", 13, 7, 1), ( "J1", 0, 5, 1), ( "J3", 0, 5, 0), ("J11", 13, 7, 0), ("J12", 13, 6, 1), ( "K3", 0, 3, 0), ( "K4", 0, 3, 1), ("K11", 13, 4, 1), ("K12", 13, 4, 0), ("K14", 13, 6, 0), ( "L1", 0, 2, 0), ( "L4", 1, 0, 1), ( "L5", 3, 0, 1), ( "L6", 4, 0, 1), ( "L7", 8, 0, 0), ( "L8", 9, 0, 0), ( "L9", 10, 0, 0), ("L12", 13, 2, 0), ("L14", 13, 3, 1), ( "M1", 0, 2, 1), ( "M3", 1, 0, 0), ( "M4", 3, 0, 0), ( "M6", 5, 0, 1), ( "M7", 6, 0, 0), ( "M8", 8, 0, 1), ( "M9", 9, 0, 1), ("M11", 11, 0, 0), ("M12", 13, 1, 0), ("N14", 13, 2, 1), ( "P2", 2, 0, 0), ( "P3", 2, 0, 1), ( "P4", 4, 0, 0), ( "P5", 5, 0, 0), ( "P7", 6, 0, 1), ( "P8", 7, 0, 0), ( "P9", 7, 0, 1), ("P10", 10, 0, 1), ("P11", 11, 0, 1), ("P12", 12, 0, 0), ("P13", 12, 0, 1), ("P14", 13, 1, 1), ], "1k-qn84": [ ( "A1", 0, 14, 0), ( "A2", 0, 13, 0), ( "A3", 0, 12, 0), ( "A4", 0, 11, 0), ( "A5", 0, 10, 0), ( "A8", 0, 9, 0), ( "A9", 0, 8, 1), ("A10", 0, 5, 1), ("A11", 0, 4, 0), ("A12", 0, 2, 0), ("A13", 4, 0, 0), ("A14", 6, 0, 1), ("A16", 6, 0, 0), ("A19", 9, 0, 1), ("A20", 10, 0, 1), ("A22", 11, 0, 1), ("A23", 12, 0, 0), ("A25", 13, 4, 0), ("A26", 13, 6, 0), ("A27", 13, 7, 1), ("A29", 13, 8, 1), ("A31", 13, 11, 1), ("A32", 13, 12, 1), ("A33", 13, 13, 1), ("A34", 13, 14, 0), ("A35", 13, 15, 0), ("A38", 11, 17, 0), ("A39", 10, 17, 0), ("A40", 9, 17, 0), ("A41", 8, 17, 0), ("A43", 7, 17, 0), ("A44", 6, 17, 0), ("A45", 5, 17, 0), ("A46", 4, 17, 0), ("A47", 3, 17, 0), ("A48", 1, 17, 1), ( "B1", 0, 13, 1), ( "B2", 0, 12, 1), ( "B3", 0, 11, 1), ( "B4", 0, 10, 1), ( "B5", 0, 9, 1), ( "B7", 0, 8, 0), ( "B8", 0, 5, 0), ( "B9", 0, 3, 0), ("B10", 5, 0, 0), ("B11", 5, 0, 1), ("B12", 7, 0, 0), ("B13", 8, 0, 0), ("B14", 9, 0, 0), ("B15", 10, 0, 0), ("B17", 11, 0, 0), ("B18", 12, 0, 1), ("B19", 13, 3, 1), ("B20", 13, 6, 1), ("B21", 13, 7, 0), ("B22", 13, 9, 0), ("B23", 13, 11, 0), ("B24", 13, 12, 0), ("B26", 13, 14, 1), ("B27", 13, 15, 1), ("B29", 10, 17, 1), ("B30", 9, 17, 1), ("B31", 8, 17, 1), ("B32", 6, 17, 1), ("B34", 4, 17, 1), ("B35", 3, 17, 1), ("B36", 2, 17, 1), ], "1k-tq144": [ ( "1", 0, 14, 1), ( "2", 0, 14, 0), ( "3", 0, 13, 1), ( "4", 0, 13, 0), ( "7", 0, 12, 1), ( "8", 0, 12, 0), ( "9", 0, 11, 1), ( "10", 0, 11, 0), ( "11", 0, 10, 1), ( "12", 0, 10, 0), ( "19", 0, 9, 1), ( "20", 0, 9, 0), ( "21", 0, 8, 1), ( "22", 0, 8, 0), ( "23", 0, 6, 1), ( "24", 0, 6, 0), ( "25", 0, 5, 1), ( "26", 0, 5, 0), ( "28", 0, 4, 1), ( "29", 0, 4, 0), ( "31", 0, 3, 1), ( "32", 0, 3, 0), ( "33", 0, 2, 1), ( "34", 0, 2, 0), ( "37", 1, 0, 0), ( "38", 1, 0, 1), ( "39", 2, 0, 0), ( "41", 2, 0, 1), ( "42", 3, 0, 0), ( "43", 3, 0, 1), ( "44", 4, 0, 0), ( "45", 4, 0, 1), ( "47", 5, 0, 0), ( "48", 5, 0, 1), ( "49", 6, 0, 1), ( "50", 7, 0, 0), ( "52", 6, 0, 0), ( "56", 7, 0, 1), ( "58", 8, 0, 0), ( "60", 8, 0, 1), ( "61", 9, 0, 0), ( "62", 9, 0, 1), ( "63", 10, 0, 0), ( "64", 10, 0, 1), ( "67", 11, 0, 0), ( "68", 11, 0, 1), ( "70", 12, 0, 0), ( "71", 12, 0, 1), ( "73", 13, 1, 0), ( "74", 13, 1, 1), ( "75", 13, 2, 0), ( "76", 13, 2, 1), ( "78", 13, 3, 1), ( "79", 13, 4, 0), ( "80", 13, 4, 1), ( "81", 13, 6, 0), ( "87", 13, 6, 1), ( "88", 13, 7, 0), ( "90", 13, 7, 1), ( "91", 13, 8, 0), ( "93", 13, 8, 1), ( "94", 13, 9, 0), ( "95", 13, 9, 1), ( "96", 13, 11, 0), ( "97", 13, 11, 1), ( "98", 13, 12, 0), ( "99", 13, 12, 1), ("101", 13, 13, 0), ("102", 13, 13, 1), ("104", 13, 14, 0), ("105", 13, 14, 1), ("106", 13, 15, 0), ("107", 13, 15, 1), ("112", 12, 17, 1), ("113", 12, 17, 0), ("114", 11, 17, 1), ("115", 11, 17, 0), ("116", 10, 17, 1), ("117", 10, 17, 0), ("118", 9, 17, 1), ("119", 9, 17, 0), ("120", 8, 17, 1), ("121", 8, 17, 0), ("122", 7, 17, 1), ("128", 7, 17, 0), ("129", 6, 17, 1), ("134", 5, 17, 1), ("135", 5, 17, 0), ("136", 4, 17, 1), ("137", 4, 17, 0), ("138", 3, 17, 1), ("139", 3, 17, 0), ("141", 2, 17, 1), ("142", 2, 17, 0), ("143", 1, 17, 1), ("144", 1, 17, 0), ], "1k-vq100": [ ( "1", 0, 14, 1), ( "2", 0, 14, 0), ( "3", 0, 13, 1), ( "4", 0, 13, 0), ( "7", 0, 12, 1), ( "8", 0, 12, 0), ( "9", 0, 10, 1), ( "10", 0, 10, 0), ( "12", 0, 9, 1), ( "13", 0, 9, 0), ( "15", 0, 8, 1), ( "16", 0, 8, 0), ( "18", 0, 6, 1), ( "19", 0, 6, 0), ( "20", 0, 4, 1), ( "21", 0, 4, 0), ( "24", 0, 2, 1), ( "25", 0, 2, 0), ( "26", 2, 0, 0), ( "27", 2, 0, 1), ( "28", 3, 0, 0), ( "29", 3, 0, 1), ( "30", 4, 0, 0), ( "33", 6, 0, 1), ( "34", 7, 0, 0), ( "36", 6, 0, 0), ( "37", 7, 0, 1), ( "40", 9, 0, 1), ( "41", 10, 0, 0), ( "42", 10, 0, 1), ( "45", 11, 0, 0), ( "46", 11, 0, 1), ( "48", 12, 0, 0), ( "49", 12, 0, 1), ( "51", 13, 3, 1), ( "52", 13, 4, 0), ( "53", 13, 4, 1), ( "54", 13, 6, 0), ( "56", 13, 6, 1), ( "57", 13, 7, 0), ( "59", 13, 7, 1), ( "60", 13, 8, 0), ( "62", 13, 8, 1), ( "63", 13, 9, 0), ( "64", 13, 11, 0), ( "65", 13, 11, 1), ( "66", 13, 12, 0), ( "68", 13, 13, 0), ( "69", 13, 13, 1), ( "71", 13, 14, 0), ( "72", 13, 14, 1), ( "73", 13, 15, 0), ( "74", 13, 15, 1), ( "78", 12, 17, 1), ( "79", 12, 17, 0), ( "80", 11, 17, 1), ( "81", 10, 17, 1), ( "82", 10, 17, 0), ( "83", 9, 17, 1), ( "85", 9, 17, 0), ( "86", 8, 17, 1), ( "87", 8, 17, 0), ( "89", 7, 17, 0), ( "90", 6, 17, 1), ( "91", 6, 17, 0), ( "93", 5, 17, 1), ( "94", 5, 17, 0), ( "95", 4, 17, 1), ( "96", 4, 17, 0), ( "97", 3, 17, 1), ( "99", 2, 17, 1), ("100", 1, 17, 1), ], "8k-cb132:4k": [ ( "A1", 2, 33, 0), ( "A2", 3, 33, 0), ( "A3", 3, 33, 1), ( "A4", 5, 33, 0), ( "A5", 10, 33, 1), ( "A6", 16, 33, 1), ( "A7", 17, 33, 0), ("A10", 25, 33, 0), ("A11", 26, 33, 0), ("A12", 30, 33, 1), ( "B1", 0, 30, 1), ("B14", 33, 28, 0), ( "C1", 0, 30, 0), ( "C3", 0, 27, 1), ( "C4", 4, 33, 0), ( "C5", 8, 33, 1), ( "C6", 11, 33, 1), ( "C7", 14, 33, 1), ( "C9", 20, 33, 1), ("C10", 22, 33, 1), ("C11", 28, 33, 1), ("C12", 29, 33, 1), ("C14", 33, 24, 1), ( "D1", 0, 25, 1), ( "D3", 0, 27, 0), ( "D4", 0, 22, 1), ( "D5", 9, 33, 0), ( "D6", 11, 33, 0), ( "D7", 13, 33, 1), ( "D9", 21, 33, 1), ("D10", 27, 33, 0), ("D11", 26, 33, 1), ("D12", 33, 27, 1), ("D14", 33, 23, 1), ( "E1", 0, 25, 0), ( "E4", 0, 22, 0), ("E11", 33, 20, 1), ("E12", 33, 21, 0), ("E14", 33, 21, 1), ( "F3", 0, 21, 0), ( "F4", 0, 21, 1), ("F11", 33, 19, 1), ("F12", 33, 15, 0), ("F14", 33, 16, 1), ( "G1", 0, 17, 0), ( "G3", 0, 17, 1), ( "G4", 0, 20, 0), ("G11", 33, 14, 1), ("G12", 33, 11, 0), ("G14", 33, 17, 0), ( "H1", 0, 16, 1), ( "H3", 0, 16, 0), ( "H4", 0, 20, 1), ("H11", 33, 10, 1), ("H12", 33, 6, 1), ( "J1", 0, 18, 0), ( "J3", 0, 18, 1), ("J11", 33, 6, 0), ("J12", 33, 5, 1), ( "K3", 0, 11, 1), ( "K4", 0, 11, 0), ("K11", 33, 4, 1), ("K12", 33, 4, 0), ("K14", 33, 5, 0), ( "L1", 0, 6, 1), ( "L4", 12, 0, 0), ( "L5", 11, 0, 1), ( "L6", 15, 0, 0), ( "L8", 20, 0, 1), ( "L9", 29, 0, 0), ("L12", 33, 2, 0), ("L14", 33, 3, 1), ( "M1", 0, 6, 0), ( "M3", 8, 0, 0), ( "M4", 7, 0, 1), ( "M6", 14, 0, 1), ( "M7", 15, 0, 1), ( "M9", 22, 0, 1), ("M11", 30, 0, 0), ("M12", 33, 1, 0), ( "N1", 0, 4, 1), ("N14", 33, 2, 1), ( "P1", 0, 4, 0), ( "P2", 4, 0, 0), ( "P3", 5, 0, 1), ( "P4", 12, 0, 1), ( "P5", 13, 0, 0), ( "P7", 16, 0, 1), ( "P8", 17, 0, 0), ( "P9", 21, 0, 1), ("P10", 29, 0, 1), ("P11", 30, 0, 1), ("P12", 31, 0, 0), ("P13", 31, 0, 1), ("P14", 33, 1, 1), ], "8k-tq144:4k": [ ( "1", 0, 30, 1), ( "2", 0, 30, 0), ( "3", 0, 28, 1), ( "4", 0, 28, 0), ( "7", 0, 27, 1), ( "8", 0, 27, 0), ( "9", 0, 25, 1), ( "10", 0, 25, 0), ( "11", 0, 22, 1), ( "12", 0, 22, 0), ( "15", 0, 20, 1), ( "16", 0, 20, 0), ( "17", 0, 18, 1), ( "18", 0, 18, 0), ( "19", 0, 17, 1), ( "20", 0, 17, 0), ( "21", 0, 16, 1), ( "22", 0, 16, 0), ( "23", 0, 12, 1), ( "24", 0, 12, 0), ( "25", 0, 11, 1), ( "26", 0, 11, 0), ( "28", 0, 6, 1), ( "29", 0, 6, 0), ( "31", 0, 5, 1), ( "32", 0, 5, 0), ( "33", 0, 4, 1), ( "34", 0, 4, 0), ( "37", 4, 0, 0), ( "38", 4, 0, 1), ( "39", 6, 0, 1), ( "41", 7, 0, 1), ( "42", 8, 0, 0), ( "43", 11, 0, 1), ( "44", 12, 0, 0), ( "45", 12, 0, 1), ( "47", 15, 0, 1), ( "48", 16, 0, 0), ( "49", 16, 0, 1), ( "52", 17, 0, 0), ( "55", 22, 0, 1), ( "56", 24, 0, 0), ( "60", 24, 0, 1), ( "61", 25, 0, 0), ( "62", 28, 0, 0), ( "63", 29, 0, 0), ( "64", 29, 0, 1), ( "67", 30, 0, 0), ( "68", 30, 0, 1), ( "70", 31, 0, 0), ( "71", 31, 0, 1), ( "73", 33, 1, 0), ( "74", 33, 1, 1), ( "75", 33, 2, 0), ( "76", 33, 2, 1), ( "78", 33, 3, 1), ( "79", 33, 4, 0), ( "80", 33, 4, 1), ( "81", 33, 5, 0), ( "82", 33, 5, 1), ( "83", 33, 6, 0), ( "84", 33, 6, 1), ( "85", 33, 10, 1), ( "87", 33, 14, 1), ( "88", 33, 15, 0), ( "90", 33, 15, 1), ( "91", 33, 16, 0), ( "93", 33, 16, 1), ( "94", 33, 17, 0), ( "95", 33, 19, 1), ( "96", 33, 20, 1), ( "97", 33, 21, 0), ( "98", 33, 21, 1), ( "99", 33, 23, 1), ("101", 33, 27, 1), ("102", 33, 28, 0), ("104", 33, 29, 1), ("105", 33, 30, 0), ("106", 33, 30, 1), ("107", 33, 31, 0), ("110", 31, 33, 1), ("112", 31, 33, 0), ("113", 30, 33, 1), ("114", 30, 33, 0), ("115", 29, 33, 1), ("116", 29, 33, 0), ("117", 28, 33, 1), ("118", 27, 33, 0), ("119", 26, 33, 1), ("120", 26, 33, 0), ("121", 25, 33, 0), ("122", 20, 33, 1), ("124", 20, 33, 0), ("125", 19, 33, 1), ("128", 17, 33, 0), ("129", 16, 33, 1), ("130", 11, 33, 1), ("134", 8, 33, 1), ("135", 8, 33, 0), ("136", 7, 33, 1), ("137", 7, 33, 0), ("138", 6, 33, 1), ("139", 6, 33, 0), ("141", 5, 33, 0), ("142", 4, 33, 1), ("143", 4, 33, 0), ("144", 3, 33, 1), ], "8k-cm81:4k": [ ( "A1", 2, 33, 1), ( "A2", 4, 33, 0), ( "A3", 6, 33, 0), ( "A4", 10, 33, 1), ( "A6", 23, 33, 0), ( "A7", 27, 33, 0), ( "A8", 28, 33, 1), ( "A9", 33, 4, 1), ( "B1", 0, 28, 1), ( "B2", 0, 30, 0), ( "B3", 5, 33, 1), ( "B4", 9, 33, 0), ( "B5", 21, 33, 1), ( "B6", 24, 33, 0), ( "B7", 25, 33, 1), ( "B8", 30, 33, 1), ( "B9", 33, 6, 1), ( "C1", 0, 28, 0), ( "C2", 0, 30, 1), ( "C3", 0, 23, 0), ( "C4", 16, 33, 1), ( "C5", 17, 33, 0), ( "C9", 33, 21, 1), ( "D1", 0, 20, 1), ( "D2", 0, 23, 1), ( "D3", 0, 17, 0), ( "D5", 8, 33, 1), ( "D6", 33, 4, 0), ( "D7", 33, 5, 0), ( "D8", 33, 17, 0), ( "D9", 33, 6, 0), ( "E1", 0, 20, 0), ( "E2", 0, 17, 1), ( "E3", 0, 16, 1), ( "E4", 0, 16, 0), ( "E5", 7, 33, 1), ( "E7", 33, 5, 1), ( "E8", 33, 16, 1), ( "F1", 0, 7, 1), ( "F3", 0, 7, 0), ( "F7", 31, 0, 1), ( "F8", 33, 3, 0), ( "G1", 0, 5, 0), ( "G2", 0, 3, 1), ( "G3", 0, 5, 1), ( "G4", 16, 0, 1), ( "G5", 29, 0, 0), ( "G6", 30, 0, 0), ( "G7", 31, 0, 0), ( "G8", 33, 3, 1), ( "G9", 33, 2, 1), ( "H1", 3, 0, 0), ( "H2", 0, 3, 0), ( "H4", 17, 0, 0), ( "H5", 29, 0, 1), ( "H7", 30, 0, 1), ( "H9", 33, 2, 0), ( "J1", 3, 0, 1), ( "J2", 4, 0, 0), ( "J3", 4, 0, 1), ( "J4", 11, 0, 0), ( "J8", 33, 1, 0), ( "J9", 33, 1, 1), ], "8k-cm121:4k": [ ( "A1", 2, 33, 0), ( "A2", 3, 33, 1), ( "A3", 3, 33, 0), ( "A4", 9, 33, 0), ( "A5", 11, 33, 0), ( "A6", 11, 33, 1), ( "A7", 19, 33, 1), ( "A8", 20, 33, 1), ( "A9", 26, 33, 1), ("A10", 30, 33, 1), ("A11", 31, 33, 1), ( "B1", 0, 30, 1), ( "B2", 0, 30, 0), ( "B3", 4, 33, 0), ( "B4", 5, 33, 0), ( "B5", 10, 33, 1), ( "B6", 16, 33, 1), ( "B7", 17, 33, 0), ( "B8", 27, 33, 0), ( "B9", 28, 33, 1), ("B11", 33, 28, 0), ( "C1", 0, 25, 0), ( "C2", 0, 25, 1), ( "C3", 0, 27, 0), ( "C4", 0, 27, 1), ( "C7", 20, 33, 0), ( "C8", 26, 33, 0), ( "C9", 29, 33, 1), ("C11", 33, 27, 1), ( "D1", 0, 22, 0), ( "D2", 0, 21, 1), ( "D3", 0, 21, 0), ( "D5", 8, 33, 1), ( "D7", 25, 33, 0), ( "D9", 33, 21, 0), ("D10", 33, 24, 1), ("D11", 33, 23, 1), ( "E1", 0, 22, 1), ( "E2", 0, 20, 1), ( "E3", 0, 20, 0), ( "E8", 33, 20, 1), ( "E9", 33, 19, 1), ("E10", 33, 17, 0), ("E11", 33, 21, 1), ( "F1", 0, 18, 1), ( "F2", 0, 18, 0), ( "F3", 0, 17, 0), ( "F4", 0, 17, 1), ( "F9", 33, 15, 0), ("F10", 33, 14, 1), ("F11", 33, 16, 1), ( "G1", 0, 16, 1), ( "G2", 0, 16, 0), ( "G3", 0, 12, 1), ( "G8", 33, 5, 1), ( "G9", 33, 10, 1), ("G10", 33, 6, 1), ("G11", 33, 11, 0), ( "H1", 0, 11, 1), ( "H2", 0, 11, 0), ( "H3", 0, 12, 0), ( "H7", 20, 0, 1), ( "H9", 29, 0, 1), ("H10", 33, 4, 1), ("H11", 33, 6, 0), ( "J1", 0, 6, 1), ( "J2", 0, 4, 0), ( "J3", 4, 0, 1), ( "J4", 8, 0, 0), ( "J5", 15, 0, 0), ( "J7", 20, 0, 0), ( "J8", 22, 0, 1), ( "J9", 30, 0, 1), ("J10", 33, 5, 0), ("J11", 33, 3, 1), ( "K1", 0, 6, 0), ( "K2", 0, 4, 1), ( "K3", 7, 0, 1), ( "K4", 12, 0, 1), ( "K5", 15, 0, 1), ( "K6", 17, 0, 0), ( "K7", 21, 0, 1), ( "K9", 30, 0, 0), ("K10", 31, 0, 1), ("K11", 33, 4, 0), ( "L1", 4, 0, 0), ( "L2", 6, 0, 1), ( "L3", 11, 0, 1), ( "L4", 12, 0, 0), ( "L5", 16, 0, 1), ( "L7", 24, 0, 0), ( "L8", 29, 0, 0), ("L10", 31, 0, 0), ], "8k-cm225:4k": [ ( "A1", 1, 33, 1), ( "A2", 3, 33, 1), ( "A5", 6, 33, 1), ( "A6", 11, 33, 0), ( "A7", 12, 33, 0), ( "A8", 17, 33, 1), ( "A9", 18, 33, 1), ("A11", 23, 33, 1), ("A15", 31, 33, 0), ( "B2", 2, 33, 1), ( "B3", 4, 33, 1), ( "B4", 5, 33, 1), ( "B5", 7, 33, 1), ( "B6", 10, 33, 0), ( "B7", 14, 33, 0), ( "B8", 19, 33, 1), ( "B9", 18, 33, 0), ("B10", 22, 33, 0), ("B11", 23, 33, 0), ("B12", 25, 33, 1), ("B13", 27, 33, 1), ("B14", 31, 33, 1), ("B15", 33, 31, 0), ( "C1", 0, 28, 0), ( "C3", 2, 33, 0), ( "C4", 3, 33, 0), ( "C5", 5, 33, 0), ( "C6", 13, 33, 0), ( "C7", 11, 33, 1), ( "C8", 19, 33, 0), ( "C9", 17, 33, 0), ("C10", 20, 33, 0), ("C11", 24, 33, 1), ("C12", 30, 33, 1), ("C13", 30, 33, 0), ("C14", 33, 30, 0), ( "D1", 0, 25, 0), ( "D2", 0, 24, 1), ( "D3", 0, 27, 0), ( "D4", 0, 30, 0), ( "D5", 4, 33, 0), ( "D6", 9, 33, 0), ( "D7", 10, 33, 1), ( "D8", 16, 33, 1), ( "D9", 26, 33, 1), ("D10", 25, 33, 0), ("D11", 28, 33, 1), ("D13", 33, 27, 1), ("D14", 33, 25, 0), ("D15", 33, 27, 0), ( "E2", 0, 24, 0), ( "E3", 0, 28, 1), ( "E4", 0, 30, 1), ( "E5", 0, 27, 1), ( "E6", 0, 25, 1), ( "E9", 26, 33, 0), ("E10", 27, 33, 0), ("E11", 29, 33, 1), ("E13", 33, 28, 0), ("E14", 33, 24, 0), ( "F1", 0, 20, 0), ( "F2", 0, 21, 0), ( "F3", 0, 21, 1), ( "F4", 0, 22, 0), ( "F5", 0, 22, 1), ( "F7", 8, 33, 1), ( "F9", 20, 33, 1), ("F11", 33, 24, 1), ("F12", 33, 23, 1), ("F13", 33, 23, 0), ("F14", 33, 21, 0), ("F15", 33, 22, 0), ( "G2", 0, 20, 1), ( "G4", 0, 17, 0), ( "G5", 0, 18, 1), ("G10", 33, 20, 1), ("G11", 33, 19, 1), ("G12", 33, 21, 1), ("G13", 33, 17, 0), ("G14", 33, 20, 0), ("G15", 33, 19, 0), ( "H1", 0, 16, 0), ( "H2", 0, 18, 0), ( "H3", 0, 14, 1), ( "H4", 0, 13, 1), ( "H5", 0, 16, 1), ( "H6", 0, 17, 1), ("H11", 33, 14, 1), ("H12", 33, 16, 1), ("H13", 33, 15, 1), ("H14", 33, 15, 0), ( "J1", 0, 13, 0), ( "J2", 0, 12, 0), ( "J3", 0, 14, 0), ( "J4", 0, 11, 1), ( "J5", 0, 12, 1), ("J10", 33, 5, 1), ("J11", 33, 10, 1), ("J12", 33, 6, 1), ("J14", 33, 14, 0), ("J15", 33, 13, 0), ( "K1", 0, 11, 0), ( "K4", 0, 4, 0), ( "K5", 0, 6, 1), ( "K9", 20, 0, 1), ("K11", 29, 0, 0), ("K12", 33, 4, 1), ("K13", 33, 5, 0), ("K15", 33, 9, 0), ( "L3", 0, 7, 1), ( "L4", 0, 3, 0), ( "L5", 4, 0, 0), ( "L6", 7, 0, 0), ( "L7", 12, 0, 0), ( "L9", 17, 0, 0), ("L10", 21, 0, 1), ("L11", 30, 0, 1), ("L12", 33, 3, 1), ("L13", 33, 6, 0), ( "M1", 0, 7, 0), ( "M2", 0, 6, 0), ( "M3", 0, 5, 0), ( "M4", 0, 3, 1), ( "M5", 6, 0, 0), ( "M6", 8, 0, 0), ( "M7", 13, 0, 1), ( "M8", 15, 0, 0), ( "M9", 19, 0, 1), ("M11", 30, 0, 0), ("M12", 31, 0, 1), ("M13", 33, 4, 0), ("M15", 33, 3, 0), ( "N2", 0, 5, 1), ( "N3", 2, 0, 0), ( "N4", 3, 0, 0), ( "N5", 9, 0, 1), ( "N6", 12, 0, 1), ( "N7", 16, 0, 1), ( "N9", 20, 0, 0), ("N10", 22, 0, 1), ("N12", 31, 0, 0), ( "P1", 0, 4, 1), ( "P2", 2, 0, 1), ( "P4", 7, 0, 1), ( "P5", 10, 0, 1), ( "P6", 14, 0, 1), ( "P7", 17, 0, 1), ( "P8", 19, 0, 0), ( "P9", 22, 0, 0), ("P10", 23, 0, 0), ("P11", 25, 0, 0), ("P12", 29, 0, 1), ("P13", 27, 0, 0), ("P14", 33, 2, 1), ("P15", 33, 1, 1), ( "R1", 3, 0, 1), ( "R2", 4, 0, 1), ( "R3", 6, 0, 1), ( "R4", 8, 0, 1), ( "R5", 11, 0, 1), ( "R6", 15, 0, 1), ( "R9", 21, 0, 0), ("R10", 24, 0, 0), ("R11", 26, 0, 0), ("R12", 28, 0, 0), ("R14", 33, 2, 0), ("R15", 33, 1, 0), ], "8k-cm81": [ ( "A1", 2, 33, 1), ( "A2", 4, 33, 0), ( "A3", 6, 33, 0), ( "A4", 10, 33, 1), ( "A6", 23, 33, 0), ( "A7", 27, 33, 0), ( "A8", 28, 33, 1), ( "A9", 33, 4, 1), ( "B1", 0, 28, 1), ( "B2", 0, 30, 0), ( "B3", 5, 33, 1), ( "B4", 9, 33, 0), ( "B5", 21, 33, 1), ( "B6", 24, 33, 0), ( "B7", 25, 33, 1), ( "B8", 30, 33, 1), ( "B9", 33, 6, 1), ( "C1", 0, 28, 0), ( "C2", 0, 30, 1), ( "C3", 0, 23, 0), ( "C4", 16, 33, 1), ( "C5", 17, 33, 0), ( "C9", 33, 21, 1), ( "D1", 0, 20, 1), ( "D2", 0, 23, 1), ( "D3", 0, 17, 0), ( "D5", 8, 33, 1), ( "D6", 33, 4, 0), ( "D7", 33, 5, 0), ( "D8", 33, 17, 0), ( "D9", 33, 6, 0), ( "E1", 0, 20, 0), ( "E2", 0, 17, 1), ( "E3", 0, 16, 1), ( "E4", 0, 16, 0), ( "E5", 7, 33, 1), ( "E7", 33, 5, 1), ( "E8", 33, 16, 1), ( "F1", 0, 7, 1), ( "F3", 0, 7, 0), ( "F7", 31, 0, 1), ( "F8", 33, 3, 0), ( "G1", 0, 5, 0), ( "G2", 0, 3, 1), ( "G3", 0, 5, 1), ( "G4", 16, 0, 1), ( "G5", 29, 0, 0), ( "G6", 30, 0, 0), ( "G7", 31, 0, 0), ( "G8", 33, 3, 1), ( "G9", 33, 2, 1), ( "H1", 3, 0, 0), ( "H2", 0, 3, 0), ( "H4", 17, 0, 0), ( "H5", 29, 0, 1), ( "H7", 30, 0, 1), ( "H9", 33, 2, 0), ( "J1", 3, 0, 1), ( "J2", 4, 0, 0), ( "J3", 4, 0, 1), ( "J4", 11, 0, 0), ( "J8", 33, 1, 0), ( "J9", 33, 1, 1), ], "8k-cm121": [ ( "A1", 2, 33, 0), ( "A2", 3, 33, 1), ( "A3", 3, 33, 0), ( "A4", 9, 33, 0), ( "A5", 11, 33, 0), ( "A6", 11, 33, 1), ( "A7", 19, 33, 1), ( "A8", 20, 33, 1), ( "A9", 26, 33, 1), ("A10", 30, 33, 1), ("A11", 31, 33, 1), ( "B1", 0, 30, 1), ( "B2", 0, 30, 0), ( "B3", 4, 33, 0), ( "B4", 5, 33, 0), ( "B5", 10, 33, 1), ( "B6", 16, 33, 1), ( "B7", 17, 33, 0), ( "B8", 27, 33, 0), ( "B9", 28, 33, 1), ("B11", 33, 28, 0), ( "C1", 0, 25, 0), ( "C2", 0, 25, 1), ( "C3", 0, 27, 0), ( "C4", 0, 27, 1), ( "C7", 20, 33, 0), ( "C8", 26, 33, 0), ( "C9", 29, 33, 1), ("C11", 33, 27, 1), ( "D1", 0, 22, 0), ( "D2", 0, 21, 1), ( "D3", 0, 21, 0), ( "D5", 8, 33, 1), ( "D7", 25, 33, 0), ( "D9", 33, 21, 0), ("D10", 33, 24, 1), ("D11", 33, 23, 1), ( "E1", 0, 22, 1), ( "E2", 0, 20, 1), ( "E3", 0, 20, 0), ( "E8", 33, 20, 1), ( "E9", 33, 19, 1), ("E10", 33, 17, 0), ("E11", 33, 21, 1), ( "F1", 0, 18, 1), ( "F2", 0, 18, 0), ( "F3", 0, 17, 0), ( "F4", 0, 17, 1), ( "F9", 33, 15, 0), ("F10", 33, 14, 1), ("F11", 33, 16, 1), ( "G1", 0, 16, 1), ( "G2", 0, 16, 0), ( "G3", 0, 12, 1), ( "G8", 33, 5, 1), ( "G9", 33, 10, 1), ("G10", 33, 6, 1), ("G11", 33, 11, 0), ( "H1", 0, 11, 1), ( "H2", 0, 11, 0), ( "H3", 0, 12, 0), ( "H7", 20, 0, 1), ( "H9", 29, 0, 1), ("H10", 33, 4, 1), ("H11", 33, 6, 0), ( "J1", 0, 6, 1), ( "J2", 0, 4, 0), ( "J3", 4, 0, 1), ( "J4", 8, 0, 0), ( "J5", 15, 0, 0), ( "J7", 20, 0, 0), ( "J8", 22, 0, 1), ( "J9", 30, 0, 1), ("J10", 33, 5, 0), ("J11", 33, 3, 1), ( "K1", 0, 6, 0), ( "K2", 0, 4, 1), ( "K3", 7, 0, 1), ( "K4", 12, 0, 1), ( "K5", 15, 0, 1), ( "K6", 17, 0, 0), ( "K7", 21, 0, 1), ( "K9", 30, 0, 0), ("K10", 31, 0, 1), ("K11", 33, 4, 0), ( "L1", 4, 0, 0), ( "L2", 6, 0, 1), ( "L3", 11, 0, 1), ( "L4", 12, 0, 0), ( "L5", 16, 0, 1), ( "L7", 24, 0, 0), ( "L8", 29, 0, 0), ("L10", 31, 0, 0), ], "8k-cm225": [ ( "A1", 1, 33, 1), ( "A2", 3, 33, 1), ( "A5", 6, 33, 1), ( "A6", 11, 33, 0), ( "A7", 12, 33, 0), ( "A8", 17, 33, 1), ( "A9", 18, 33, 1), ("A10", 21, 33, 0), ("A11", 23, 33, 1), ("A15", 31, 33, 0), ( "B1", 0, 31, 0), ( "B2", 2, 33, 1), ( "B3", 4, 33, 1), ( "B4", 5, 33, 1), ( "B5", 7, 33, 1), ( "B6", 10, 33, 0), ( "B7", 14, 33, 0), ( "B8", 19, 33, 1), ( "B9", 18, 33, 0), ("B10", 22, 33, 0), ("B11", 23, 33, 0), ("B12", 25, 33, 1), ("B13", 27, 33, 1), ("B14", 31, 33, 1), ("B15", 33, 31, 0), ( "C1", 0, 28, 0), ( "C2", 0, 31, 1), ( "C3", 2, 33, 0), ( "C4", 3, 33, 0), ( "C5", 5, 33, 0), ( "C6", 13, 33, 0), ( "C7", 11, 33, 1), ( "C8", 19, 33, 0), ( "C9", 17, 33, 0), ("C10", 20, 33, 0), ("C11", 24, 33, 1), ("C12", 30, 33, 1), ("C13", 30, 33, 0), ("C14", 33, 30, 0), ( "D1", 0, 25, 0), ( "D2", 0, 24, 1), ( "D3", 0, 27, 0), ( "D4", 0, 30, 0), ( "D5", 4, 33, 0), ( "D6", 9, 33, 0), ( "D7", 10, 33, 1), ( "D8", 16, 33, 1), ( "D9", 26, 33, 1), ("D10", 25, 33, 0), ("D11", 28, 33, 1), ("D13", 33, 27, 1), ("D14", 33, 25, 0), ("D15", 33, 27, 0), ( "E2", 0, 24, 0), ( "E3", 0, 28, 1), ( "E4", 0, 30, 1), ( "E5", 0, 27, 1), ( "E6", 0, 25, 1), ( "E9", 26, 33, 0), ("E10", 27, 33, 0), ("E11", 29, 33, 1), ("E13", 33, 28, 0), ("E14", 33, 24, 0), ( "F1", 0, 20, 0), ( "F2", 0, 21, 0), ( "F3", 0, 21, 1), ( "F4", 0, 22, 0), ( "F5", 0, 22, 1), ( "F7", 8, 33, 1), ( "F9", 20, 33, 1), ("F11", 33, 24, 1), ("F12", 33, 23, 1), ("F13", 33, 23, 0), ("F14", 33, 21, 0), ("F15", 33, 22, 0), ( "G1", 0, 19, 0), ( "G2", 0, 20, 1), ( "G3", 0, 19, 1), ( "G4", 0, 17, 0), ( "G5", 0, 18, 1), ("G10", 33, 20, 1), ("G11", 33, 19, 1), ("G12", 33, 21, 1), ("G13", 33, 17, 0), ("G14", 33, 20, 0), ("G15", 33, 19, 0), ( "H1", 0, 16, 0), ( "H2", 0, 18, 0), ( "H3", 0, 14, 1), ( "H4", 0, 13, 1), ( "H5", 0, 16, 1), ( "H6", 0, 17, 1), ("H11", 33, 14, 1), ("H12", 33, 16, 1), ("H13", 33, 15, 1), ("H14", 33, 15, 0), ( "J1", 0, 13, 0), ( "J2", 0, 12, 0), ( "J3", 0, 14, 0), ( "J4", 0, 11, 1), ( "J5", 0, 12, 1), ("J10", 33, 5, 1), ("J11", 33, 10, 1), ("J12", 33, 6, 1), ("J13", 33, 11, 0), ("J14", 33, 14, 0), ("J15", 33, 13, 0), ( "K1", 0, 11, 0), ( "K3", 0, 9, 1), ( "K4", 0, 4, 0), ( "K5", 0, 6, 1), ( "K9", 20, 0, 1), ("K11", 29, 0, 0), ("K12", 33, 4, 1), ("K13", 33, 5, 0), ("K14", 33, 12, 0), ("K15", 33, 9, 0), ( "L1", 0, 9, 0), ( "L3", 0, 7, 1), ( "L4", 0, 3, 0), ( "L5", 4, 0, 0), ( "L6", 7, 0, 0), ( "L7", 12, 0, 0), ( "L9", 17, 0, 0), ("L10", 21, 0, 1), ("L11", 30, 0, 1), ("L12", 33, 3, 1), ("L13", 33, 6, 0), ("L14", 33, 7, 0), ( "M1", 0, 7, 0), ( "M2", 0, 6, 0), ( "M3", 0, 5, 0), ( "M4", 0, 3, 1), ( "M5", 6, 0, 0), ( "M6", 8, 0, 0), ( "M7", 13, 0, 1), ( "M8", 15, 0, 0), ( "M9", 19, 0, 1), ("M11", 30, 0, 0), ("M12", 31, 0, 1), ("M13", 33, 4, 0), ("M14", 33, 8, 0), ("M15", 33, 3, 0), ( "N2", 0, 5, 1), ( "N3", 2, 0, 0), ( "N4", 3, 0, 0), ( "N5", 9, 0, 1), ( "N6", 12, 0, 1), ( "N7", 16, 0, 1), ( "N9", 20, 0, 0), ("N10", 22, 0, 1), ("N12", 31, 0, 0), ( "P1", 0, 4, 1), ( "P2", 2, 0, 1), ( "P4", 7, 0, 1), ( "P5", 10, 0, 1), ( "P6", 14, 0, 1), ( "P7", 17, 0, 1), ( "P8", 19, 0, 0), ( "P9", 22, 0, 0), ("P10", 23, 0, 0), ("P11", 25, 0, 0), ("P12", 29, 0, 1), ("P13", 27, 0, 0), ("P14", 33, 2, 1), ("P15", 33, 1, 1), ( "R1", 3, 0, 1), ( "R2", 4, 0, 1), ( "R3", 6, 0, 1), ( "R4", 8, 0, 1), ( "R5", 11, 0, 1), ( "R6", 15, 0, 1), ( "R9", 21, 0, 0), ("R10", 24, 0, 0), ("R11", 26, 0, 0), ("R12", 28, 0, 0), ("R14", 33, 2, 0), ("R15", 33, 1, 0), ], "8k-cb132": [ ( "A1", 2, 33, 0), ( "A2", 3, 33, 0), ( "A3", 3, 33, 1), ( "A4", 5, 33, 0), ( "A5", 10, 33, 1), ( "A6", 16, 33, 1), ( "A7", 17, 33, 0), ("A10", 25, 33, 0), ("A11", 26, 33, 0), ("A12", 30, 33, 1), ( "B1", 0, 30, 1), ("B14", 33, 28, 0), ( "C1", 0, 30, 0), ( "C3", 0, 27, 1), ( "C4", 4, 33, 0), ( "C5", 8, 33, 1), ( "C6", 11, 33, 1), ( "C7", 14, 33, 1), ( "C9", 20, 33, 1), ("C10", 22, 33, 1), ("C11", 28, 33, 1), ("C12", 29, 33, 1), ("C14", 33, 24, 1), ( "D1", 0, 25, 1), ( "D3", 0, 27, 0), ( "D4", 0, 22, 1), ( "D5", 9, 33, 0), ( "D6", 11, 33, 0), ( "D7", 13, 33, 1), ( "D9", 21, 33, 1), ("D10", 27, 33, 0), ("D11", 26, 33, 1), ("D12", 33, 27, 1), ("D14", 33, 23, 1), ( "E1", 0, 25, 0), ( "E4", 0, 22, 0), ("E11", 33, 20, 1), ("E12", 33, 21, 0), ("E14", 33, 21, 1), ( "F3", 0, 21, 0), ( "F4", 0, 21, 1), ("F11", 33, 19, 1), ("F12", 33, 15, 0), ("F14", 33, 16, 1), ( "G1", 0, 17, 0), ( "G3", 0, 17, 1), ( "G4", 0, 20, 0), ("G11", 33, 14, 1), ("G12", 33, 11, 0), ("G14", 33, 17, 0), ( "H1", 0, 16, 1), ( "H3", 0, 16, 0), ( "H4", 0, 20, 1), ("H11", 33, 10, 1), ("H12", 33, 6, 1), ( "J1", 0, 18, 0), ( "J3", 0, 18, 1), ("J11", 33, 6, 0), ("J12", 33, 5, 1), ( "K3", 0, 11, 1), ( "K4", 0, 11, 0), ("K11", 33, 4, 1), ("K12", 33, 4, 0), ("K14", 33, 5, 0), ( "L1", 0, 6, 1), ( "L4", 12, 0, 0), ( "L5", 11, 0, 1), ( "L6", 15, 0, 0), ( "L8", 20, 0, 1), ( "L9", 29, 0, 0), ("L12", 33, 2, 0), ("L14", 33, 3, 1), ( "M1", 0, 6, 0), ( "M3", 8, 0, 0), ( "M4", 7, 0, 1), ( "M6", 14, 0, 1), ( "M7", 15, 0, 1), ( "M9", 22, 0, 1), ("M11", 30, 0, 0), ("M12", 33, 1, 0), ( "N1", 0, 4, 1), ("N14", 33, 2, 1), ( "P1", 0, 4, 0), ( "P2", 4, 0, 0), ( "P3", 5, 0, 1), ( "P4", 12, 0, 1), ( "P5", 13, 0, 0), ( "P7", 16, 0, 1), ( "P8", 17, 0, 0), ( "P9", 21, 0, 1), ("P10", 29, 0, 1), ("P11", 30, 0, 1), ("P12", 31, 0, 0), ("P13", 31, 0, 1), ("P14", 33, 1, 1), ], "8k-ct256": [ ( "A1", 4, 33, 1), ( "A2", 5, 33, 1), ( "A5", 8, 33, 0), ( "A6", 9, 33, 0), ( "A7", 12, 33, 0), ( "A9", 18, 33, 1), ("A10", 22, 33, 1), ("A11", 22, 33, 0), ("A15", 27, 33, 0), ("A16", 27, 33, 1), ( "B1", 0, 30, 0), ( "B2", 0, 31, 0), ( "B3", 3, 33, 0), ( "B4", 6, 33, 1), ( "B5", 7, 33, 1), ( "B6", 10, 33, 1), ( "B7", 11, 33, 0), ( "B8", 13, 33, 0), ( "B9", 16, 33, 0), ("B10", 24, 33, 0), ("B11", 23, 33, 1), ("B12", 24, 33, 1), ("B13", 26, 33, 1), ("B14", 30, 33, 0), ("B15", 31, 33, 0), ("B16", 33, 30, 0), ( "C1", 0, 28, 1), ( "C2", 0, 28, 0), ( "C3", 1, 33, 0), ( "C4", 3, 33, 1), ( "C5", 4, 33, 0), ( "C6", 10, 33, 0), ( "C7", 11, 33, 1), ( "C8", 17, 33, 0), ( "C9", 20, 33, 0), ("C10", 23, 33, 0), ("C11", 25, 33, 1), ("C12", 29, 33, 1), ("C13", 28, 33, 1), ("C14", 31, 33, 1), ("C16", 33, 28, 0), ( "D1", 0, 25, 0), ( "D2", 0, 27, 0), ( "D3", 1, 33, 1), ( "D4", 2, 33, 1), ( "D5", 5, 33, 0), ( "D6", 8, 33, 1), ( "D7", 9, 33, 1), ( "D8", 14, 33, 1), ( "D9", 19, 33, 0), ("D10", 20, 33, 1), ("D11", 25, 33, 0), ("D13", 30, 33, 1), ("D14", 33, 31, 0), ("D15", 33, 26, 0), ("D16", 33, 24, 0), ( "E2", 0, 23, 0), ( "E3", 0, 24, 0), ( "E4", 0, 31, 1), ( "E5", 2, 33, 0), ( "E6", 7, 33, 0), ( "E9", 19, 33, 1), ("E10", 26, 33, 0), ("E11", 29, 33, 0), ("E13", 33, 30, 1), ("E14", 33, 27, 1), ("E16", 33, 23, 0), ( "F1", 0, 20, 0), ( "F2", 0, 21, 0), ( "F3", 0, 22, 0), ( "F4", 0, 27, 1), ( "F5", 0, 30, 1), ( "F7", 16, 33, 1), ( "F9", 17, 33, 1), ("F11", 33, 26, 1), ("F12", 33, 25, 1), ("F13", 33, 28, 1), ("F14", 33, 25, 0), ("F15", 33, 22, 0), ("F16", 33, 21, 0), ( "G1", 0, 17, 0), ( "G2", 0, 19, 0), ( "G3", 0, 22, 1), ( "G4", 0, 24, 1), ( "G5", 0, 25, 1), ("G10", 33, 20, 1), ("G11", 33, 21, 1), ("G12", 33, 24, 1), ("G13", 33, 23, 1), ("G14", 33, 22, 1), ("G15", 33, 20, 0), ("G16", 33, 19, 0), ( "H1", 0, 16, 0), ( "H2", 0, 18, 0), ( "H3", 0, 21, 1), ( "H4", 0, 19, 1), ( "H5", 0, 23, 1), ( "H6", 0, 20, 1), ("H11", 33, 16, 1), ("H12", 33, 19, 1), ("H13", 33, 16, 0), ("H14", 33, 17, 1), ("H16", 33, 17, 0), ( "J1", 0, 14, 0), ( "J2", 0, 14, 1), ( "J3", 0, 16, 1), ( "J4", 0, 18, 1), ( "J5", 0, 17, 1), ("J10", 33, 7, 1), ("J11", 33, 9, 1), ("J12", 33, 14, 1), ("J13", 33, 15, 0), ("J14", 33, 13, 1), ("J15", 33, 11, 1), ("J16", 33, 15, 1), ( "K1", 0, 13, 1), ( "K3", 0, 13, 0), ( "K4", 0, 11, 1), ( "K5", 0, 9, 1), ( "K9", 17, 0, 0), ("K11", 29, 0, 0), ("K12", 33, 6, 1), ("K13", 33, 10, 1), ("K14", 33, 11, 0), ("K15", 33, 12, 0), ("K16", 33, 13, 0), ( "L1", 0, 12, 0), ( "L3", 0, 10, 0), ( "L4", 0, 12, 1), ( "L5", 0, 6, 1), ( "L6", 0, 10, 1), ( "L7", 0, 8, 1), ( "L9", 13, 0, 0), ("L10", 19, 0, 1), ("L11", 26, 0, 1), ("L12", 33, 4, 1), ("L13", 33, 5, 1), ("L14", 33, 6, 0), ("L16", 33, 10, 0), ( "M1", 0, 11, 0), ( "M2", 0, 9, 0), ( "M3", 0, 7, 0), ( "M4", 0, 5, 0), ( "M5", 0, 4, 0), ( "M6", 0, 7, 1), ( "M7", 8, 0, 0), ( "M8", 10, 0, 0), ( "M9", 16, 0, 0), ("M11", 23, 0, 1), ("M12", 27, 0, 1), ("M13", 33, 3, 1), ("M14", 33, 4, 0), ("M15", 33, 8, 0), ("M16", 33, 7, 0), ( "N2", 0, 8, 0), ( "N3", 0, 6, 0), ( "N4", 0, 3, 0), ( "N5", 4, 0, 0), ( "N6", 2, 0, 0), ( "N7", 9, 0, 0), ( "N9", 15, 0, 0), ("N10", 20, 0, 1), ("N12", 26, 0, 0), ("N16", 33, 5, 0), ( "P1", 0, 5, 1), ( "P2", 0, 4, 1), ( "P4", 3, 0, 0), ( "P5", 5, 0, 0), ( "P6", 9, 0, 1), ( "P7", 14, 0, 1), ( "P8", 12, 0, 0), ( "P9", 17, 0, 1), ("P10", 20, 0, 0), ("P11", 30, 0, 1), ("P12", 30, 0, 0), ("P13", 29, 0, 1), ("P14", 33, 2, 0), ("P15", 33, 2, 1), ("P16", 33, 3, 0), ( "R1", 0, 3, 1), ( "R2", 3, 0, 1), ( "R3", 5, 0, 1), ( "R4", 7, 0, 1), ( "R5", 6, 0, 0), ( "R6", 11, 0, 1), ( "R9", 16, 0, 1), ("R10", 19, 0, 0), ("R11", 31, 0, 0), ("R12", 31, 0, 1), ("R14", 33, 1, 0), ("R15", 33, 1, 1), ("R16", 28, 0, 0), ( "T1", 2, 0, 1), ( "T2", 4, 0, 1), ( "T3", 6, 0, 1), ( "T5", 10, 0, 1), ( "T6", 12, 0, 1), ( "T7", 13, 0, 1), ( "T8", 14, 0, 0), ( "T9", 15, 0, 1), ("T10", 21, 0, 0), ("T11", 21, 0, 1), ("T13", 24, 0, 0), ("T14", 23, 0, 0), ("T15", 22, 0, 1), ("T16", 27, 0, 0), ], "384-qn32": [ ( "1", 0, 7, 0), ( "2", 0, 7, 1), ( "5", 0, 5, 1), ( "6", 0, 5, 0), ( "7", 0, 4, 0), ( "8", 0, 4, 1), ( "12", 5, 0, 0), ( "13", 5, 0, 1), ( "14", 6, 0, 1), ( "15", 6, 0, 0), ( "18", 7, 4, 0), ( "19", 7, 4, 1), ( "20", 7, 5, 0), ( "22", 7, 6, 0), ( "23", 7, 6, 1), ( "26", 6, 9, 0), ( "27", 5, 9, 0), ( "29", 4, 9, 0), ( "30", 3, 9, 1), ( "31", 2, 9, 0), ( "32", 2, 9, 1), ], "384-cm36": [ ( "A1", 0, 7, 0), ( "A2", 2, 9, 1), ( "A3", 3, 9, 1), ( "B1", 0, 7, 1), ( "B3", 4, 9, 0), ( "B4", 7, 5, 0), ( "B5", 7, 5, 1), ( "B6", 7, 6, 0), ( "C1", 0, 5, 0), ( "C2", 0, 5, 1), ( "C3", 2, 9, 0), ( "C5", 7, 4, 1), ( "C6", 7, 6, 1), ( "D1", 0, 4, 1), ( "D5", 6, 0, 1), ( "D6", 7, 4, 0), ( "E1", 0, 4, 0), ( "E2", 3, 0, 1), ( "E3", 4, 0, 0), ( "E4", 5, 0, 0), ( "E5", 6, 0, 0), ( "E6", 7, 3, 1), ( "F2", 3, 0, 0), ( "F3", 4, 0, 1), ( "F5", 5, 0, 1), ], "384-cm49": [ ( "A1", 0, 7, 1), ( "A2", 2, 9, 1), ( "A3", 3, 9, 0), ( "A4", 4, 9, 1), ( "A5", 5, 9, 0), ( "A6", 6, 9, 0), ( "A7", 6, 9, 1), ( "B1", 0, 7, 0), ( "B2", 0, 6, 0), ( "B3", 2, 9, 0), ( "B4", 4, 9, 0), ( "C1", 0, 5, 1), ( "C2", 0, 6, 1), ( "C4", 3, 9, 1), ( "C5", 7, 6, 1), ( "C6", 7, 5, 1), ( "C7", 7, 6, 0), ( "D1", 0, 4, 0), ( "D2", 0, 5, 0), ( "D3", 0, 2, 0), ( "D4", 5, 9, 1), ( "D6", 7, 4, 1), ( "D7", 7, 5, 0), ( "E2", 0, 4, 1), ( "E6", 6, 0, 1), ( "E7", 7, 4, 0), ( "F1", 0, 2, 1), ( "F2", 0, 1, 0), ( "F3", 3, 0, 1), ( "F4", 4, 0, 0), ( "F5", 5, 0, 0), ( "F6", 6, 0, 0), ( "F7", 7, 3, 1), ( "G1", 0, 1, 1), ( "G3", 3, 0, 0), ( "G4", 4, 0, 1), ( "G6", 5, 0, 1), ], "5k-sg48": [ ( "2", 8, 0, 0), ( "3", 9, 0, 1), ( "4", 9, 0, 0), ( "6", 13, 0, 1), ( "9", 15, 0, 0), ( "10", 16, 0, 0), ( "11", 17, 0, 0), ( "12", 18, 0, 0), ( "13", 19, 0, 0), ( "14", 23, 0, 0), ( "15", 24, 0, 0), ( "16", 24, 0, 1), ( "17", 23, 0, 1), ( "18", 22, 0, 1), ( "19", 21, 0, 1), ( "20", 19, 0, 1), ( "21", 18, 0, 1), ( "23", 19, 31, 0), ( "25", 19, 31, 1), ( "26", 18, 31, 0), ( "27", 18, 31, 1), ( "28", 17, 31, 0), ( "31", 16, 31, 1), ( "32", 16, 31, 0), ( "34", 13, 31, 1), ( "35", 12, 31, 1), ( "36", 9, 31, 1), ( "37", 13, 31, 0), ( "38", 8, 31, 1), ( "39", 4, 31, 0), ( "40", 5, 31, 0), ( "41", 6, 31, 0), ( "42", 8, 31, 0), ( "43", 9, 31, 0), ( "44", 6, 0, 1), ( "45", 7, 0, 1), ( "46", 5, 0, 0), ( "47", 6, 0, 0), ( "48", 7, 0, 0), ], } iotile_full_db = parse_db(iceboxdb.database_io_txt) logictile_db = parse_db(iceboxdb.database_logic_txt, "1k") logictile_5k_db = parse_db(iceboxdb.database_logic_txt, "5k") logictile_8k_db = parse_db(iceboxdb.database_logic_txt, "8k") logictile_384_db = parse_db(iceboxdb.database_logic_txt, "384") rambtile_db = parse_db(iceboxdb.database_ramb_txt, "1k") ramttile_db = parse_db(iceboxdb.database_ramt_txt, "1k") rambtile_5k_db = parse_db(iceboxdb.database_ramb_5k_txt, "5k") ramttile_5k_db = parse_db(iceboxdb.database_ramt_5k_txt, "5k") rambtile_8k_db = parse_db(iceboxdb.database_ramb_8k_txt, "8k") ramttile_8k_db = parse_db(iceboxdb.database_ramt_8k_txt, "8k") iotile_l_db = list() iotile_r_db = list() iotile_t_db = list() iotile_b_db = list() for entry in iotile_full_db: if entry[1] == "buffer" and entry[2].startswith("IO_L."): new_entry = entry[:] new_entry[2] = new_entry[2][5:] iotile_l_db.append(new_entry) elif entry[1] == "buffer" and entry[2].startswith("IO_R."): new_entry = entry[:] new_entry[2] = new_entry[2][5:] iotile_r_db.append(new_entry) elif entry[1] == "buffer" and entry[2].startswith("IO_T."): new_entry = entry[:] new_entry[2] = new_entry[2][5:] iotile_t_db.append(new_entry) elif entry[1] == "buffer" and entry[2].startswith("IO_B."): new_entry = entry[:] new_entry[2] = new_entry[2][5:] iotile_b_db.append(new_entry) else: iotile_l_db.append(entry) iotile_r_db.append(entry) iotile_t_db.append(entry) iotile_b_db.append(entry) logictile_db.append([["B1[49]"], "buffer", "carry_in", "carry_in_mux"]) logictile_db.append([["B1[50]"], "CarryInSet"]) logictile_8k_db.append([["B1[49]"], "buffer", "carry_in", "carry_in_mux"]) logictile_8k_db.append([["B1[50]"], "CarryInSet"]) logictile_384_db.append([["B1[49]"], "buffer", "carry_in", "carry_in_mux"]) logictile_384_db.append([["B1[50]"], "CarryInSet"]) for db in [iotile_l_db, iotile_r_db, iotile_t_db, iotile_b_db, logictile_db, logictile_5k_db, logictile_8k_db, logictile_384_db, rambtile_db, ramttile_db, rambtile_5k_db, ramttile_5k_db, rambtile_8k_db, ramttile_8k_db]: for entry in db: if entry[1] in ("buffer", "routing"): entry[2] = netname_normalize(entry[2], ramb=(db == rambtile_db), ramt=(db == ramttile_db), ramb_8k=(db in (rambtile_8k_db, rambtile_5k_db)), ramt_8k=(db in (ramttile_8k_db, ramttile_5k_db))) entry[3] = netname_normalize(entry[3], ramb=(db == rambtile_db), ramt=(db == ramttile_db), ramb_8k=(db in (rambtile_8k_db, rambtile_5k_db)), ramt_8k=(db in (ramttile_8k_db, ramttile_5k_db))) unique_entries = dict() while db: entry = db.pop() key = " ".join(entry[1:]) + str(entry) unique_entries[key] = entry for key in sorted(unique_entries): db.append(unique_entries[key]) if __name__ == "__main__": run_checks() Fix icebox to generate a working chipdb #!/usr/bin/env python3 # # Copyright (C) 2015 Clifford Wolf <clifford@clifford.at> # # 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. # import iceboxdb import re, sys class iceconfig: def __init__(self): self.clear() def clear(self): self.max_x = 0 self.max_y = 0 self.device = "" self.warmboot = True self.logic_tiles = dict() self.io_tiles = dict() self.ramb_tiles = dict() self.ramt_tiles = dict() self.ram_data = dict() self.extra_bits = set() self.symbols = dict() def setup_empty_384(self): self.clear() self.device = "384" self.max_x = 7 self.max_y = 9 for x in range(1, self.max_x): for y in range(1, self.max_y): self.logic_tiles[(x, y)] = ["0" * 54 for i in range(16)] for x in range(1, self.max_x): self.io_tiles[(x, 0)] = ["0" * 18 for i in range(16)] self.io_tiles[(x, self.max_y)] = ["0" * 18 for i in range(16)] for y in range(1, self.max_y): self.io_tiles[(0, y)] = ["0" * 18 for i in range(16)] self.io_tiles[(self.max_x, y)] = ["0" * 18 for i in range(16)] def setup_empty_1k(self): self.clear() self.device = "1k" self.max_x = 13 self.max_y = 17 for x in range(1, self.max_x): for y in range(1, self.max_y): if x in (3, 10): if y % 2 == 1: self.ramb_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.ramt_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.logic_tiles[(x, y)] = ["0" * 54 for i in range(16)] for x in range(1, self.max_x): self.io_tiles[(x, 0)] = ["0" * 18 for i in range(16)] self.io_tiles[(x, self.max_y)] = ["0" * 18 for i in range(16)] for y in range(1, self.max_y): self.io_tiles[(0, y)] = ["0" * 18 for i in range(16)] self.io_tiles[(self.max_x, y)] = ["0" * 18 for i in range(16)] def setup_empty_5k(self): self.clear() self.device = "5k" self.max_x = 25 self.max_y = 31 for x in range(1, self.max_x): for y in range(1, self.max_y): if x in (7, 20): if y % 2 == 1: self.ramb_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.ramt_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.logic_tiles[(x, y)] = ["0" * 54 for i in range(16)] for x in range(1, self.max_x): self.io_tiles[(x, 0)] = ["0" * 18 for i in range(16)] self.io_tiles[(x, self.max_y)] = ["0" * 18 for i in range(16)] def setup_empty_8k(self): self.clear() self.device = "8k" self.max_x = 33 self.max_y = 33 for x in range(1, self.max_x): for y in range(1, self.max_y): if x in (8, 25): if y % 2 == 1: self.ramb_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.ramt_tiles[(x, y)] = ["0" * 42 for i in range(16)] else: self.logic_tiles[(x, y)] = ["0" * 54 for i in range(16)] for x in range(1, self.max_x): self.io_tiles[(x, 0)] = ["0" * 18 for i in range(16)] self.io_tiles[(x, self.max_y)] = ["0" * 18 for i in range(16)] for y in range(1, self.max_y): self.io_tiles[(0, y)] = ["0" * 18 for i in range(16)] self.io_tiles[(self.max_x, y)] = ["0" * 18 for i in range(16)] def lookup_extra_bit(self, bit): assert self.device in extra_bits_db if bit in extra_bits_db[self.device]: return extra_bits_db[self.device][bit] return ("UNKNOWN_FUNCTION",) def tile(self, x, y): if (x, y) in self.io_tiles: return self.io_tiles[(x, y)] if (x, y) in self.logic_tiles: return self.logic_tiles[(x, y)] if (x, y) in self.ramb_tiles: return self.ramb_tiles[(x, y)] if (x, y) in self.ramt_tiles: return self.ramt_tiles[(x, y)] return None def pinloc_db(self): if self.device == "384": return pinloc_db["384-qn32"] if self.device == "1k": return pinloc_db["1k-tq144"] if self.device == "5k": return pinloc_db["5k-sg48"] if self.device == "8k": return pinloc_db["8k-ct256"] assert False def gbufin_db(self): return gbufin_db[self.device] def iolatch_db(self): return iolatch_db[self.device] def padin_pio_db(self): return padin_pio_db[self.device] def extra_bits_db(self): return extra_bits_db[self.device] def ieren_db(self): return ieren_db[self.device] def pll_list(self): if self.device == "1k": return ["1k"] if self.device == "5k": #FIXME: PLL removed as it was causing problems in arachne, likely due to broken pin config for it return [ ] if self.device == "8k": return ["8k_0", "8k_1"] if self.device == "384": return [ ] assert False def colbuf_db(self): if self.device == "1k": entries = list() for x in range(self.max_x+1): for y in range(self.max_y+1): src_y = None if 0 <= y <= 4: src_y = 4 if 5 <= y <= 8: src_y = 5 if 9 <= y <= 12: src_y = 12 if 13 <= y <= 17: src_y = 13 if x in [3, 10] and src_y == 4: src_y = 3 if x in [3, 10] and src_y == 12: src_y = 11 entries.append((x, src_y, x, y)) return entries if self.device == "8k": entries = list() for x in range(self.max_x+1): for y in range(self.max_y+1): src_y = None if 0 <= y <= 8: src_y = 8 if 9 <= y <= 16: src_y = 9 if 17 <= y <= 24: src_y = 24 if 25 <= y <= 33: src_y = 25 entries.append((x, src_y, x, y)) return entries if self.device == "5k": #Assume same as 8k because same height, is this valid??? entries = list() for x in range(self.max_x+1): for y in range(self.max_y+1): src_y = None if 0 <= y <= 8: src_y = 8 if 9 <= y <= 16: src_y = 9 if 17 <= y <= 24: src_y = 24 if 25 <= y <= 33: src_y = 25 entries.append((x, src_y, x, y)) return entries if self.device == "384": entries = list() for x in range(self.max_x+1): for y in range(self.max_y+1): src_y = None #Is ColBufCtrl relevant? if 0 <= y <= 2: src_y = 2 #384? if 3 <= y <= 4: src_y = 3 #384? if 5 <= y <= 6: src_y = 6 #384? if 7 <= y <= 9: src_y = 7 #384? entries.append((x, src_y, x, y)) return entries assert False def tile_db(self, x, y): # Only these devices have IO on the left and right sides. if self.device in ["384", "1k", "8k"]: if x == 0: return iotile_l_db if x == self.max_x: return iotile_r_db if y == 0: return iotile_b_db if y == self.max_y: return iotile_t_db if self.device == "1k": if (x, y) in self.logic_tiles: return logictile_db if (x, y) in self.ramb_tiles: return rambtile_db if (x, y) in self.ramt_tiles: return ramttile_db elif self.device == "5k": if (x, y) in self.logic_tiles: return logictile_5k_db if (x, y) in self.ramb_tiles: return rambtile_5k_db if (x, y) in self.ramt_tiles: return ramttile_5k_db elif self.device == "8k": if (x, y) in self.logic_tiles: return logictile_8k_db if (x, y) in self.ramb_tiles: return rambtile_8k_db if (x, y) in self.ramt_tiles: return ramttile_8k_db elif self.device == "384": if (x, y) in self.logic_tiles: return logictile_384_db print("Tile type unknown at (%d, %d)" % (x, y)) assert False def tile_type(self, x, y): if x == 0: return "IO" if y == 0: return "IO" if x == self.max_x: return "IO" if y == self.max_y: return "IO" if (x, y) in self.ramb_tiles: return "RAMB" if (x, y) in self.ramt_tiles: return "RAMT" if (x, y) in self.logic_tiles: return "LOGIC" assert False def tile_pos(self, x, y): if x == 0 and 0 < y < self.max_y: return "l" if y == 0 and 0 < x < self.max_x: return "b" if x == self.max_x and 0 < y < self.max_y: return "r" if y == self.max_y and 0 < x < self.max_x: return "t" if 0 < x < self.max_x and 0 < y < self.max_y: return "x" return None def tile_has_entry(self, x, y, entry): if entry[1] in ("routing", "buffer"): return self.tile_has_net(x, y, entry[2]) and self.tile_has_net(x, y, entry[3]) return True def tile_has_net(self, x, y, netname): if netname.startswith("logic_op_"): if netname.startswith("logic_op_bot_"): if y == self.max_y and 0 < x < self.max_x: return True if netname.startswith("logic_op_bnl_"): if x == self.max_x and 1 < y < self.max_y: return True if y == self.max_y and 1 < x < self.max_x: return True if netname.startswith("logic_op_bnr_"): if x == 0 and 1 < y < self.max_y: return True if y == self.max_y and 0 < x < self.max_x-1: return True if netname.startswith("logic_op_top_"): if y == 0 and 0 < x < self.max_x: return True if netname.startswith("logic_op_tnl_"): if x == self.max_x and 0 < y < self.max_y-1: return True if y == 0 and 1 < x < self.max_x: return True if netname.startswith("logic_op_tnr_"): if x == 0 and 0 < y < self.max_y-1: return True if y == 0 and 0 < x < self.max_x-1: return True if netname.startswith("logic_op_lft_"): if x == self.max_x: return True if netname.startswith("logic_op_rgt_"): if x == 0: return True return False if not 0 <= x <= self.max_x: return False if not 0 <= y <= self.max_y: return False return pos_has_net(self.tile_pos(x, y), netname) def tile_follow_net(self, x, y, direction, netname): if x == 1 and y not in (0, self.max_y) and direction == 'l': return pos_follow_net("x", "L", netname) if y == 1 and x not in (0, self.max_x) and direction == 'b': return pos_follow_net("x", "B", netname) if x == self.max_x-1 and y not in (0, self.max_y) and direction == 'r': return pos_follow_net("x", "R", netname) if y == self.max_y-1 and x not in (0, self.max_x) and direction == 't': return pos_follow_net("x", "T", netname) return pos_follow_net(self.tile_pos(x, y), direction, netname) def follow_funcnet(self, x, y, func): neighbours = set() def do_direction(name, nx, ny): if 0 < nx < self.max_x and 0 < ny < self.max_y: neighbours.add((nx, ny, "neigh_op_%s_%d" % (name, func))) if nx in (0, self.max_x) and 0 < ny < self.max_y and nx != x: neighbours.add((nx, ny, "logic_op_%s_%d" % (name, func))) if ny in (0, self.max_y) and 0 < nx < self.max_x and ny != y: neighbours.add((nx, ny, "logic_op_%s_%d" % (name, func))) do_direction("bot", x, y+1) do_direction("bnl", x+1, y+1) do_direction("bnr", x-1, y+1) do_direction("top", x, y-1) do_direction("tnl", x+1, y-1) do_direction("tnr", x-1, y-1) do_direction("lft", x+1, y ) do_direction("rgt", x-1, y ) return neighbours def lookup_funcnet(self, nx, ny, x, y, func): npos = self.tile_pos(nx, ny) pos = self.tile_pos(x, y) if npos is not None and pos is not None: if npos == "x": if (nx, ny) in self.logic_tiles: return (nx, ny, "lutff_%d/out" % func) if (nx, ny) in self.ramb_tiles: if self.device == "1k": return (nx, ny, "ram/RDATA_%d" % func) elif self.device == "5k": return (nx, ny, "ram/RDATA_%d" % (15-func)) elif self.device == "8k": return (nx, ny, "ram/RDATA_%d" % (15-func)) else: assert False if (nx, ny) in self.ramt_tiles: if self.device == "1k": return (nx, ny, "ram/RDATA_%d" % (8+func)) elif self.device == "5k": return (nx, ny, "ram/RDATA_%d" % (7-func)) elif self.device == "8k": return (nx, ny, "ram/RDATA_%d" % (7-func)) else: assert False elif pos == "x" and npos in ("l", "r", "t", "b"): if func in (0, 4): return (nx, ny, "io_0/D_IN_0") if func in (1, 5): return (nx, ny, "io_0/D_IN_1") if func in (2, 6): return (nx, ny, "io_1/D_IN_0") if func in (3, 7): return (nx, ny, "io_1/D_IN_1") return None def rlookup_funcnet(self, x, y, netname): funcnets = set() if netname == "io_0/D_IN_0": for net in self.follow_funcnet(x, y, 0) | self.follow_funcnet(x, y, 4): if self.tile_pos(net[0], net[1]) == "x": funcnets.add(net) if netname == "io_0/D_IN_1": for net in self.follow_funcnet(x, y, 1) | self.follow_funcnet(x, y, 5): if self.tile_pos(net[0], net[1]) == "x": funcnets.add(net) if netname == "io_1/D_IN_0": for net in self.follow_funcnet(x, y, 2) | self.follow_funcnet(x, y, 6): if self.tile_pos(net[0], net[1]) == "x": funcnets.add(net) if netname == "io_1/D_IN_1": for net in self.follow_funcnet(x, y, 3) | self.follow_funcnet(x, y, 7): if self.tile_pos(net[0], net[1]) == "x": funcnets.add(net) match = re.match(r"lutff_(\d+)/out", netname) if match: funcnets |= self.follow_funcnet(x, y, int(match.group(1))) match = re.match(r"ram/RDATA_(\d+)", netname) if match: if self.device == "1k": funcnets |= self.follow_funcnet(x, y, int(match.group(1)) % 8) elif self.device == "5k": funcnets |= self.follow_funcnet(x, y, 7 - int(match.group(1)) % 8) elif self.device == "8k": funcnets |= self.follow_funcnet(x, y, 7 - int(match.group(1)) % 8) else: assert False return funcnets def follow_net(self, netspec): x, y, netname = netspec neighbours = self.rlookup_funcnet(x, y, netname) #print(netspec) #print('\t', neighbours) if netname == "carry_in" and y > 1: neighbours.add((x, y-1, "lutff_7/cout")) if netname == "lutff_7/cout" and y+1 < self.max_y: neighbours.add((x, y+1, "carry_in")) if netname.startswith("glb_netwk_"): for nx in range(self.max_x+1): for ny in range(self.max_y+1): if self.tile_pos(nx, ny) is not None: neighbours.add((nx, ny, netname)) match = re.match(r"sp4_r_v_b_(\d+)", netname) if match and 0 < x < self.max_x-1: neighbours.add((x+1, y, sp4v_normalize("sp4_v_b_" + match.group(1)))) #print('\tafter r_v_b', neighbours) match = re.match(r"sp4_v_[bt]_(\d+)", netname) if match and 1 < x < self.max_x: n = sp4v_normalize(netname, "b") if n is not None: n = n.replace("sp4_", "sp4_r_") neighbours.add((x-1, y, n)) #print('\tafter v_[bt]', neighbours) match = re.match(r"(logic|neigh)_op_(...)_(\d+)", netname) if match: if match.group(2) == "bot": nx, ny = (x, y-1) if match.group(2) == "bnl": nx, ny = (x-1, y-1) if match.group(2) == "bnr": nx, ny = (x+1, y-1) if match.group(2) == "top": nx, ny = (x, y+1) if match.group(2) == "tnl": nx, ny = (x-1, y+1) if match.group(2) == "tnr": nx, ny = (x+1, y+1) if match.group(2) == "lft": nx, ny = (x-1, y ) if match.group(2) == "rgt": nx, ny = (x+1, y ) n = self.lookup_funcnet(nx, ny, x, y, int(match.group(3))) if n is not None: neighbours.add(n) for direction in ["l", "r", "t", "b"]: n = self.tile_follow_net(x, y, direction, netname) if n is not None: if direction == "l": s = (x-1, y, n) if direction == "r": s = (x+1, y, n) if direction == "t": s = (x, y+1, n) if direction == "b": s = (x, y-1, n) if s[0] in (0, self.max_x) and s[1] in (0, self.max_y): if re.match("span4_(vert|horz)_[lrtb]_\d+$", n): vert_net = n.replace("_l_", "_t_").replace("_r_", "_b_").replace("_horz_", "_vert_") horz_net = n.replace("_t_", "_l_").replace("_b_", "_r_").replace("_vert_", "_horz_") if s[0] == 0 and s[1] == 0: if direction == "l": s = (0, 1, vert_net) if direction == "b": s = (1, 0, horz_net) if s[0] == self.max_x and s[1] == self.max_y: if direction == "r": s = (self.max_x, self.max_y-1, vert_net) if direction == "t": s = (self.max_x-1, self.max_y, horz_net) vert_net = netname.replace("_l_", "_t_").replace("_r_", "_b_").replace("_horz_", "_vert_") horz_net = netname.replace("_t_", "_l_").replace("_b_", "_r_").replace("_vert_", "_horz_") if s[0] == 0 and s[1] == self.max_y: if direction == "l": s = (0, self.max_y-1, vert_net) if direction == "t": s = (1, self.max_y, horz_net) if s[0] == self.max_x and s[1] == 0: if direction == "r": s = (self.max_x, 1, vert_net) if direction == "b": s = (self.max_x-1, 0, horz_net) if self.tile_has_net(s[0], s[1], s[2]): neighbours.add((s[0], s[1], s[2])) #print('\tafter directions', neighbours) return neighbours def group_segments(self, all_from_tiles=set(), extra_connections=list(), extra_segments=list(), connect_gb=True): seed_segments = set() seen_segments = set() connected_segments = dict() grouped_segments = set() for seg in extra_segments: seed_segments.add(seg) for conn in extra_connections: s1, s2 = conn connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) for idx, tile in self.io_tiles.items(): tc = tileconfig(tile) pintypes = [ list("000000"), list("000000") ] for entry in self.tile_db(idx[0], idx[1]): if entry[1].startswith("IOB_") and entry[2].startswith("PINTYPE_") and tc.match(entry[0]): pintypes[int(entry[1][-1])][int(entry[2][-1])] = "1" if "".join(pintypes[0][2:6]) != "0000": seed_segments.add((idx[0], idx[1], "io_0/D_OUT_0")) if "".join(pintypes[1][2:6]) != "0000": seed_segments.add((idx[0], idx[1], "io_1/D_OUT_0")) def add_seed_segments(idx, tile, db): tc = tileconfig(tile) for entry in db: if entry[1] in ("routing", "buffer"): config_match = tc.match(entry[0]) if idx in all_from_tiles or config_match: if not self.tile_has_net(idx[0], idx[1], entry[2]): continue if not self.tile_has_net(idx[0], idx[1], entry[3]): continue s1 = (idx[0], idx[1], entry[2]) s2 = (idx[0], idx[1], entry[3]) if config_match: connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) for idx, tile in self.io_tiles.items(): add_seed_segments(idx, tile, self.tile_db(idx[0], idx[1])) for idx, tile in self.logic_tiles.items(): if idx in all_from_tiles: seed_segments.add((idx[0], idx[1], "lutff_7/cout")) if self.device == "1k": add_seed_segments(idx, tile, logictile_db) elif self.device == "5k": add_seed_segments(idx, tile, logictile_5k_db) elif self.device == "8k": add_seed_segments(idx, tile, logictile_8k_db) elif self.device == "384": add_seed_segments(idx, tile, logictile_384_db) else: assert False for idx, tile in self.ramb_tiles.items(): if self.device == "1k": add_seed_segments(idx, tile, rambtile_db) elif self.device == "5k": add_seed_segments(idx, tile, rambtile_5k_db) elif self.device == "8k": add_seed_segments(idx, tile, rambtile_8k_db) else: assert False for idx, tile in self.ramt_tiles.items(): if self.device == "1k": add_seed_segments(idx, tile, ramttile_db) elif self.device == "5k": add_seed_segments(idx, tile, ramttile_5k_db) elif self.device == "8k": add_seed_segments(idx, tile, ramttile_8k_db) else: assert False for padin, pio in enumerate(self.padin_pio_db()): s1 = (pio[0], pio[1], "padin_%d" % pio[2]) s2 = (pio[0], pio[1], "glb_netwk_%d" % padin) if s1 in seed_segments or (pio[0], pio[1]) in all_from_tiles: connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) for entry in self.iolatch_db(): if entry[0] == 0 or entry[0] == self.max_x: iocells = [(entry[0], i) for i in range(1, self.max_y)] if entry[1] == 0 or entry[1] == self.max_y: iocells = [(i, entry[1]) for i in range(1, self.max_x)] for cell in iocells: s1 = (entry[0], entry[1], "fabout") s2 = (cell[0], cell[1], "io_global/latch") if s1 in seed_segments or s2 in seed_segments or \ (entry[0], entry[1]) in all_from_tiles or (cell[0], cell[1]) in all_from_tiles: connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) if connect_gb: for entry in self.gbufin_db(): s1 = (entry[0], entry[1], "fabout") s2 = (entry[0], entry[1], "glb_netwk_%d" % entry[2]) if s1 in seed_segments or (pio[0], pio[1]) in all_from_tiles: connected_segments.setdefault(s1, set()).add(s2) connected_segments.setdefault(s2, set()).add(s1) seed_segments.add(s1) seed_segments.add(s2) while seed_segments: queue = set() segments = set() queue.add(seed_segments.pop()) while queue: next_segment = queue.pop() expanded = self.expand_net(next_segment) for s in expanded: if s not in segments: segments.add(s) if s in seen_segments: print("//", s, "has already been seen. Check your bitmapping.") assert False seen_segments.add(s) seed_segments.discard(s) if s in connected_segments: for cs in connected_segments[s]: if not cs in segments: queue.add(cs) for s in segments: assert s not in seed_segments grouped_segments.add(tuple(sorted(segments))) return grouped_segments def expand_net(self, netspec): queue = set() segments = set() queue.add(netspec) while queue: n = queue.pop() segments.add(n) for k in self.follow_net(n): if k not in segments: queue.add(k) return segments def read_file(self, filename): self.clear() current_data = None expected_data_lines = 0 with open(filename, "r") as f: for linenum, linetext in enumerate(f): # print("DEBUG: input line %d: %s" % (linenum, linetext.strip())) line = linetext.strip().split() if len(line) == 0: assert expected_data_lines == 0 continue if line[0][0] != ".": if expected_data_lines == -1: continue if line[0][0] not in "0123456789abcdef": print("Warning: ignoring data block in line %d: %s" % (linenum, linetext.strip())) expected_data_lines = 0 continue assert expected_data_lines != 0 current_data.append(line[0]) expected_data_lines -= 1 continue assert expected_data_lines <= 0 if line[0] in (".io_tile", ".logic_tile", ".ramb_tile", ".ramt_tile", ".ram_data"): current_data = list() expected_data_lines = 16 self.max_x = max(self.max_x, int(line[1])) self.max_y = max(self.max_y, int(line[2])) if line[0] == ".io_tile": self.io_tiles[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".logic_tile": self.logic_tiles[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".ramb_tile": self.ramb_tiles[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".ramt_tile": self.ramt_tiles[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".ram_data": self.ram_data[(int(line[1]), int(line[2]))] = current_data continue if line[0] == ".extra_bit": self.extra_bits.add((int(line[1]), int(line[2]), int(line[3]))) continue if line[0] == ".device": assert line[1] in ["1k", "5k", "8k", "384"] self.device = line[1] continue if line[0] == ".warmboot": assert line[1] in ["disabled", "enabled"] self.warmboot = line[1] == "enabled" continue if line[0] == ".sym": self.symbols.setdefault(int(line[1]), set()).add(line[2]) continue if line[0] == ".comment": expected_data_lines = -1 continue print("Warning: ignoring line %d: %s" % (linenum, linetext.strip())) expected_data_lines = -1 def write_file(self, filename): with open(filename, "w") as f: print(".device %s" % self.device, file=f) if not self.warmboot: print(".warmboot disabled", file=f) for y in range(self.max_y+1): for x in range(self.max_x+1): if self.tile_pos(x, y) is not None: print(".%s_tile %d %d" % (self.tile_type(x, y).lower(), x, y), file=f) for line in self.tile(x, y): print(line, file=f) for x, y in sorted(self.ram_data): print(".ram_data %d %d" % (x, y), file=f) for line in self.ram_data[(x, y)]: print(line, file=f) for extra_bit in sorted(self.extra_bits): print(".extra_bit %d %d %d" % extra_bit, file=f) class tileconfig: def __init__(self, tile): self.bits = set() for k, line in enumerate(tile): for i in range(len(line)): if line[i] == "1": self.bits.add("B%d[%d]" % (k, i)) else: self.bits.add("!B%d[%d]" % (k, i)) def match(self, pattern): for bit in pattern: if not bit in self.bits: return False return True if False: ## Lattice span net name normalization valid_sp4_h_l = set([1, 2, 4, 5, 7, 9, 10, 11, 15, 16, 17, 21, 24, 34, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]) valid_sp4_h_r = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 19, 21, 24, 25, 27, 30, 31, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 45, 46]) valid_sp4_v_t = set([1, 3, 5, 9, 12, 14, 16, 17, 18, 21, 22, 23, 26, 28, 29, 30, 32, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]) valid_sp4_v_b = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 18, 19, 21, 22, 23, 24, 26, 30, 33, 36, 37, 38, 42, 46, 47]) valid_sp12_h_l = set([3, 4, 5, 12, 14, 16, 17, 18, 21, 22, 23]) valid_sp12_h_r = set([0, 1, 2, 3, 5, 8, 9, 10, 11, 12, 13, 14, 16, 20, 23]) valid_sp12_v_t = set([0, 1, 2, 3, 6, 9, 10, 12, 14, 21, 22, 23]) valid_sp12_v_b = set([0, 1, 6, 7, 8, 11, 12, 14, 16, 18, 19, 20, 21, 23]) else: ## IceStorm span net name normalization valid_sp4_h_l = set(range(36, 48)) valid_sp4_h_r = set(range(48)) valid_sp4_v_t = set(range(36, 48)) valid_sp4_v_b = set(range(48)) valid_sp12_h_l = set(range(22, 24)) valid_sp12_h_r = set(range(24)) valid_sp12_v_t = set(range(22, 24)) valid_sp12_v_b = set(range(24)) def sp4h_normalize(netname, edge=""): m = re.match("sp4_h_([lr])_(\d+)$", netname) assert m if not m: return None cur_edge = m.group(1) cur_index = int(m.group(2)) if cur_edge == edge: return netname if cur_edge == "r" and (edge == "l" or (edge == "" and cur_index not in valid_sp4_h_r)): if cur_index < 12: return None return "sp4_h_l_%d" % ((cur_index-12)^1) if cur_edge == "l" and (edge == "r" or (edge == "" and cur_index not in valid_sp4_h_l)): if cur_index >= 36: return None return "sp4_h_r_%d" % ((cur_index+12)^1) return netname def sp4v_normalize(netname, edge=""): m = re.match("sp4_v_([bt])_(\d+)$", netname) assert m if not m: return None cur_edge = m.group(1) cur_index = int(m.group(2)) if cur_edge == edge: return netname if cur_edge == "b" and (edge == "t" or (edge == "" and cur_index not in valid_sp4_v_b)): if cur_index < 12: return None return "sp4_v_t_%d" % ((cur_index-12)^1) if cur_edge == "t" and (edge == "b" or (edge == "" and cur_index not in valid_sp4_v_t)): if cur_index >= 36: return None return "sp4_v_b_%d" % ((cur_index+12)^1) return netname def sp12h_normalize(netname, edge=""): m = re.match("sp12_h_([lr])_(\d+)$", netname) assert m if not m: return None cur_edge = m.group(1) cur_index = int(m.group(2)) if cur_edge == edge: return netname if cur_edge == "r" and (edge == "l" or (edge == "" and cur_index not in valid_sp12_h_r)): if cur_index < 2: return None return "sp12_h_l_%d" % ((cur_index-2)^1) if cur_edge == "l" and (edge == "r" or (edge == "" and cur_index not in valid_sp12_h_l)): if cur_index >= 22: return None return "sp12_h_r_%d" % ((cur_index+2)^1) return netname def sp12v_normalize(netname, edge=""): m = re.match("sp12_v_([bt])_(\d+)$", netname) assert m if not m: return None cur_edge = m.group(1) cur_index = int(m.group(2)) if cur_edge == edge: return netname if cur_edge == "b" and (edge == "t" or (edge == "" and cur_index not in valid_sp12_v_b)): if cur_index < 2: return None return "sp12_v_t_%d" % ((cur_index-2)^1) if cur_edge == "t" and (edge == "b" or (edge == "" and cur_index not in valid_sp12_v_t)): if cur_index >= 22: return None return "sp12_v_b_%d" % ((cur_index+2)^1) return netname def netname_normalize(netname, edge="", ramb=False, ramt=False, ramb_8k=False, ramt_8k=False): if netname.startswith("sp4_v_"): return sp4v_normalize(netname, edge) if netname.startswith("sp4_h_"): return sp4h_normalize(netname, edge) if netname.startswith("sp12_v_"): return sp12v_normalize(netname, edge) if netname.startswith("sp12_h_"): return sp12h_normalize(netname, edge) if netname.startswith("input_2_"): netname = netname.replace("input_2_", "wire_logic_cluster/lc_") + "/in_2" netname = netname.replace("lc_trk_", "local_") netname = netname.replace("lc_", "lutff_") netname = netname.replace("wire_logic_cluster/", "") netname = netname.replace("wire_io_cluster/", "") netname = netname.replace("wire_bram/", "") if (ramb or ramt or ramb_8k or ramt_8k) and netname.startswith("input"): match = re.match(r"input(\d)_(\d)", netname) idx1, idx2 = (int(match.group(1)), int(match.group(2))) if ramb: netname="ram/WADDR_%d" % (idx1*4 + idx2) if ramt: netname="ram/RADDR_%d" % (idx1*4 + idx2) if ramb_8k: netname="ram/RADDR_%d" % ([7, 6, 5, 4, 3, 2, 1, 0, -1, -1, -1, -1, -1, 10, 9, 8][idx1*4 + idx2]) if ramt_8k: netname="ram/WADDR_%d" % ([7, 6, 5, 4, 3, 2, 1, 0, -1, -1, -1, -1, -1, 10, 9, 8][idx1*4 + idx2]) match = re.match(r"(...)_op_(.*)", netname) if match: netname = "neigh_op_%s_%s" % (match.group(1), match.group(2)) if re.match(r"lutff_7/(cen|clk|s_r)", netname): netname = netname.replace("lutff_7/", "lutff_global/") if re.match(r"io_1/(cen|inclk|outclk)", netname): netname = netname.replace("io_1/", "io_global/") if netname == "carry_in_mux/cout": return "carry_in_mux" return netname def pos_has_net(pos, netname): if pos in ("l", "r"): if re.search(r"_vert_\d+$", netname): return False if re.search(r"_horz_[rl]_\d+$", netname): return False if pos in ("t", "b"): if re.search(r"_horz_\d+$", netname): return False if re.search(r"_vert_[bt]_\d+$", netname): return False return True def pos_follow_net(pos, direction, netname): if pos == "x": m = re.match("sp4_h_[lr]_(\d+)$", netname) if m and direction in ("l", "L"): n = sp4h_normalize(netname, "l") if n is not None: if direction == "l": n = re.sub("_l_", "_r_", n) n = sp4h_normalize(n) else: n = re.sub("_l_", "_", n) n = re.sub("sp4_h_", "span4_horz_", n) return n if m and direction in ("r", "R"): n = sp4h_normalize(netname, "r") if n is not None: if direction == "r": n = re.sub("_r_", "_l_", n) n = sp4h_normalize(n) else: n = re.sub("_r_", "_", n) n = re.sub("sp4_h_", "span4_horz_", n) return n m = re.match("sp4_v_[tb]_(\d+)$", netname) if m and direction in ("t", "T"): n = sp4v_normalize(netname, "t") if n is not None: if direction == "t": n = re.sub("_t_", "_b_", n) n = sp4v_normalize(n) else: n = re.sub("_t_", "_", n) n = re.sub("sp4_v_", "span4_vert_", n) return n if m and direction in ("b", "B"): n = sp4v_normalize(netname, "b") if n is not None: if direction == "b": n = re.sub("_b_", "_t_", n) n = sp4v_normalize(n) else: n = re.sub("_b_", "_", n) n = re.sub("sp4_v_", "span4_vert_", n) return n m = re.match("sp12_h_[lr]_(\d+)$", netname) if m and direction in ("l", "L"): n = sp12h_normalize(netname, "l") if n is not None: if direction == "l": n = re.sub("_l_", "_r_", n) n = sp12h_normalize(n) else: n = re.sub("_l_", "_", n) n = re.sub("sp12_h_", "span12_horz_", n) return n if m and direction in ("r", "R"): n = sp12h_normalize(netname, "r") if n is not None: if direction == "r": n = re.sub("_r_", "_l_", n) n = sp12h_normalize(n) else: n = re.sub("_r_", "_", n) n = re.sub("sp12_h_", "span12_horz_", n) return n m = re.match("sp12_v_[tb]_(\d+)$", netname) if m and direction in ("t", "T"): n = sp12v_normalize(netname, "t") if n is not None: if direction == "t": n = re.sub("_t_", "_b_", n) n = sp12v_normalize(n) else: n = re.sub("_t_", "_", n) n = re.sub("sp12_v_", "span12_vert_", n) return n if m and direction in ("b", "B"): n = sp12v_normalize(netname, "b") if n is not None: if direction == "b": n = re.sub("_b_", "_t_", n) n = sp12v_normalize(n) else: n = re.sub("_b_", "_", n) n = re.sub("sp12_v_", "span12_vert_", n) return n if pos in ("l", "r" ): m = re.match("span4_vert_([bt])_(\d+)$", netname) if m: case, idx = direction + m.group(1), int(m.group(2)) if case == "tt": return "span4_vert_b_%d" % idx if case == "tb" and idx >= 4: return "span4_vert_b_%d" % (idx-4) if case == "bb" and idx < 12: return "span4_vert_b_%d" % (idx+4) if case == "bb" and idx >= 12: return "span4_vert_t_%d" % idx if pos in ("t", "b" ): m = re.match("span4_horz_([rl])_(\d+)$", netname) if m: case, idx = direction + m.group(1), int(m.group(2)) if case == "ll": return "span4_horz_r_%d" % idx if case == "lr" and idx >= 4: return "span4_horz_r_%d" % (idx-4) if case == "rr" and idx < 12: return "span4_horz_r_%d" % (idx+4) if case == "rr" and idx >= 12: return "span4_horz_l_%d" % idx if pos == "l" and direction == "r": m = re.match("span4_horz_(\d+)$", netname) if m: return sp4h_normalize("sp4_h_l_%s" % m.group(1)) m = re.match("span12_horz_(\d+)$", netname) if m: return sp12h_normalize("sp12_h_l_%s" % m.group(1)) if pos == "r" and direction == "l": m = re.match("span4_horz_(\d+)$", netname) if m: return sp4h_normalize("sp4_h_r_%s" % m.group(1)) m = re.match("span12_horz_(\d+)$", netname) if m: return sp12h_normalize("sp12_h_r_%s" % m.group(1)) if pos == "t" and direction == "b": m = re.match("span4_vert_(\d+)$", netname) if m: return sp4v_normalize("sp4_v_t_%s" % m.group(1)) m = re.match("span12_vert_(\d+)$", netname) if m: return sp12v_normalize("sp12_v_t_%s" % m.group(1)) if pos == "b" and direction == "t": m = re.match("span4_vert_(\d+)$", netname) if m: return sp4v_normalize("sp4_v_b_%s" % m.group(1)) m = re.match("span12_vert_(\d+)$", netname) if m: return sp12v_normalize("sp12_v_b_%s" % m.group(1)) return None def get_lutff_bits(tile, index): bits = list("--------------------") for k, line in enumerate(tile): for i in range(36, 46): lutff_idx = k // 2 lutff_bitnum = (i-36) + 10*(k%2) if lutff_idx == index: bits[lutff_bitnum] = line[i]; return bits def get_lutff_lut_bits(tile, index): lutff_bits = get_lutff_bits(tile, index) return [lutff_bits[i] for i in [4, 14, 15, 5, 6, 16, 17, 7, 3, 13, 12, 2, 1, 11, 10, 0]] def get_lutff_seq_bits(tile, index): lutff_bits = get_lutff_bits(tile, index) return [lutff_bits[i] for i in [8, 9, 18, 19]] def get_carry_cascade_bit(tile): return tile[1][49] def get_carry_bit(tile): return tile[1][50] def get_negclk_bit(tile): return tile[0][0] def key_netname(netname): return re.sub(r"\d+", lambda m: "%09d" % int(m.group(0)), netname) def run_checks_neigh(): print("Running consistency checks on neighbour finder..") ic = iceconfig() # ic.setup_empty_1k() ic.setup_empty_5k() # ic.setup_empty_8k() # ic.setup_empty_384() all_segments = set() def add_segments(idx, db): for entry in db: if entry[1] in ("routing", "buffer"): if not ic.tile_has_net(idx[0], idx[1], entry[2]): continue if not ic.tile_has_net(idx[0], idx[1], entry[3]): continue all_segments.add((idx[0], idx[1], entry[2])) all_segments.add((idx[0], idx[1], entry[3])) for x in range(ic.max_x+1): for y in range(ic.max_x+1): # Skip the corners. if x in (0, ic.max_x) and y in (0, ic.max_y): continue # Skip the sides of a 5k device. if ic.device == "5k" and x in (0, ic.max_x): continue add_segments((x, y), ic.tile_db(x, y)) if (x, y) in ic.logic_tiles: all_segments.add((x, y, "lutff_7/cout")) for s1 in all_segments: for s2 in ic.follow_net(s1): # if s1[1] > 4: continue if s1 not in ic.follow_net(s2): print("ERROR: %s -> %s, but not vice versa!" % (s1, s2)) print("Neighbours of %s:" % (s1,)) for s in ic.follow_net(s1): print(" ", s) print("Neighbours of %s:" % (s2,)) for s in ic.follow_net(s2): print(" ", s) print() def run_checks(): run_checks_neigh() def parse_db(text, device="1k"): db = list() for line in text.split("\n"): line_384 = line.replace("384_glb_netwk_", "glb_netwk_") line_1k = line.replace("1k_glb_netwk_", "glb_netwk_") line_5k = line.replace("5k_glb_netwk_", "glb_netwk_") line_8k = line.replace("8k_glb_netwk_", "glb_netwk_") if line_1k != line: if device != "1k": continue line = line_1k elif line_8k != line: if device != "8k": continue line = line_8k elif line_5k != line: if device != "5k": continue line = line_5k elif line_384 != line: if device != "384": continue line = line_384 line = line.split("\t") if len(line) == 0 or line[0] == "": continue line[0] = line[0].split(",") db.append(line) return db extra_bits_db = { "1k": { (0, 330, 142): ("padin_glb_netwk", "0"), (0, 331, 142): ("padin_glb_netwk", "1"), (1, 330, 143): ("padin_glb_netwk", "2"), (1, 331, 143): ("padin_glb_netwk", "3"), # (1 3) (331 144) (331 144) routing T_0_0.padin_3 <X> T_0_0.glb_netwk_3 (1, 330, 142): ("padin_glb_netwk", "4"), (1, 331, 142): ("padin_glb_netwk", "5"), (0, 330, 143): ("padin_glb_netwk", "6"), # (0 0) (330 143) (330 143) routing T_0_0.padin_6 <X> T_0_0.glb_netwk_6 (0, 331, 143): ("padin_glb_netwk", "7"), }, "5k": { (0, 690, 334): ("padin_glb_netwk", "0"), # (0 1) (690 334) (690 334) routing T_0_0.padin_0 <X> T_0_0.glb_netwk_0 (1, 691, 334): ("padin_glb_netwk", "1"), # (1 1) (691 334) (691 334) routing T_0_0.padin_1 <X> T_0_0.glb_netwk_1 (0, 690, 336): ("padin_glb_netwk", "2"), # (0 3) (690 336) (690 336) routing T_0_0.padin_2 <X> T_0_0.glb_netwk_2 (1, 871, 271): ("padin_glb_netwk", "3"), (1, 870, 270): ("padin_glb_netwk", "4"), (1, 871, 270): ("padin_glb_netwk", "5"), (0, 870, 271): ("padin_glb_netwk", "6"), (1, 691, 335): ("padin_glb_netwk", "7"), # (1 0) (691 335) (691 335) routing T_0_0.padin_7 <X> T_0_0.glb_netwk_7 }, "8k": { (0, 870, 270): ("padin_glb_netwk", "0"), (0, 871, 270): ("padin_glb_netwk", "1"), (1, 870, 271): ("padin_glb_netwk", "2"), (1, 871, 271): ("padin_glb_netwk", "3"), (1, 870, 270): ("padin_glb_netwk", "4"), (1, 871, 270): ("padin_glb_netwk", "5"), (0, 870, 271): ("padin_glb_netwk", "6"), (0, 871, 271): ("padin_glb_netwk", "7"), }, "384": { (0, 180, 78): ("padin_glb_netwk", "0"), (0, 181, 78): ("padin_glb_netwk", "1"), (1, 180, 79): ("padin_glb_netwk", "2"), (1, 181, 79): ("padin_glb_netwk", "3"), (1, 180, 78): ("padin_glb_netwk", "4"), (1, 181, 78): ("padin_glb_netwk", "5"), (0, 180, 79): ("padin_glb_netwk", "6"), (0, 181, 79): ("padin_glb_netwk", "7"), } } gbufin_db = { "1k": [ (13, 8, 7), ( 0, 8, 6), ( 7, 17, 1), ( 7, 0, 0), ( 0, 9, 3), (13, 9, 2), ( 6, 0, 5), ( 6, 17, 4), ], "5k": [ # not sure how to get the third column, currently based on diagram in pdf. ( 6, 0, 0), (12, 0, 1), (13, 0, 3), (19, 0, 6), ( 6, 31, 5), (12, 31, 2), (13, 31, 7), (19, 31, 4), ], "8k": [ (33, 16, 7), ( 0, 16, 6), (17, 33, 1), (17, 0, 0), ( 0, 17, 3), (33, 17, 2), (16, 0, 5), (16, 33, 4), ], "384": [ ( 7, 4, 7), ( 0, 4, 6), ( 4, 9, 1), ( 4, 0, 0), ( 0, 5, 3), ( 7, 5, 2), ( 3, 0, 5), ( 3, 9, 4), ] } # To figure these out: # 1. Copy io_latched.sh and convert it for your pinout (like io_latched_5k.sh). # 2. Run it. It will create an io_latched_<device>.work directory with a bunch of files. # 3. Grep the *.ve files in that directory for "'fabout')". The coordinates # before it are where the io latches are. # # Note: This may not work if your icepack configuration of cell sizes is incorrect because # icebox_vlog.py won't correctly interpret the meaning of particular bits. iolatch_db = { "1k": [ ( 0, 7), (13, 10), ( 5, 0), ( 8, 17), ], "5k": [ (14, 0), (14, 31), ], "8k": [ ( 0, 15), (33, 18), (18, 0), (15, 33), ], "384": [ ( 0, 3), #384? ( 7, 5), #384? ( 2, 0), #384? ( 5, 9), #384? ], } # The x, y cell locations of the WARMBOOT controls. Run tests/sb_warmboot.v # through icecube.sh to determine these values. warmbootinfo_db = { "1k": { "BOOT": ( 12, 0, "fabout" ), "S0": ( 13, 1, "fabout" ), "S1": ( 13, 2, "fabout" ), }, "5k": { # These are the right locations but may be the wrong order. "BOOT": ( 22, 0, "fabout" ), "S0": ( 23, 0, "fabout" ), "S1": ( 24, 0, "fabout" ), }, "8k": { "BOOT": ( 31, 0, "fabout" ), "S0": ( 33, 1, "fabout" ), "S1": ( 33, 2, "fabout" ), }, "384": { "BOOT": ( 6, 0, "fabout" ), #384? "S0": ( 7, 1, "fabout" ), "S1": ( 7, 2, "fabout" ), } } noplls_db = { "1k-swg16tr": [ "1k" ], "1k-cm36": [ "1k" ], "1k-cm49": [ "1k" ], "8k-cm81": [ "8k_1" ], "8k-cm81:4k": [ "8k_1" ], "1k-qn48": [ "1k" ], "1k-cb81": [ "1k" ], "1k-cb121": [ "1k" ], "1k-vq100": [ "1k" ], "384-qn32": [ "384" ], "5k-sg48": [ "5k" ], } pllinfo_db = { "1k": { "LOC" : (6, 0), # 3'b000 = "DISABLED" # 3'b010 = "SB_PLL40_PAD" # 3'b100 = "SB_PLL40_2_PAD" # 3'b110 = "SB_PLL40_2F_PAD" # 3'b011 = "SB_PLL40_CORE" # 3'b111 = "SB_PLL40_2F_CORE" "PLLTYPE_0": ( 0, 3, "PLLCONFIG_5"), "PLLTYPE_1": ( 0, 5, "PLLCONFIG_1"), "PLLTYPE_2": ( 0, 5, "PLLCONFIG_3"), # 3'b000 = "DELAY" # 3'b001 = "SIMPLE" # 3'b010 = "PHASE_AND_DELAY" # 3'b110 = "EXTERNAL" "FEEDBACK_PATH_0": ( 0, 5, "PLLCONFIG_5"), "FEEDBACK_PATH_1": ( 0, 2, "PLLCONFIG_9"), "FEEDBACK_PATH_2": ( 0, 3, "PLLCONFIG_1"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_FEEDBACK=4'b1111) "DELAY_ADJMODE_FB": ( 0, 4, "PLLCONFIG_4"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_RELATIVE=4'b1111) "DELAY_ADJMODE_REL": ( 0, 4, "PLLCONFIG_9"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_A_0": ( 0, 3, "PLLCONFIG_6"), "PLLOUT_SELECT_A_1": ( 0, 3, "PLLCONFIG_7"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_B_0": ( 0, 3, "PLLCONFIG_2"), "PLLOUT_SELECT_B_1": ( 0, 3, "PLLCONFIG_3"), # Numeric Parameters "SHIFTREG_DIV_MODE": ( 0, 3, "PLLCONFIG_4"), "FDA_FEEDBACK_0": ( 0, 3, "PLLCONFIG_9"), "FDA_FEEDBACK_1": ( 0, 4, "PLLCONFIG_1"), "FDA_FEEDBACK_2": ( 0, 4, "PLLCONFIG_2"), "FDA_FEEDBACK_3": ( 0, 4, "PLLCONFIG_3"), "FDA_RELATIVE_0": ( 0, 4, "PLLCONFIG_5"), "FDA_RELATIVE_1": ( 0, 4, "PLLCONFIG_6"), "FDA_RELATIVE_2": ( 0, 4, "PLLCONFIG_7"), "FDA_RELATIVE_3": ( 0, 4, "PLLCONFIG_8"), "DIVR_0": ( 0, 1, "PLLCONFIG_1"), "DIVR_1": ( 0, 1, "PLLCONFIG_2"), "DIVR_2": ( 0, 1, "PLLCONFIG_3"), "DIVR_3": ( 0, 1, "PLLCONFIG_4"), "DIVF_0": ( 0, 1, "PLLCONFIG_5"), "DIVF_1": ( 0, 1, "PLLCONFIG_6"), "DIVF_2": ( 0, 1, "PLLCONFIG_7"), "DIVF_3": ( 0, 1, "PLLCONFIG_8"), "DIVF_4": ( 0, 1, "PLLCONFIG_9"), "DIVF_5": ( 0, 2, "PLLCONFIG_1"), "DIVF_6": ( 0, 2, "PLLCONFIG_2"), "DIVQ_0": ( 0, 2, "PLLCONFIG_3"), "DIVQ_1": ( 0, 2, "PLLCONFIG_4"), "DIVQ_2": ( 0, 2, "PLLCONFIG_5"), "FILTER_RANGE_0": ( 0, 2, "PLLCONFIG_6"), "FILTER_RANGE_1": ( 0, 2, "PLLCONFIG_7"), "FILTER_RANGE_2": ( 0, 2, "PLLCONFIG_8"), "TEST_MODE": ( 0, 3, "PLLCONFIG_8"), # PLL Ports "PLLOUT_A": ( 6, 0, 1), "PLLOUT_B": ( 7, 0, 0), "REFERENCECLK": ( 0, 1, "fabout"), "EXTFEEDBACK": ( 0, 2, "fabout"), "DYNAMICDELAY_0": ( 0, 4, "fabout"), "DYNAMICDELAY_1": ( 0, 5, "fabout"), "DYNAMICDELAY_2": ( 0, 6, "fabout"), "DYNAMICDELAY_3": ( 0, 10, "fabout"), "DYNAMICDELAY_4": ( 0, 11, "fabout"), "DYNAMICDELAY_5": ( 0, 12, "fabout"), "DYNAMICDELAY_6": ( 0, 13, "fabout"), "DYNAMICDELAY_7": ( 0, 14, "fabout"), "LOCK": ( 1, 1, "neigh_op_bnl_1"), "BYPASS": ( 1, 0, "fabout"), "RESETB": ( 2, 0, "fabout"), "LATCHINPUTVALUE": ( 5, 0, "fabout"), "SDO": (12, 1, "neigh_op_bnr_3"), "SDI": ( 4, 0, "fabout"), "SCLK": ( 3, 0, "fabout"), }, "5k": { #FIXME: pins are definitely not correct "LOC" : (12, 31), # 3'b000 = "DISABLED" # 3'b010 = "SB_PLL40_PAD" # 3'b100 = "SB_PLL40_2_PAD" # 3'b110 = "SB_PLL40_2F_PAD" # 3'b011 = "SB_PLL40_CORE" # 3'b111 = "SB_PLL40_2F_CORE" "PLLTYPE_0": ( 16, 0, "PLLCONFIG_5"), "PLLTYPE_1": ( 18, 0, "PLLCONFIG_1"), "PLLTYPE_2": ( 18, 0, "PLLCONFIG_3"), # 3'b000 = "DELAY" # 3'b001 = "SIMPLE" # 3'b010 = "PHASE_AND_DELAY" # 3'b110 = "EXTERNAL" "FEEDBACK_PATH_0": ( 18, 0, "PLLCONFIG_5"), "FEEDBACK_PATH_1": ( 15, 0, "PLLCONFIG_9"), "FEEDBACK_PATH_2": ( 16, 0, "PLLCONFIG_1"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_FEEDBACK=4'b1111) "DELAY_ADJMODE_FB": ( 17, 0, "PLLCONFIG_4"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_RELATIVE=4'b1111) "DELAY_ADJMODE_REL": ( 17, 0, "PLLCONFIG_9"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_A_0": ( 16, 0, "PLLCONFIG_6"), "PLLOUT_SELECT_A_1": ( 16, 0, "PLLCONFIG_7"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_B_0": ( 16, 0, "PLLCONFIG_2"), "PLLOUT_SELECT_B_1": ( 16, 0, "PLLCONFIG_3"), # Numeric Parameters "SHIFTREG_DIV_MODE": ( 16, 0, "PLLCONFIG_4"), "FDA_FEEDBACK_0": ( 16, 0, "PLLCONFIG_9"), "FDA_FEEDBACK_1": ( 17, 0, "PLLCONFIG_1"), "FDA_FEEDBACK_2": ( 17, 0, "PLLCONFIG_2"), "FDA_FEEDBACK_3": ( 17, 0, "PLLCONFIG_3"), "FDA_RELATIVE_0": ( 17, 0, "PLLCONFIG_5"), "FDA_RELATIVE_1": ( 17, 0, "PLLCONFIG_6"), "FDA_RELATIVE_2": ( 17, 0, "PLLCONFIG_7"), "FDA_RELATIVE_3": ( 17, 0, "PLLCONFIG_8"), "DIVR_0": ( 14, 0, "PLLCONFIG_1"), "DIVR_1": ( 14, 0, "PLLCONFIG_2"), "DIVR_2": ( 14, 0, "PLLCONFIG_3"), "DIVR_3": ( 14, 0, "PLLCONFIG_4"), "DIVF_0": ( 14, 0, "PLLCONFIG_5"), "DIVF_1": ( 14, 0, "PLLCONFIG_6"), "DIVF_2": ( 14, 0, "PLLCONFIG_7"), "DIVF_3": ( 14, 0, "PLLCONFIG_8"), "DIVF_4": ( 14, 0, "PLLCONFIG_9"), "DIVF_5": ( 15, 0, "PLLCONFIG_1"), "DIVF_6": ( 15, 0, "PLLCONFIG_2"), "DIVQ_0": ( 15, 0, "PLLCONFIG_3"), "DIVQ_1": ( 15, 0, "PLLCONFIG_4"), "DIVQ_2": ( 15, 0, "PLLCONFIG_5"), "FILTER_RANGE_0": ( 15, 0, "PLLCONFIG_6"), "FILTER_RANGE_1": ( 15, 0, "PLLCONFIG_7"), "FILTER_RANGE_2": ( 15, 0, "PLLCONFIG_8"), "TEST_MODE": ( 16, 0, "PLLCONFIG_8"), # PLL Ports "PLLOUT_A": ( 16, 0, 1), "PLLOUT_B": ( 17, 0, 0), "REFERENCECLK": ( 13, 0, "fabout"), "EXTFEEDBACK": ( 14, 0, "fabout"), "DYNAMICDELAY_0": ( 5, 0, "fabout"), "DYNAMICDELAY_1": ( 6, 0, "fabout"), "DYNAMICDELAY_2": ( 7, 0, "fabout"), "DYNAMICDELAY_3": ( 8, 0, "fabout"), "DYNAMICDELAY_4": ( 9, 0, "fabout"), "DYNAMICDELAY_5": ( 10, 0, "fabout"), "DYNAMICDELAY_6": ( 11, 0, "fabout"), "DYNAMICDELAY_7": ( 12, 0, "fabout"), "LOCK": ( 1, 1, "neigh_op_bnl_1"), "BYPASS": ( 19, 0, "fabout"), "RESETB": ( 20, 0, "fabout"), "LATCHINPUTVALUE": ( 15, 0, "fabout"), "SDO": ( 24, 30, "neigh_op_bnr_3"), "SDI": ( 22, 0, "fabout"), "SCLK": ( 21, 0, "fabout"), }, "8k_0": { "LOC" : (16, 0), # 3'b000 = "DISABLED" # 3'b010 = "SB_PLL40_PAD" # 3'b100 = "SB_PLL40_2_PAD" # 3'b110 = "SB_PLL40_2F_PAD" # 3'b011 = "SB_PLL40_CORE" # 3'b111 = "SB_PLL40_2F_CORE" "PLLTYPE_0": ( 16, 0, "PLLCONFIG_5"), "PLLTYPE_1": ( 18, 0, "PLLCONFIG_1"), "PLLTYPE_2": ( 18, 0, "PLLCONFIG_3"), # 3'b000 = "DELAY" # 3'b001 = "SIMPLE" # 3'b010 = "PHASE_AND_DELAY" # 3'b110 = "EXTERNAL" "FEEDBACK_PATH_0": ( 18, 0, "PLLCONFIG_5"), "FEEDBACK_PATH_1": ( 15, 0, "PLLCONFIG_9"), "FEEDBACK_PATH_2": ( 16, 0, "PLLCONFIG_1"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_FEEDBACK=4'b1111) "DELAY_ADJMODE_FB": ( 17, 0, "PLLCONFIG_4"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_RELATIVE=4'b1111) "DELAY_ADJMODE_REL": ( 17, 0, "PLLCONFIG_9"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_A_0": ( 16, 0, "PLLCONFIG_6"), "PLLOUT_SELECT_A_1": ( 16, 0, "PLLCONFIG_7"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_B_0": ( 16, 0, "PLLCONFIG_2"), "PLLOUT_SELECT_B_1": ( 16, 0, "PLLCONFIG_3"), # Numeric Parameters "SHIFTREG_DIV_MODE": ( 16, 0, "PLLCONFIG_4"), "FDA_FEEDBACK_0": ( 16, 0, "PLLCONFIG_9"), "FDA_FEEDBACK_1": ( 17, 0, "PLLCONFIG_1"), "FDA_FEEDBACK_2": ( 17, 0, "PLLCONFIG_2"), "FDA_FEEDBACK_3": ( 17, 0, "PLLCONFIG_3"), "FDA_RELATIVE_0": ( 17, 0, "PLLCONFIG_5"), "FDA_RELATIVE_1": ( 17, 0, "PLLCONFIG_6"), "FDA_RELATIVE_2": ( 17, 0, "PLLCONFIG_7"), "FDA_RELATIVE_3": ( 17, 0, "PLLCONFIG_8"), "DIVR_0": ( 14, 0, "PLLCONFIG_1"), "DIVR_1": ( 14, 0, "PLLCONFIG_2"), "DIVR_2": ( 14, 0, "PLLCONFIG_3"), "DIVR_3": ( 14, 0, "PLLCONFIG_4"), "DIVF_0": ( 14, 0, "PLLCONFIG_5"), "DIVF_1": ( 14, 0, "PLLCONFIG_6"), "DIVF_2": ( 14, 0, "PLLCONFIG_7"), "DIVF_3": ( 14, 0, "PLLCONFIG_8"), "DIVF_4": ( 14, 0, "PLLCONFIG_9"), "DIVF_5": ( 15, 0, "PLLCONFIG_1"), "DIVF_6": ( 15, 0, "PLLCONFIG_2"), "DIVQ_0": ( 15, 0, "PLLCONFIG_3"), "DIVQ_1": ( 15, 0, "PLLCONFIG_4"), "DIVQ_2": ( 15, 0, "PLLCONFIG_5"), "FILTER_RANGE_0": ( 15, 0, "PLLCONFIG_6"), "FILTER_RANGE_1": ( 15, 0, "PLLCONFIG_7"), "FILTER_RANGE_2": ( 15, 0, "PLLCONFIG_8"), "TEST_MODE": ( 16, 0, "PLLCONFIG_8"), # PLL Ports "PLLOUT_A": ( 16, 0, 1), "PLLOUT_B": ( 17, 0, 0), "REFERENCECLK": ( 13, 0, "fabout"), "EXTFEEDBACK": ( 14, 0, "fabout"), "DYNAMICDELAY_0": ( 5, 0, "fabout"), "DYNAMICDELAY_1": ( 6, 0, "fabout"), "DYNAMICDELAY_2": ( 7, 0, "fabout"), "DYNAMICDELAY_3": ( 8, 0, "fabout"), "DYNAMICDELAY_4": ( 9, 0, "fabout"), "DYNAMICDELAY_5": ( 10, 0, "fabout"), "DYNAMICDELAY_6": ( 11, 0, "fabout"), "DYNAMICDELAY_7": ( 12, 0, "fabout"), "LOCK": ( 1, 1, "neigh_op_bnl_1"), "BYPASS": ( 19, 0, "fabout"), "RESETB": ( 20, 0, "fabout"), "LATCHINPUTVALUE": ( 15, 0, "fabout"), "SDO": ( 32, 1, "neigh_op_bnr_3"), "SDI": ( 22, 0, "fabout"), "SCLK": ( 21, 0, "fabout"), }, "8k_1": { "LOC" : (16, 33), # 3'b000 = "DISABLED" # 3'b010 = "SB_PLL40_PAD" # 3'b100 = "SB_PLL40_2_PAD" # 3'b110 = "SB_PLL40_2F_PAD" # 3'b011 = "SB_PLL40_CORE" # 3'b111 = "SB_PLL40_2F_CORE" "PLLTYPE_0": ( 16, 33, "PLLCONFIG_5"), "PLLTYPE_1": ( 18, 33, "PLLCONFIG_1"), "PLLTYPE_2": ( 18, 33, "PLLCONFIG_3"), # 3'b000 = "DELAY" # 3'b001 = "SIMPLE" # 3'b010 = "PHASE_AND_DELAY" # 3'b110 = "EXTERNAL" "FEEDBACK_PATH_0": ( 18, 33, "PLLCONFIG_5"), "FEEDBACK_PATH_1": ( 15, 33, "PLLCONFIG_9"), "FEEDBACK_PATH_2": ( 16, 33, "PLLCONFIG_1"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_FEEDBACK=4'b1111) "DELAY_ADJMODE_FB": ( 17, 33, "PLLCONFIG_4"), # 1'b0 = "FIXED" # 1'b1 = "DYNAMIC" (also set FDA_RELATIVE=4'b1111) "DELAY_ADJMODE_REL": ( 17, 33, "PLLCONFIG_9"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_A_0": ( 16, 33, "PLLCONFIG_6"), "PLLOUT_SELECT_A_1": ( 16, 33, "PLLCONFIG_7"), # 2'b00 = "GENCLK" # 2'b01 = "GENCLK_HALF" # 2'b10 = "SHIFTREG_90deg" # 2'b11 = "SHIFTREG_0deg" "PLLOUT_SELECT_B_0": ( 16, 33, "PLLCONFIG_2"), "PLLOUT_SELECT_B_1": ( 16, 33, "PLLCONFIG_3"), # Numeric Parameters "SHIFTREG_DIV_MODE": ( 16, 33, "PLLCONFIG_4"), "FDA_FEEDBACK_0": ( 16, 33, "PLLCONFIG_9"), "FDA_FEEDBACK_1": ( 17, 33, "PLLCONFIG_1"), "FDA_FEEDBACK_2": ( 17, 33, "PLLCONFIG_2"), "FDA_FEEDBACK_3": ( 17, 33, "PLLCONFIG_3"), "FDA_RELATIVE_0": ( 17, 33, "PLLCONFIG_5"), "FDA_RELATIVE_1": ( 17, 33, "PLLCONFIG_6"), "FDA_RELATIVE_2": ( 17, 33, "PLLCONFIG_7"), "FDA_RELATIVE_3": ( 17, 33, "PLLCONFIG_8"), "DIVR_0": ( 14, 33, "PLLCONFIG_1"), "DIVR_1": ( 14, 33, "PLLCONFIG_2"), "DIVR_2": ( 14, 33, "PLLCONFIG_3"), "DIVR_3": ( 14, 33, "PLLCONFIG_4"), "DIVF_0": ( 14, 33, "PLLCONFIG_5"), "DIVF_1": ( 14, 33, "PLLCONFIG_6"), "DIVF_2": ( 14, 33, "PLLCONFIG_7"), "DIVF_3": ( 14, 33, "PLLCONFIG_8"), "DIVF_4": ( 14, 33, "PLLCONFIG_9"), "DIVF_5": ( 15, 33, "PLLCONFIG_1"), "DIVF_6": ( 15, 33, "PLLCONFIG_2"), "DIVQ_0": ( 15, 33, "PLLCONFIG_3"), "DIVQ_1": ( 15, 33, "PLLCONFIG_4"), "DIVQ_2": ( 15, 33, "PLLCONFIG_5"), "FILTER_RANGE_0": ( 15, 33, "PLLCONFIG_6"), "FILTER_RANGE_1": ( 15, 33, "PLLCONFIG_7"), "FILTER_RANGE_2": ( 15, 33, "PLLCONFIG_8"), "TEST_MODE": ( 16, 33, "PLLCONFIG_8"), # PLL Ports "PLLOUT_A": ( 16, 33, 1), "PLLOUT_B": ( 17, 33, 0), "REFERENCECLK": ( 13, 33, "fabout"), "EXTFEEDBACK": ( 14, 33, "fabout"), "DYNAMICDELAY_0": ( 5, 33, "fabout"), "DYNAMICDELAY_1": ( 6, 33, "fabout"), "DYNAMICDELAY_2": ( 7, 33, "fabout"), "DYNAMICDELAY_3": ( 8, 33, "fabout"), "DYNAMICDELAY_4": ( 9, 33, "fabout"), "DYNAMICDELAY_5": ( 10, 33, "fabout"), "DYNAMICDELAY_6": ( 11, 33, "fabout"), "DYNAMICDELAY_7": ( 12, 33, "fabout"), "LOCK": ( 1, 32, "neigh_op_tnl_1"), "BYPASS": ( 19, 33, "fabout"), "RESETB": ( 20, 33, "fabout"), "LATCHINPUTVALUE": ( 15, 33, "fabout"), "SDO": ( 32, 32, "neigh_op_tnr_1"), "SDI": ( 22, 33, "fabout"), "SCLK": ( 21, 33, "fabout"), }, } padin_pio_db = { "1k": [ (13, 8, 1), # glb_netwk_0 ( 0, 8, 1), # glb_netwk_1 ( 7, 17, 0), # glb_netwk_2 ( 7, 0, 0), # glb_netwk_3 ( 0, 9, 0), # glb_netwk_4 (13, 9, 0), # glb_netwk_5 ( 6, 0, 1), # glb_netwk_6 ( 6, 17, 1), # glb_netwk_7 ], "5k": [ ( 6, 0, 1), (19, 0, 1), ( 6, 31, 0), (12, 31, 1), (13, 31, 0), ], "8k": [ (33, 16, 1), ( 0, 16, 1), (17, 33, 0), (17, 0, 0), ( 0, 17, 0), (33, 17, 0), (16, 0, 1), (16, 33, 1), ], "384": [ ( 7, 4, 1), ( 0, 4, 1), ( 4, 9, 0), ( 4, 0, 0), #QFN32: no pin?! ( 0, 5, 0), ( 7, 5, 0), ( 3, 0, 1), #QFN32: no pin?! ( 3, 9, 1), ] } ieren_db = { "1k": [ # IO-block (X, Y, Z) <-> IeRen-block (X, Y, Z) ( 0, 2, 0, 0, 2, 1), ( 0, 2, 1, 0, 2, 0), ( 0, 3, 0, 0, 3, 1), ( 0, 3, 1, 0, 3, 0), ( 0, 4, 0, 0, 4, 1), ( 0, 4, 1, 0, 4, 0), ( 0, 5, 0, 0, 5, 1), ( 0, 5, 1, 0, 5, 0), ( 0, 6, 0, 0, 6, 1), ( 0, 6, 1, 0, 6, 0), ( 0, 8, 0, 0, 8, 1), ( 0, 8, 1, 0, 8, 0), ( 0, 9, 0, 0, 9, 1), ( 0, 9, 1, 0, 9, 0), ( 0, 10, 0, 0, 10, 1), ( 0, 10, 1, 0, 10, 0), ( 0, 11, 0, 0, 11, 1), ( 0, 11, 1, 0, 11, 0), ( 0, 12, 0, 0, 12, 1), ( 0, 12, 1, 0, 12, 0), ( 0, 13, 0, 0, 13, 1), ( 0, 13, 1, 0, 13, 0), ( 0, 14, 0, 0, 14, 1), ( 0, 14, 1, 0, 14, 0), ( 1, 0, 0, 1, 0, 0), ( 1, 0, 1, 1, 0, 1), ( 1, 17, 0, 1, 17, 0), ( 1, 17, 1, 1, 17, 1), ( 2, 0, 0, 2, 0, 0), ( 2, 0, 1, 2, 0, 1), ( 2, 17, 0, 2, 17, 0), ( 2, 17, 1, 2, 17, 1), ( 3, 0, 0, 3, 0, 0), ( 3, 0, 1, 3, 0, 1), ( 3, 17, 0, 3, 17, 0), ( 3, 17, 1, 3, 17, 1), ( 4, 0, 0, 4, 0, 0), ( 4, 0, 1, 4, 0, 1), ( 4, 17, 0, 4, 17, 0), ( 4, 17, 1, 4, 17, 1), ( 5, 0, 0, 5, 0, 0), ( 5, 0, 1, 5, 0, 1), ( 5, 17, 0, 5, 17, 0), ( 5, 17, 1, 5, 17, 1), ( 6, 0, 0, 7, 0, 0), ( 6, 0, 1, 6, 0, 0), ( 6, 17, 0, 6, 17, 0), ( 6, 17, 1, 6, 17, 1), ( 7, 0, 0, 6, 0, 1), ( 7, 0, 1, 7, 0, 1), ( 7, 17, 0, 7, 17, 0), ( 7, 17, 1, 7, 17, 1), ( 8, 0, 0, 8, 0, 0), ( 8, 0, 1, 8, 0, 1), ( 8, 17, 0, 8, 17, 0), ( 8, 17, 1, 8, 17, 1), ( 9, 0, 0, 9, 0, 0), ( 9, 0, 1, 9, 0, 1), ( 9, 17, 0, 10, 17, 0), ( 9, 17, 1, 10, 17, 1), (10, 0, 0, 10, 0, 0), (10, 0, 1, 10, 0, 1), (10, 17, 0, 9, 17, 0), (10, 17, 1, 9, 17, 1), (11, 0, 0, 11, 0, 0), (11, 0, 1, 11, 0, 1), (11, 17, 0, 11, 17, 0), (11, 17, 1, 11, 17, 1), (12, 0, 0, 12, 0, 0), (12, 0, 1, 12, 0, 1), (12, 17, 0, 12, 17, 0), (12, 17, 1, 12, 17, 1), (13, 1, 0, 13, 1, 0), (13, 1, 1, 13, 1, 1), (13, 2, 0, 13, 2, 0), (13, 2, 1, 13, 2, 1), (13, 3, 1, 13, 3, 1), (13, 4, 0, 13, 4, 0), (13, 4, 1, 13, 4, 1), (13, 6, 0, 13, 6, 0), (13, 6, 1, 13, 6, 1), (13, 7, 0, 13, 7, 0), (13, 7, 1, 13, 7, 1), (13, 8, 0, 13, 8, 0), (13, 8, 1, 13, 8, 1), (13, 9, 0, 13, 9, 0), (13, 9, 1, 13, 9, 1), (13, 11, 0, 13, 10, 0), (13, 11, 1, 13, 10, 1), (13, 12, 0, 13, 11, 0), (13, 12, 1, 13, 11, 1), (13, 13, 0, 13, 13, 0), (13, 13, 1, 13, 13, 1), (13, 14, 0, 13, 14, 0), (13, 14, 1, 13, 14, 1), (13, 15, 0, 13, 15, 0), (13, 15, 1, 13, 15, 1), ], "8k": [ ( 0, 3, 0, 0, 3, 0), ( 0, 3, 1, 0, 3, 1), ( 0, 4, 0, 0, 4, 0), ( 0, 4, 1, 0, 4, 1), ( 0, 5, 0, 0, 5, 0), ( 0, 5, 1, 0, 5, 1), ( 0, 6, 0, 0, 6, 0), ( 0, 6, 1, 0, 6, 1), ( 0, 7, 0, 0, 7, 0), ( 0, 7, 1, 0, 7, 1), ( 0, 8, 0, 0, 8, 0), ( 0, 8, 1, 0, 8, 1), ( 0, 9, 0, 0, 9, 0), ( 0, 9, 1, 0, 9, 1), ( 0, 10, 0, 0, 10, 0), ( 0, 10, 1, 0, 10, 1), ( 0, 11, 0, 0, 11, 0), ( 0, 11, 1, 0, 11, 1), ( 0, 12, 0, 0, 12, 0), ( 0, 12, 1, 0, 12, 1), ( 0, 13, 0, 0, 13, 0), ( 0, 13, 1, 0, 13, 1), ( 0, 14, 0, 0, 14, 0), ( 0, 14, 1, 0, 14, 1), ( 0, 16, 0, 0, 16, 0), ( 0, 16, 1, 0, 16, 1), ( 0, 17, 0, 0, 17, 0), ( 0, 17, 1, 0, 17, 1), ( 0, 18, 0, 0, 18, 0), ( 0, 18, 1, 0, 18, 1), ( 0, 19, 0, 0, 19, 0), ( 0, 19, 1, 0, 19, 1), ( 0, 20, 0, 0, 20, 0), ( 0, 20, 1, 0, 20, 1), ( 0, 21, 0, 0, 21, 0), ( 0, 21, 1, 0, 21, 1), ( 0, 22, 0, 0, 22, 0), ( 0, 22, 1, 0, 22, 1), ( 0, 23, 0, 0, 23, 0), ( 0, 23, 1, 0, 23, 1), ( 0, 24, 0, 0, 24, 0), ( 0, 24, 1, 0, 24, 1), ( 0, 25, 0, 0, 25, 0), ( 0, 25, 1, 0, 25, 1), ( 0, 27, 0, 0, 27, 0), ( 0, 27, 1, 0, 27, 1), ( 0, 28, 0, 0, 28, 0), ( 0, 28, 1, 0, 28, 1), ( 0, 30, 0, 0, 30, 0), ( 0, 30, 1, 0, 30, 1), ( 0, 31, 0, 0, 31, 0), ( 0, 31, 1, 0, 31, 1), ( 1, 33, 0, 1, 33, 0), ( 1, 33, 1, 1, 33, 1), ( 2, 0, 0, 2, 0, 0), ( 2, 0, 1, 2, 0, 1), ( 2, 33, 0, 2, 33, 0), ( 2, 33, 1, 2, 33, 1), ( 3, 0, 0, 3, 0, 0), ( 3, 0, 1, 3, 0, 1), ( 3, 33, 0, 3, 33, 0), ( 3, 33, 1, 3, 33, 1), ( 4, 0, 0, 4, 0, 0), ( 4, 0, 1, 4, 0, 1), ( 4, 33, 0, 4, 33, 0), ( 4, 33, 1, 4, 33, 1), ( 5, 0, 0, 5, 0, 0), ( 5, 0, 1, 5, 0, 1), ( 5, 33, 0, 5, 33, 0), ( 5, 33, 1, 5, 33, 1), ( 6, 0, 0, 6, 0, 0), ( 6, 0, 1, 6, 0, 1), ( 6, 33, 0, 6, 33, 0), ( 6, 33, 1, 6, 33, 1), ( 7, 0, 0, 7, 0, 0), ( 7, 0, 1, 7, 0, 1), ( 7, 33, 0, 7, 33, 0), ( 7, 33, 1, 7, 33, 1), ( 8, 0, 0, 8, 0, 0), ( 8, 0, 1, 8, 0, 1), ( 8, 33, 0, 8, 33, 0), ( 8, 33, 1, 8, 33, 1), ( 9, 0, 0, 9, 0, 0), ( 9, 0, 1, 9, 0, 1), ( 9, 33, 0, 9, 33, 0), ( 9, 33, 1, 9, 33, 1), (10, 0, 0, 10, 0, 0), (10, 0, 1, 10, 0, 1), (10, 33, 0, 10, 33, 0), (10, 33, 1, 10, 33, 1), (11, 0, 0, 11, 0, 0), (11, 0, 1, 11, 0, 1), (11, 33, 0, 11, 33, 0), (11, 33, 1, 11, 33, 1), (12, 0, 0, 12, 0, 0), (12, 0, 1, 12, 0, 1), (12, 33, 0, 12, 33, 0), (13, 0, 0, 13, 0, 0), (13, 0, 1, 13, 0, 1), (13, 33, 0, 13, 33, 0), (13, 33, 1, 13, 33, 1), (14, 0, 0, 14, 0, 0), (14, 0, 1, 14, 0, 1), (14, 33, 0, 14, 33, 0), (14, 33, 1, 14, 33, 1), (15, 0, 0, 15, 0, 0), (15, 0, 1, 15, 0, 1), (16, 0, 0, 16, 0, 0), (16, 0, 1, 16, 0, 1), (16, 33, 0, 16, 33, 0), (16, 33, 1, 16, 33, 1), (17, 0, 0, 17, 0, 0), (17, 0, 1, 17, 0, 1), (17, 33, 0, 17, 33, 0), (17, 33, 1, 17, 33, 1), (18, 33, 0, 18, 33, 0), (18, 33, 1, 18, 33, 1), (19, 0, 0, 19, 0, 0), (19, 0, 1, 19, 0, 1), (19, 33, 0, 19, 33, 0), (19, 33, 1, 19, 33, 1), (20, 0, 0, 20, 0, 0), (20, 0, 1, 20, 0, 1), (20, 33, 0, 20, 33, 0), (20, 33, 1, 20, 33, 1), (21, 0, 0, 21, 0, 0), (21, 0, 1, 21, 0, 1), (21, 33, 0, 21, 33, 0), (21, 33, 1, 21, 33, 1), (22, 0, 0, 22, 0, 0), (22, 0, 1, 22, 0, 1), (22, 33, 0, 22, 33, 0), (22, 33, 1, 22, 33, 1), (23, 0, 0, 23, 0, 0), (23, 0, 1, 23, 0, 1), (23, 33, 0, 23, 33, 0), (23, 33, 1, 23, 33, 1), (24, 0, 0, 24, 0, 0), (24, 0, 1, 24, 0, 1), (24, 33, 0, 24, 33, 0), (24, 33, 1, 24, 33, 1), (25, 0, 0, 25, 0, 0), (25, 33, 0, 25, 33, 0), (25, 33, 1, 25, 33, 1), (26, 0, 0, 26, 0, 0), (26, 0, 1, 26, 0, 1), (26, 33, 0, 26, 33, 0), (26, 33, 1, 26, 33, 1), (27, 0, 0, 27, 0, 0), (27, 0, 1, 27, 0, 1), (27, 33, 0, 27, 33, 0), (27, 33, 1, 27, 33, 1), (28, 0, 0, 28, 0, 0), (28, 33, 1, 28, 33, 1), (29, 0, 0, 29, 0, 0), (29, 0, 1, 29, 0, 1), (29, 33, 0, 29, 33, 0), (29, 33, 1, 29, 33, 1), (30, 0, 0, 30, 0, 0), (30, 0, 1, 30, 0, 1), (30, 33, 0, 30, 33, 0), (30, 33, 1, 30, 33, 1), (31, 0, 0, 31, 0, 0), (31, 0, 1, 31, 0, 1), (31, 33, 0, 31, 33, 0), (31, 33, 1, 31, 33, 1), (33, 1, 0, 33, 1, 0), (33, 1, 1, 33, 1, 1), (33, 2, 0, 33, 2, 0), (33, 2, 1, 33, 2, 1), (33, 3, 0, 33, 3, 0), (33, 3, 1, 33, 3, 1), (33, 4, 0, 33, 4, 0), (33, 4, 1, 33, 4, 1), (33, 5, 0, 33, 5, 0), (33, 5, 1, 33, 5, 1), (33, 6, 0, 33, 6, 0), (33, 6, 1, 33, 6, 1), (33, 7, 0, 33, 7, 0), (33, 7, 1, 33, 7, 1), (33, 8, 0, 33, 8, 0), (33, 9, 0, 33, 9, 0), (33, 9, 1, 33, 9, 1), (33, 10, 0, 33, 10, 0), (33, 10, 1, 33, 10, 1), (33, 11, 0, 33, 11, 0), (33, 11, 1, 33, 11, 1), (33, 12, 0, 33, 12, 0), (33, 13, 0, 33, 13, 0), (33, 13, 1, 33, 13, 1), (33, 14, 0, 33, 14, 0), (33, 14, 1, 33, 14, 1), (33, 15, 0, 33, 15, 0), (33, 15, 1, 33, 15, 1), (33, 16, 0, 33, 16, 0), (33, 16, 1, 33, 16, 1), (33, 17, 0, 33, 17, 0), (33, 17, 1, 33, 17, 1), (33, 19, 0, 33, 19, 0), (33, 19, 1, 33, 19, 1), (33, 20, 0, 33, 20, 0), (33, 20, 1, 33, 20, 1), (33, 21, 0, 33, 21, 0), (33, 21, 1, 33, 21, 1), (33, 22, 0, 33, 22, 0), (33, 22, 1, 33, 22, 1), (33, 23, 0, 33, 23, 0), (33, 23, 1, 33, 23, 1), (33, 24, 0, 33, 24, 0), (33, 24, 1, 33, 24, 1), (33, 25, 0, 33, 25, 0), (33, 25, 1, 33, 25, 1), (33, 26, 0, 33, 26, 0), (33, 26, 1, 33, 26, 1), (33, 27, 0, 33, 27, 0), (33, 27, 1, 33, 27, 1), (33, 28, 0, 33, 28, 0), (33, 28, 1, 33, 28, 1), (33, 29, 1, 33, 29, 1), (33, 30, 0, 33, 30, 0), (33, 30, 1, 33, 30, 1), (33, 31, 0, 33, 31, 0), ], "384": [ ( 0, 1, 0, 0, 1, 1), ( 0, 1, 1, 0, 1, 0), ( 0, 2, 0, 0, 2, 1), ( 0, 2, 1, 0, 2, 0), ( 0, 4, 0, 0, 4, 1), ( 0, 4, 1, 0, 4, 0), ( 0, 5, 0, 0, 5, 1), ( 0, 5, 1, 0, 5, 0), ( 0, 6, 0, 0, 6, 1), ( 0, 6, 1, 0, 6, 0), ( 0, 7, 0, 0, 7, 1), ( 0, 7, 1, 0, 7, 0), ( 2, 9, 0, 2, 9, 1), ( 2, 9, 1, 2, 9, 0), ( 3, 0, 0, 3, 0, 1), ( 3, 0, 1, 3, 0, 0), ( 3, 9, 0, 3, 9, 1), ( 3, 9, 1, 3, 9, 0), ( 4, 0, 0, 4, 0, 1), ( 4, 0, 1, 4, 0, 0), ( 4, 9, 0, 4, 9, 1), ( 4, 9, 1, 4, 9, 0), ( 5, 0, 0, 5, 0, 1), ( 5, 0, 1, 5, 0, 0), ( 5, 9, 0, 5, 9, 1), ( 5, 9, 1, 5, 9, 0), ( 6, 0, 0, 6, 0, 1), ( 6, 0, 1, 6, 0, 0), ( 6, 9, 0, 6, 9, 1), ( 6, 9, 1, 6, 9, 0), ( 7, 3, 1, 7, 3, 0), ( 7, 4, 0, 7, 4, 1), ( 7, 4, 1, 7, 4, 0), ( 7, 5, 0, 7, 5, 1), ( 7, 5, 1, 7, 5, 0), ( 7, 6, 0, 7, 6, 1), ( 7, 6, 1, 7, 6, 0), ], "5k": [ #TODO: is this correct? (1 , 0, 0, 1 , 0, 0), (1 , 0, 1, 1 , 0, 1), (1 , 31, 0, 1 , 31, 0), (1 , 31, 1, 1 , 31, 1), (2 , 0, 0, 2 , 0, 0), (2 , 0, 1, 2 , 0, 1), (2 , 31, 0, 2 , 31, 0), (2 , 31, 1, 2 , 31, 1), (3 , 0, 0, 3 , 0, 0), (3 , 0, 1, 3 , 0, 1), (3 , 31, 0, 3 , 31, 0), (3 , 31, 1, 3 , 31, 1), (4 , 0, 0, 4 , 0, 0), (4 , 0, 1, 4 , 0, 1), (4 , 31, 0, 4 , 31, 0), (4 , 31, 1, 4 , 31, 1), (5 , 0, 0, 5 , 0, 0), (5 , 0, 1, 5 , 0, 1), (5 , 31, 0, 5 , 31, 0), (5 , 31, 1, 5 , 31, 1), (6 , 0, 0, 6 , 0, 0), (6 , 0, 1, 6 , 0, 1), (6 , 31, 0, 6 , 31, 0), (6 , 31, 1, 6 , 31, 1), (7 , 0, 0, 7 , 0, 0), (7 , 0, 1, 7 , 0, 1), (7 , 31, 0, 7 , 31, 0), (7 , 31, 1, 7 , 31, 1), (8 , 0, 0, 8 , 0, 0), (8 , 0, 1, 8 , 0, 1), (8 , 31, 0, 8 , 31, 0), (8 , 31, 1, 8 , 31, 1), (9 , 0, 0, 9 , 0, 0), (9 , 0, 1, 9 , 0, 1), (9 , 31, 0, 9 , 31, 0), (9 , 31, 1, 9 , 31, 1), (10, 0, 0, 10, 0, 0), (10, 0, 1, 10, 0, 1), (10, 31, 0, 10, 31, 0), (10, 31, 1, 10, 31, 1), (11, 0, 0, 11, 0, 0), (11, 0, 1, 11, 0, 1), (11, 31, 0, 11, 31, 0), (11, 31, 1, 11, 31, 1), (12, 0, 0, 12, 0, 0), (12, 0, 1, 12, 0, 1), (12, 31, 0, 12, 31, 0), (12, 31, 1, 12, 31, 1), (13, 0, 0, 13, 0, 0), (13, 0, 1, 13, 0, 1), (13, 31, 0, 13, 31, 0), (13, 31, 1, 13, 31, 1), (14, 0, 0, 14, 0, 0), (14, 0, 1, 14, 0, 1), (14, 31, 0, 14, 31, 0), (14, 31, 1, 14, 31, 1), (15, 0, 0, 15, 0, 0), (15, 0, 1, 15, 0, 1), (15, 31, 0, 15, 31, 0), (15, 31, 1, 15, 31, 1), (16, 0, 0, 16, 0, 0), (16, 0, 1, 16, 0, 1), (16, 31, 0, 16, 31, 0), (16, 31, 1, 16, 31, 1), (17, 0, 0, 17, 0, 0), (17, 0, 1, 17, 0, 1), (17, 31, 0, 17, 31, 0), (17, 31, 1, 17, 31, 1), (18, 0, 0, 18, 0, 0), (18, 0, 1, 18, 0, 1), (18, 31, 0, 18, 31, 0), (18, 31, 1, 18, 31, 1), (19, 0, 0, 19, 0, 0), (19, 0, 1, 19, 0, 1), (19, 31, 0, 19, 31, 0), (19, 31, 1, 19, 31, 1), (20, 0, 0, 20, 0, 0), (20, 0, 1, 20, 0, 1), (20, 31, 0, 20, 31, 0), (20, 31, 1, 20, 31, 1), (21, 0, 0, 21, 0, 0), (21, 0, 1, 21, 0, 1), (21, 31, 0, 21, 31, 0), (21, 31, 1, 21, 31, 1), (22, 0, 0, 22, 0, 0), (22, 0, 1, 22, 0, 1), (22, 31, 0, 22, 31, 0), (22, 31, 1, 22, 31, 1), (23, 0, 0, 23, 0, 0), (23, 0, 1, 23, 0, 1), (23, 31, 0, 23, 31, 0), (23, 31, 1, 23, 31, 1), (24, 0, 0, 24, 0, 0), (24, 0, 1, 24, 0, 1), (24, 31, 0, 24, 31, 0), (24, 31, 1, 24, 31, 1) ] } # This dictionary maps package variants to a table of pin names and their # corresponding grid location (x, y, block). This is most easily found through # the package view in iCEcube2 by hovering the mouse over each pin. pinloc_db = { "1k-swg16tr": [ ( "A2", 6, 17, 1), ( "A4", 2, 17, 0), ( "B1", 11, 17, 1), ( "B2", 0, 8, 1), ( "B3", 0, 9, 0), ( "C1", 12, 0, 0), ( "C2", 11, 0, 1), ( "C3", 11, 0, 0), ( "D1", 12, 0, 1), ( "D3", 6, 0, 1), ], "1k-cm36": [ ( "A1", 0, 13, 0), ( "A2", 4, 17, 1), ( "A3", 7, 17, 0), ( "B1", 0, 13, 1), ( "B3", 6, 17, 1), ( "B4", 13, 9, 0), ( "B5", 13, 11, 0), ( "B6", 13, 11, 1), ( "C1", 0, 9, 0), ( "C2", 0, 9, 1), ( "C3", 4, 17, 0), ( "C5", 13, 8, 1), ( "C6", 13, 12, 0), ( "D1", 0, 8, 1), ( "D5", 12, 0, 1), ( "D6", 13, 6, 0), ( "E1", 0, 8, 0), ( "E2", 6, 0, 0), ( "E3", 10, 0, 0), ( "E4", 11, 0, 0), ( "E5", 12, 0, 0), ( "E6", 13, 4, 1), ( "F2", 6, 0, 1), ( "F3", 10, 0, 1), ( "F5", 11, 0, 1), ], "1k-cm49": [ ( "A1", 0, 11, 1), ( "A2", 3, 17, 1), ( "A3", 8, 17, 1), ( "A4", 8, 17, 0), ( "A5", 9, 17, 1), ( "A6", 10, 17, 0), ( "A7", 9, 17, 0), ( "B1", 0, 11, 0), ( "B2", 0, 13, 0), ( "B3", 4, 17, 0), ( "B4", 6, 17, 1), ( "C1", 0, 5, 0), ( "C2", 0, 13, 1), ( "C4", 7, 17, 0), ( "C5", 13, 12, 0), ( "C6", 13, 11, 1), ( "C7", 13, 11, 0), ( "D1", 0, 5, 1), ( "D2", 0, 9, 0), ( "D3", 0, 9, 1), ( "D4", 4, 17, 1), ( "D6", 13, 8, 1), ( "D7", 13, 9, 0), ( "E2", 0, 8, 1), ( "E6", 12, 0, 1), ( "E7", 13, 4, 1), ( "F2", 0, 8, 0), ( "F3", 6, 0, 0), ( "F4", 10, 0, 0), ( "F5", 11, 0, 0), ( "F6", 12, 0, 0), ( "F7", 13, 6, 0), ( "G3", 6, 0, 1), ( "G4", 10, 0, 1), ( "G6", 11, 0, 1), ], "1k-cm81": [ ( "A1", 1, 17, 1), ( "A2", 4, 17, 0), ( "A3", 5, 17, 0), ( "A4", 6, 17, 0), ( "A6", 8, 17, 1), ( "A7", 9, 17, 0), ( "A8", 10, 17, 0), ( "A9", 13, 14, 1), ( "B1", 0, 13, 0), ( "B2", 0, 14, 0), ( "B3", 2, 17, 1), ( "B4", 4, 17, 1), ( "B5", 8, 17, 0), ( "B6", 9, 17, 1), ( "B7", 10, 17, 1), ( "B8", 11, 17, 0), ( "B9", 13, 11, 1), ( "C1", 0, 13, 1), ( "C2", 0, 14, 1), ( "C3", 0, 12, 1), ( "C4", 6, 17, 1), ( "C5", 7, 17, 0), ( "C9", 13, 12, 0), ( "D1", 0, 11, 1), ( "D2", 0, 12, 0), ( "D3", 0, 9, 0), ( "D5", 3, 17, 1), ( "D6", 13, 6, 0), ( "D7", 13, 7, 0), ( "D8", 13, 9, 0), ( "D9", 13, 11, 0), ( "E1", 0, 10, 1), ( "E2", 0, 10, 0), ( "E3", 0, 8, 1), ( "E4", 0, 11, 0), ( "E5", 5, 17, 1), ( "E7", 13, 6, 1), ( "E8", 13, 8, 1), ( "F1", 0, 8, 0), ( "F3", 0, 9, 1), ( "F7", 12, 0, 1), ( "F8", 13, 4, 0), ( "G1", 0, 5, 1), ( "G3", 0, 5, 0), ( "G4", 6, 0, 0), ( "G5", 10, 0, 0), ( "G6", 11, 0, 0), ( "G7", 12, 0, 0), ( "G8", 13, 4, 1), ( "G9", 13, 2, 1), ( "H1", 2, 0, 0), ( "H4", 6, 0, 1), ( "H5", 10, 0, 1), ( "H7", 11, 0, 1), ( "H9", 13, 2, 0), ( "J1", 3, 0, 0), ( "J2", 2, 0, 1), ( "J3", 3, 0, 1), ( "J4", 5, 0, 0), ( "J6", 7, 0, 0), ( "J7", 9, 0, 1), ( "J8", 13, 1, 0), ( "J9", 13, 1, 1), ], "1k-cm121": [ ( "A1", 0, 14, 0), ( "A2", 2, 17, 1), ( "A3", 3, 17, 0), ( "A5", 5, 17, 1), ( "A7", 8, 17, 0), ( "A8", 10, 17, 1), ( "A9", 11, 17, 0), ("A10", 12, 17, 0), ("A11", 13, 15, 0), ( "B1", 0, 13, 0), ( "B2", 1, 17, 1), ( "B3", 2, 17, 0), ( "B4", 3, 17, 1), ( "B5", 4, 17, 1), ( "B7", 9, 17, 0), ( "B8", 11, 17, 1), ( "B9", 12, 17, 1), ("B10", 13, 15, 1), ("B11", 13, 14, 1), ( "C1", 0, 12, 0), ( "C2", 0, 13, 1), ( "C3", 0, 14, 1), ( "C4", 1, 17, 0), ( "C5", 4, 17, 0), ( "C6", 7, 17, 1), ( "C7", 8, 17, 1), ( "C8", 9, 17, 1), ( "C9", 10, 17, 0), ("C10", 13, 14, 0), ("C11", 13, 13, 1), ( "D1", 0, 11, 0), ( "D2", 0, 12, 1), ( "D3", 0, 11, 1), ( "D4", 0, 10, 1), ( "D5", 6, 17, 1), ( "D6", 7, 17, 0), ("D10", 13, 12, 1), ("D11", 13, 11, 1), ( "E2", 0, 10, 0), ( "E3", 0, 9, 1), ( "E4", 0, 9, 0), ( "E6", 5, 17, 0), ( "E7", 13, 12, 0), ( "E8", 13, 13, 0), ( "E9", 13, 9, 0), ("E10", 13, 9, 1), ( "F2", 0, 6, 0), ( "F3", 0, 5, 0), ( "F4", 0, 8, 1), ( "F5", 0, 8, 0), ( "F6", 6, 17, 0), ( "F8", 13, 11, 0), ( "F9", 13, 8, 1), ("F11", 13, 7, 1), ( "G2", 0, 5, 1), ( "G4", 0, 3, 0), ( "G8", 12, 0, 1), ( "G9", 13, 8, 0), ("G11", 13, 7, 0), ( "H1", 0, 6, 1), ( "H2", 0, 4, 1), ( "H4", 0, 2, 0), ( "H5", 6, 0, 0), ( "H6", 10, 0, 0), ( "H7", 11, 0, 0), ( "H8", 12, 0, 0), ( "H9", 13, 6, 1), ("H10", 13, 2, 1), ("H11", 13, 4, 1), ( "J1", 0, 4, 0), ( "J2", 1, 0, 1), ( "J5", 6, 0, 1), ( "J6", 10, 0, 1), ( "J8", 11, 0, 1), ("J10", 13, 2, 0), ("J11", 13, 6, 0), ( "K1", 0, 3, 1), ( "K2", 2, 0, 0), ( "K3", 2, 0, 1), ( "K4", 4, 0, 0), ( "K5", 5, 0, 0), ( "K7", 7, 0, 1), ( "K8", 9, 0, 0), ( "K9", 13, 1, 0), ("K10", 13, 1, 1), ("K11", 13, 3, 1), ( "L1", 0, 2, 1), ( "L2", 3, 0, 0), ( "L3", 3, 0, 1), ( "L4", 4, 0, 1), ( "L5", 7, 0, 0), ( "L7", 8, 0, 0), ( "L9", 8, 0, 1), ("L10", 9, 0, 1), ("L11", 13, 4, 0), ], "1k-cb81": [ ( "A2", 2, 17, 1), ( "A3", 3, 17, 1), ( "A4", 6, 17, 1), ( "A7", 11, 17, 0), ( "A8", 12, 17, 1), ( "B1", 0, 13, 1), ( "B2", 0, 14, 0), ( "B3", 0, 13, 0), ( "B4", 5, 17, 1), ( "B5", 8, 17, 1), ( "B6", 9, 17, 1), ( "B7", 11, 17, 1), ( "B8", 12, 17, 0), ( "C1", 0, 12, 0), ( "C2", 0, 10, 0), ( "C3", 0, 14, 1), ( "C4", 1, 17, 1), ( "C5", 8, 17, 0), ( "C6", 10, 17, 0), ( "C7", 13, 15, 0), ( "C8", 13, 15, 1), ( "C9", 13, 14, 1), ( "D1", 0, 9, 0), ( "D2", 0, 10, 1), ( "D3", 0, 12, 1), ( "D4", 5, 17, 0), ( "D5", 4, 17, 0), ( "D6", 7, 17, 0), ( "D7", 13, 13, 0), ( "D8", 13, 13, 1), ( "E1", 0, 8, 1), ( "E2", 0, 8, 0), ( "E3", 0, 9, 1), ( "E6", 10, 17, 1), ( "E7", 13, 12, 0), ( "E8", 13, 11, 0), ( "E9", 13, 11, 1), ( "F2", 0, 6, 1), ( "F3", 0, 6, 0), ( "F6", 13, 8, 0), ( "F7", 13, 9, 0), ( "F8", 13, 8, 1), ( "F9", 13, 7, 1), ( "G1", 0, 4, 1), ( "G2", 0, 2, 1), ( "G3", 3, 0, 1), ( "G4", 4, 0, 0), ( "G5", 10, 0, 0), ( "G6", 13, 4, 0), ( "G7", 13, 4, 1), ( "G8", 13, 6, 1), ( "G9", 13, 7, 0), ( "H2", 0, 4, 0), ( "H3", 2, 0, 1), ( "H4", 6, 0, 0), ( "H5", 10, 0, 1), ( "H7", 11, 0, 0), ( "H8", 12, 0, 1), ( "J2", 2, 0, 0), ( "J3", 6, 0, 1), ( "J7", 11, 0, 1), ( "J8", 12, 0, 0), ], "1k-cb121": [ ( "A2", 1, 17, 1), ( "A3", 2, 17, 0), ( "A4", 4, 17, 0), ( "A5", 3, 17, 1), ( "A6", 4, 17, 1), ( "A8", 10, 17, 0), ("A10", 12, 17, 1), ("A11", 13, 15, 0), ( "B1", 0, 14, 0), ( "B3", 1, 17, 0), ( "B4", 2, 17, 1), ( "B5", 3, 17, 0), ( "B8", 10, 17, 1), ( "B9", 12, 17, 0), ("B11", 13, 15, 1), ( "C1", 0, 14, 1), ( "C2", 0, 11, 1), ( "C3", 0, 13, 1), ( "C4", 0, 13, 0), ( "C5", 5, 17, 0), ( "C6", 7, 17, 0), ( "C7", 8, 17, 1), ( "C8", 11, 17, 0), ( "C9", 11, 17, 1), ("C11", 13, 14, 1), ( "D1", 0, 10, 1), ( "D2", 0, 11, 0), ( "D3", 0, 9, 0), ( "D4", 0, 12, 0), ( "D5", 5, 17, 1), ( "D6", 6, 17, 1), ( "D7", 8, 17, 0), ( "D8", 13, 12, 0), ( "D9", 13, 13, 0), ("D10", 13, 13, 1), ("D11", 13, 14, 0), ( "E2", 0, 10, 0), ( "E3", 0, 9, 1), ( "E4", 0, 12, 1), ( "E5", 6, 17, 0), ( "E6", 7, 17, 1), ( "E7", 9, 17, 0), ( "E8", 13, 11, 0), ( "E9", 13, 11, 1), ("E11", 13, 12, 1), ( "F2", 0, 6, 1), ( "F3", 0, 5, 1), ( "F4", 0, 8, 1), ( "F7", 9, 17, 1), ( "F8", 13, 8, 1), ( "F9", 13, 9, 0), ("F10", 13, 9, 1), ( "G1", 0, 6, 0), ( "G3", 0, 5, 0), ( "G4", 0, 8, 0), ( "G7", 13, 6, 1), ( "G8", 13, 7, 0), ( "G9", 13, 7, 1), ("G10", 13, 8, 0), ( "H1", 0, 3, 1), ( "H2", 0, 4, 1), ( "H3", 0, 4, 0), ( "H4", 4, 0, 0), ( "H5", 4, 0, 1), ( "H6", 10, 0, 0), ( "H7", 13, 4, 1), ( "H8", 13, 6, 0), ( "H9", 13, 4, 0), ("H10", 13, 3, 1), ("H11", 9, 0, 1), ( "J1", 0, 3, 0), ( "J2", 0, 2, 0), ( "J3", 0, 2, 1), ( "J4", 2, 0, 1), ( "J5", 3, 0, 0), ( "J6", 10, 0, 1), ( "J8", 11, 0, 0), ( "J9", 12, 0, 1), ("J11", 8, 0, 1), ( "K3", 1, 0, 0), ( "K4", 1, 0, 1), ( "K8", 11, 0, 1), ( "K9", 12, 0, 0), ("K11", 9, 0, 0), ( "L2", 2, 0, 0), ( "L3", 3, 0, 1), ( "L4", 5, 0, 0), ( "L5", 5, 0, 1), ( "L8", 7, 0, 0), ( "L9", 6, 0, 1), ("L10", 7, 0, 1), ("L11", 8, 0, 0), ], "1k-cb132": [ ( "A1", 1, 17, 1), ( "A2", 2, 17, 1), ( "A4", 4, 17, 0), ( "A5", 4, 17, 1), ( "A6", 6, 17, 1), ( "A7", 7, 17, 0), ("A10", 10, 17, 0), ("A12", 12, 17, 0), ( "B1", 0, 14, 1), ("B14", 13, 15, 0), ( "C1", 0, 14, 0), ( "C3", 0, 13, 1), ( "C4", 1, 17, 0), ( "C5", 3, 17, 0), ( "C6", 5, 17, 0), ( "C7", 6, 17, 0), ( "C8", 8, 17, 0), ( "C9", 9, 17, 0), ("C10", 11, 17, 0), ("C11", 11, 17, 1), ("C12", 12, 17, 1), ("C14", 13, 14, 0), ( "D1", 0, 11, 1), ( "D3", 0, 13, 0), ( "D4", 0, 12, 1), ( "D5", 2, 17, 0), ( "D6", 3, 17, 1), ( "D7", 5, 17, 1), ( "D8", 7, 17, 1), ( "D9", 8, 17, 1), ("D10", 9, 17, 1), ("D11", 10, 17, 1), ("D12", 13, 15, 1), ("D14", 13, 13, 1), ( "E1", 0, 11, 0), ( "E4", 0, 12, 0), ("E11", 13, 14, 1), ("E12", 13, 13, 0), ("E14", 13, 12, 0), ( "F3", 0, 10, 0), ( "F4", 0, 10, 1), ("F11", 13, 12, 1), ("F12", 13, 11, 1), ("F14", 13, 8, 1), ( "G1", 0, 8, 1), ( "G3", 0, 8, 0), ( "G4", 0, 6, 1), ("G11", 13, 11, 0), ("G12", 13, 9, 1), ("G14", 13, 9, 0), ( "H1", 0, 9, 0), ( "H3", 0, 9, 1), ( "H4", 0, 6, 0), ("H11", 13, 8, 0), ("H12", 13, 7, 1), ( "J1", 0, 5, 1), ( "J3", 0, 5, 0), ("J11", 13, 7, 0), ("J12", 13, 6, 1), ( "K3", 0, 3, 0), ( "K4", 0, 3, 1), ("K11", 13, 4, 1), ("K12", 13, 4, 0), ("K14", 13, 6, 0), ( "L1", 0, 2, 0), ( "L4", 1, 0, 1), ( "L5", 3, 0, 1), ( "L6", 4, 0, 1), ( "L7", 8, 0, 0), ( "L8", 9, 0, 0), ( "L9", 10, 0, 0), ("L12", 13, 2, 0), ("L14", 13, 3, 1), ( "M1", 0, 2, 1), ( "M3", 1, 0, 0), ( "M4", 3, 0, 0), ( "M6", 5, 0, 1), ( "M7", 6, 0, 0), ( "M8", 8, 0, 1), ( "M9", 9, 0, 1), ("M11", 11, 0, 0), ("M12", 13, 1, 0), ("N14", 13, 2, 1), ( "P2", 2, 0, 0), ( "P3", 2, 0, 1), ( "P4", 4, 0, 0), ( "P5", 5, 0, 0), ( "P7", 6, 0, 1), ( "P8", 7, 0, 0), ( "P9", 7, 0, 1), ("P10", 10, 0, 1), ("P11", 11, 0, 1), ("P12", 12, 0, 0), ("P13", 12, 0, 1), ("P14", 13, 1, 1), ], "1k-qn84": [ ( "A1", 0, 14, 0), ( "A2", 0, 13, 0), ( "A3", 0, 12, 0), ( "A4", 0, 11, 0), ( "A5", 0, 10, 0), ( "A8", 0, 9, 0), ( "A9", 0, 8, 1), ("A10", 0, 5, 1), ("A11", 0, 4, 0), ("A12", 0, 2, 0), ("A13", 4, 0, 0), ("A14", 6, 0, 1), ("A16", 6, 0, 0), ("A19", 9, 0, 1), ("A20", 10, 0, 1), ("A22", 11, 0, 1), ("A23", 12, 0, 0), ("A25", 13, 4, 0), ("A26", 13, 6, 0), ("A27", 13, 7, 1), ("A29", 13, 8, 1), ("A31", 13, 11, 1), ("A32", 13, 12, 1), ("A33", 13, 13, 1), ("A34", 13, 14, 0), ("A35", 13, 15, 0), ("A38", 11, 17, 0), ("A39", 10, 17, 0), ("A40", 9, 17, 0), ("A41", 8, 17, 0), ("A43", 7, 17, 0), ("A44", 6, 17, 0), ("A45", 5, 17, 0), ("A46", 4, 17, 0), ("A47", 3, 17, 0), ("A48", 1, 17, 1), ( "B1", 0, 13, 1), ( "B2", 0, 12, 1), ( "B3", 0, 11, 1), ( "B4", 0, 10, 1), ( "B5", 0, 9, 1), ( "B7", 0, 8, 0), ( "B8", 0, 5, 0), ( "B9", 0, 3, 0), ("B10", 5, 0, 0), ("B11", 5, 0, 1), ("B12", 7, 0, 0), ("B13", 8, 0, 0), ("B14", 9, 0, 0), ("B15", 10, 0, 0), ("B17", 11, 0, 0), ("B18", 12, 0, 1), ("B19", 13, 3, 1), ("B20", 13, 6, 1), ("B21", 13, 7, 0), ("B22", 13, 9, 0), ("B23", 13, 11, 0), ("B24", 13, 12, 0), ("B26", 13, 14, 1), ("B27", 13, 15, 1), ("B29", 10, 17, 1), ("B30", 9, 17, 1), ("B31", 8, 17, 1), ("B32", 6, 17, 1), ("B34", 4, 17, 1), ("B35", 3, 17, 1), ("B36", 2, 17, 1), ], "1k-tq144": [ ( "1", 0, 14, 1), ( "2", 0, 14, 0), ( "3", 0, 13, 1), ( "4", 0, 13, 0), ( "7", 0, 12, 1), ( "8", 0, 12, 0), ( "9", 0, 11, 1), ( "10", 0, 11, 0), ( "11", 0, 10, 1), ( "12", 0, 10, 0), ( "19", 0, 9, 1), ( "20", 0, 9, 0), ( "21", 0, 8, 1), ( "22", 0, 8, 0), ( "23", 0, 6, 1), ( "24", 0, 6, 0), ( "25", 0, 5, 1), ( "26", 0, 5, 0), ( "28", 0, 4, 1), ( "29", 0, 4, 0), ( "31", 0, 3, 1), ( "32", 0, 3, 0), ( "33", 0, 2, 1), ( "34", 0, 2, 0), ( "37", 1, 0, 0), ( "38", 1, 0, 1), ( "39", 2, 0, 0), ( "41", 2, 0, 1), ( "42", 3, 0, 0), ( "43", 3, 0, 1), ( "44", 4, 0, 0), ( "45", 4, 0, 1), ( "47", 5, 0, 0), ( "48", 5, 0, 1), ( "49", 6, 0, 1), ( "50", 7, 0, 0), ( "52", 6, 0, 0), ( "56", 7, 0, 1), ( "58", 8, 0, 0), ( "60", 8, 0, 1), ( "61", 9, 0, 0), ( "62", 9, 0, 1), ( "63", 10, 0, 0), ( "64", 10, 0, 1), ( "67", 11, 0, 0), ( "68", 11, 0, 1), ( "70", 12, 0, 0), ( "71", 12, 0, 1), ( "73", 13, 1, 0), ( "74", 13, 1, 1), ( "75", 13, 2, 0), ( "76", 13, 2, 1), ( "78", 13, 3, 1), ( "79", 13, 4, 0), ( "80", 13, 4, 1), ( "81", 13, 6, 0), ( "87", 13, 6, 1), ( "88", 13, 7, 0), ( "90", 13, 7, 1), ( "91", 13, 8, 0), ( "93", 13, 8, 1), ( "94", 13, 9, 0), ( "95", 13, 9, 1), ( "96", 13, 11, 0), ( "97", 13, 11, 1), ( "98", 13, 12, 0), ( "99", 13, 12, 1), ("101", 13, 13, 0), ("102", 13, 13, 1), ("104", 13, 14, 0), ("105", 13, 14, 1), ("106", 13, 15, 0), ("107", 13, 15, 1), ("112", 12, 17, 1), ("113", 12, 17, 0), ("114", 11, 17, 1), ("115", 11, 17, 0), ("116", 10, 17, 1), ("117", 10, 17, 0), ("118", 9, 17, 1), ("119", 9, 17, 0), ("120", 8, 17, 1), ("121", 8, 17, 0), ("122", 7, 17, 1), ("128", 7, 17, 0), ("129", 6, 17, 1), ("134", 5, 17, 1), ("135", 5, 17, 0), ("136", 4, 17, 1), ("137", 4, 17, 0), ("138", 3, 17, 1), ("139", 3, 17, 0), ("141", 2, 17, 1), ("142", 2, 17, 0), ("143", 1, 17, 1), ("144", 1, 17, 0), ], "1k-vq100": [ ( "1", 0, 14, 1), ( "2", 0, 14, 0), ( "3", 0, 13, 1), ( "4", 0, 13, 0), ( "7", 0, 12, 1), ( "8", 0, 12, 0), ( "9", 0, 10, 1), ( "10", 0, 10, 0), ( "12", 0, 9, 1), ( "13", 0, 9, 0), ( "15", 0, 8, 1), ( "16", 0, 8, 0), ( "18", 0, 6, 1), ( "19", 0, 6, 0), ( "20", 0, 4, 1), ( "21", 0, 4, 0), ( "24", 0, 2, 1), ( "25", 0, 2, 0), ( "26", 2, 0, 0), ( "27", 2, 0, 1), ( "28", 3, 0, 0), ( "29", 3, 0, 1), ( "30", 4, 0, 0), ( "33", 6, 0, 1), ( "34", 7, 0, 0), ( "36", 6, 0, 0), ( "37", 7, 0, 1), ( "40", 9, 0, 1), ( "41", 10, 0, 0), ( "42", 10, 0, 1), ( "45", 11, 0, 0), ( "46", 11, 0, 1), ( "48", 12, 0, 0), ( "49", 12, 0, 1), ( "51", 13, 3, 1), ( "52", 13, 4, 0), ( "53", 13, 4, 1), ( "54", 13, 6, 0), ( "56", 13, 6, 1), ( "57", 13, 7, 0), ( "59", 13, 7, 1), ( "60", 13, 8, 0), ( "62", 13, 8, 1), ( "63", 13, 9, 0), ( "64", 13, 11, 0), ( "65", 13, 11, 1), ( "66", 13, 12, 0), ( "68", 13, 13, 0), ( "69", 13, 13, 1), ( "71", 13, 14, 0), ( "72", 13, 14, 1), ( "73", 13, 15, 0), ( "74", 13, 15, 1), ( "78", 12, 17, 1), ( "79", 12, 17, 0), ( "80", 11, 17, 1), ( "81", 10, 17, 1), ( "82", 10, 17, 0), ( "83", 9, 17, 1), ( "85", 9, 17, 0), ( "86", 8, 17, 1), ( "87", 8, 17, 0), ( "89", 7, 17, 0), ( "90", 6, 17, 1), ( "91", 6, 17, 0), ( "93", 5, 17, 1), ( "94", 5, 17, 0), ( "95", 4, 17, 1), ( "96", 4, 17, 0), ( "97", 3, 17, 1), ( "99", 2, 17, 1), ("100", 1, 17, 1), ], "8k-cb132:4k": [ ( "A1", 2, 33, 0), ( "A2", 3, 33, 0), ( "A3", 3, 33, 1), ( "A4", 5, 33, 0), ( "A5", 10, 33, 1), ( "A6", 16, 33, 1), ( "A7", 17, 33, 0), ("A10", 25, 33, 0), ("A11", 26, 33, 0), ("A12", 30, 33, 1), ( "B1", 0, 30, 1), ("B14", 33, 28, 0), ( "C1", 0, 30, 0), ( "C3", 0, 27, 1), ( "C4", 4, 33, 0), ( "C5", 8, 33, 1), ( "C6", 11, 33, 1), ( "C7", 14, 33, 1), ( "C9", 20, 33, 1), ("C10", 22, 33, 1), ("C11", 28, 33, 1), ("C12", 29, 33, 1), ("C14", 33, 24, 1), ( "D1", 0, 25, 1), ( "D3", 0, 27, 0), ( "D4", 0, 22, 1), ( "D5", 9, 33, 0), ( "D6", 11, 33, 0), ( "D7", 13, 33, 1), ( "D9", 21, 33, 1), ("D10", 27, 33, 0), ("D11", 26, 33, 1), ("D12", 33, 27, 1), ("D14", 33, 23, 1), ( "E1", 0, 25, 0), ( "E4", 0, 22, 0), ("E11", 33, 20, 1), ("E12", 33, 21, 0), ("E14", 33, 21, 1), ( "F3", 0, 21, 0), ( "F4", 0, 21, 1), ("F11", 33, 19, 1), ("F12", 33, 15, 0), ("F14", 33, 16, 1), ( "G1", 0, 17, 0), ( "G3", 0, 17, 1), ( "G4", 0, 20, 0), ("G11", 33, 14, 1), ("G12", 33, 11, 0), ("G14", 33, 17, 0), ( "H1", 0, 16, 1), ( "H3", 0, 16, 0), ( "H4", 0, 20, 1), ("H11", 33, 10, 1), ("H12", 33, 6, 1), ( "J1", 0, 18, 0), ( "J3", 0, 18, 1), ("J11", 33, 6, 0), ("J12", 33, 5, 1), ( "K3", 0, 11, 1), ( "K4", 0, 11, 0), ("K11", 33, 4, 1), ("K12", 33, 4, 0), ("K14", 33, 5, 0), ( "L1", 0, 6, 1), ( "L4", 12, 0, 0), ( "L5", 11, 0, 1), ( "L6", 15, 0, 0), ( "L8", 20, 0, 1), ( "L9", 29, 0, 0), ("L12", 33, 2, 0), ("L14", 33, 3, 1), ( "M1", 0, 6, 0), ( "M3", 8, 0, 0), ( "M4", 7, 0, 1), ( "M6", 14, 0, 1), ( "M7", 15, 0, 1), ( "M9", 22, 0, 1), ("M11", 30, 0, 0), ("M12", 33, 1, 0), ( "N1", 0, 4, 1), ("N14", 33, 2, 1), ( "P1", 0, 4, 0), ( "P2", 4, 0, 0), ( "P3", 5, 0, 1), ( "P4", 12, 0, 1), ( "P5", 13, 0, 0), ( "P7", 16, 0, 1), ( "P8", 17, 0, 0), ( "P9", 21, 0, 1), ("P10", 29, 0, 1), ("P11", 30, 0, 1), ("P12", 31, 0, 0), ("P13", 31, 0, 1), ("P14", 33, 1, 1), ], "8k-tq144:4k": [ ( "1", 0, 30, 1), ( "2", 0, 30, 0), ( "3", 0, 28, 1), ( "4", 0, 28, 0), ( "7", 0, 27, 1), ( "8", 0, 27, 0), ( "9", 0, 25, 1), ( "10", 0, 25, 0), ( "11", 0, 22, 1), ( "12", 0, 22, 0), ( "15", 0, 20, 1), ( "16", 0, 20, 0), ( "17", 0, 18, 1), ( "18", 0, 18, 0), ( "19", 0, 17, 1), ( "20", 0, 17, 0), ( "21", 0, 16, 1), ( "22", 0, 16, 0), ( "23", 0, 12, 1), ( "24", 0, 12, 0), ( "25", 0, 11, 1), ( "26", 0, 11, 0), ( "28", 0, 6, 1), ( "29", 0, 6, 0), ( "31", 0, 5, 1), ( "32", 0, 5, 0), ( "33", 0, 4, 1), ( "34", 0, 4, 0), ( "37", 4, 0, 0), ( "38", 4, 0, 1), ( "39", 6, 0, 1), ( "41", 7, 0, 1), ( "42", 8, 0, 0), ( "43", 11, 0, 1), ( "44", 12, 0, 0), ( "45", 12, 0, 1), ( "47", 15, 0, 1), ( "48", 16, 0, 0), ( "49", 16, 0, 1), ( "52", 17, 0, 0), ( "55", 22, 0, 1), ( "56", 24, 0, 0), ( "60", 24, 0, 1), ( "61", 25, 0, 0), ( "62", 28, 0, 0), ( "63", 29, 0, 0), ( "64", 29, 0, 1), ( "67", 30, 0, 0), ( "68", 30, 0, 1), ( "70", 31, 0, 0), ( "71", 31, 0, 1), ( "73", 33, 1, 0), ( "74", 33, 1, 1), ( "75", 33, 2, 0), ( "76", 33, 2, 1), ( "78", 33, 3, 1), ( "79", 33, 4, 0), ( "80", 33, 4, 1), ( "81", 33, 5, 0), ( "82", 33, 5, 1), ( "83", 33, 6, 0), ( "84", 33, 6, 1), ( "85", 33, 10, 1), ( "87", 33, 14, 1), ( "88", 33, 15, 0), ( "90", 33, 15, 1), ( "91", 33, 16, 0), ( "93", 33, 16, 1), ( "94", 33, 17, 0), ( "95", 33, 19, 1), ( "96", 33, 20, 1), ( "97", 33, 21, 0), ( "98", 33, 21, 1), ( "99", 33, 23, 1), ("101", 33, 27, 1), ("102", 33, 28, 0), ("104", 33, 29, 1), ("105", 33, 30, 0), ("106", 33, 30, 1), ("107", 33, 31, 0), ("110", 31, 33, 1), ("112", 31, 33, 0), ("113", 30, 33, 1), ("114", 30, 33, 0), ("115", 29, 33, 1), ("116", 29, 33, 0), ("117", 28, 33, 1), ("118", 27, 33, 0), ("119", 26, 33, 1), ("120", 26, 33, 0), ("121", 25, 33, 0), ("122", 20, 33, 1), ("124", 20, 33, 0), ("125", 19, 33, 1), ("128", 17, 33, 0), ("129", 16, 33, 1), ("130", 11, 33, 1), ("134", 8, 33, 1), ("135", 8, 33, 0), ("136", 7, 33, 1), ("137", 7, 33, 0), ("138", 6, 33, 1), ("139", 6, 33, 0), ("141", 5, 33, 0), ("142", 4, 33, 1), ("143", 4, 33, 0), ("144", 3, 33, 1), ], "8k-cm81:4k": [ ( "A1", 2, 33, 1), ( "A2", 4, 33, 0), ( "A3", 6, 33, 0), ( "A4", 10, 33, 1), ( "A6", 23, 33, 0), ( "A7", 27, 33, 0), ( "A8", 28, 33, 1), ( "A9", 33, 4, 1), ( "B1", 0, 28, 1), ( "B2", 0, 30, 0), ( "B3", 5, 33, 1), ( "B4", 9, 33, 0), ( "B5", 21, 33, 1), ( "B6", 24, 33, 0), ( "B7", 25, 33, 1), ( "B8", 30, 33, 1), ( "B9", 33, 6, 1), ( "C1", 0, 28, 0), ( "C2", 0, 30, 1), ( "C3", 0, 23, 0), ( "C4", 16, 33, 1), ( "C5", 17, 33, 0), ( "C9", 33, 21, 1), ( "D1", 0, 20, 1), ( "D2", 0, 23, 1), ( "D3", 0, 17, 0), ( "D5", 8, 33, 1), ( "D6", 33, 4, 0), ( "D7", 33, 5, 0), ( "D8", 33, 17, 0), ( "D9", 33, 6, 0), ( "E1", 0, 20, 0), ( "E2", 0, 17, 1), ( "E3", 0, 16, 1), ( "E4", 0, 16, 0), ( "E5", 7, 33, 1), ( "E7", 33, 5, 1), ( "E8", 33, 16, 1), ( "F1", 0, 7, 1), ( "F3", 0, 7, 0), ( "F7", 31, 0, 1), ( "F8", 33, 3, 0), ( "G1", 0, 5, 0), ( "G2", 0, 3, 1), ( "G3", 0, 5, 1), ( "G4", 16, 0, 1), ( "G5", 29, 0, 0), ( "G6", 30, 0, 0), ( "G7", 31, 0, 0), ( "G8", 33, 3, 1), ( "G9", 33, 2, 1), ( "H1", 3, 0, 0), ( "H2", 0, 3, 0), ( "H4", 17, 0, 0), ( "H5", 29, 0, 1), ( "H7", 30, 0, 1), ( "H9", 33, 2, 0), ( "J1", 3, 0, 1), ( "J2", 4, 0, 0), ( "J3", 4, 0, 1), ( "J4", 11, 0, 0), ( "J8", 33, 1, 0), ( "J9", 33, 1, 1), ], "8k-cm121:4k": [ ( "A1", 2, 33, 0), ( "A2", 3, 33, 1), ( "A3", 3, 33, 0), ( "A4", 9, 33, 0), ( "A5", 11, 33, 0), ( "A6", 11, 33, 1), ( "A7", 19, 33, 1), ( "A8", 20, 33, 1), ( "A9", 26, 33, 1), ("A10", 30, 33, 1), ("A11", 31, 33, 1), ( "B1", 0, 30, 1), ( "B2", 0, 30, 0), ( "B3", 4, 33, 0), ( "B4", 5, 33, 0), ( "B5", 10, 33, 1), ( "B6", 16, 33, 1), ( "B7", 17, 33, 0), ( "B8", 27, 33, 0), ( "B9", 28, 33, 1), ("B11", 33, 28, 0), ( "C1", 0, 25, 0), ( "C2", 0, 25, 1), ( "C3", 0, 27, 0), ( "C4", 0, 27, 1), ( "C7", 20, 33, 0), ( "C8", 26, 33, 0), ( "C9", 29, 33, 1), ("C11", 33, 27, 1), ( "D1", 0, 22, 0), ( "D2", 0, 21, 1), ( "D3", 0, 21, 0), ( "D5", 8, 33, 1), ( "D7", 25, 33, 0), ( "D9", 33, 21, 0), ("D10", 33, 24, 1), ("D11", 33, 23, 1), ( "E1", 0, 22, 1), ( "E2", 0, 20, 1), ( "E3", 0, 20, 0), ( "E8", 33, 20, 1), ( "E9", 33, 19, 1), ("E10", 33, 17, 0), ("E11", 33, 21, 1), ( "F1", 0, 18, 1), ( "F2", 0, 18, 0), ( "F3", 0, 17, 0), ( "F4", 0, 17, 1), ( "F9", 33, 15, 0), ("F10", 33, 14, 1), ("F11", 33, 16, 1), ( "G1", 0, 16, 1), ( "G2", 0, 16, 0), ( "G3", 0, 12, 1), ( "G8", 33, 5, 1), ( "G9", 33, 10, 1), ("G10", 33, 6, 1), ("G11", 33, 11, 0), ( "H1", 0, 11, 1), ( "H2", 0, 11, 0), ( "H3", 0, 12, 0), ( "H7", 20, 0, 1), ( "H9", 29, 0, 1), ("H10", 33, 4, 1), ("H11", 33, 6, 0), ( "J1", 0, 6, 1), ( "J2", 0, 4, 0), ( "J3", 4, 0, 1), ( "J4", 8, 0, 0), ( "J5", 15, 0, 0), ( "J7", 20, 0, 0), ( "J8", 22, 0, 1), ( "J9", 30, 0, 1), ("J10", 33, 5, 0), ("J11", 33, 3, 1), ( "K1", 0, 6, 0), ( "K2", 0, 4, 1), ( "K3", 7, 0, 1), ( "K4", 12, 0, 1), ( "K5", 15, 0, 1), ( "K6", 17, 0, 0), ( "K7", 21, 0, 1), ( "K9", 30, 0, 0), ("K10", 31, 0, 1), ("K11", 33, 4, 0), ( "L1", 4, 0, 0), ( "L2", 6, 0, 1), ( "L3", 11, 0, 1), ( "L4", 12, 0, 0), ( "L5", 16, 0, 1), ( "L7", 24, 0, 0), ( "L8", 29, 0, 0), ("L10", 31, 0, 0), ], "8k-cm225:4k": [ ( "A1", 1, 33, 1), ( "A2", 3, 33, 1), ( "A5", 6, 33, 1), ( "A6", 11, 33, 0), ( "A7", 12, 33, 0), ( "A8", 17, 33, 1), ( "A9", 18, 33, 1), ("A11", 23, 33, 1), ("A15", 31, 33, 0), ( "B2", 2, 33, 1), ( "B3", 4, 33, 1), ( "B4", 5, 33, 1), ( "B5", 7, 33, 1), ( "B6", 10, 33, 0), ( "B7", 14, 33, 0), ( "B8", 19, 33, 1), ( "B9", 18, 33, 0), ("B10", 22, 33, 0), ("B11", 23, 33, 0), ("B12", 25, 33, 1), ("B13", 27, 33, 1), ("B14", 31, 33, 1), ("B15", 33, 31, 0), ( "C1", 0, 28, 0), ( "C3", 2, 33, 0), ( "C4", 3, 33, 0), ( "C5", 5, 33, 0), ( "C6", 13, 33, 0), ( "C7", 11, 33, 1), ( "C8", 19, 33, 0), ( "C9", 17, 33, 0), ("C10", 20, 33, 0), ("C11", 24, 33, 1), ("C12", 30, 33, 1), ("C13", 30, 33, 0), ("C14", 33, 30, 0), ( "D1", 0, 25, 0), ( "D2", 0, 24, 1), ( "D3", 0, 27, 0), ( "D4", 0, 30, 0), ( "D5", 4, 33, 0), ( "D6", 9, 33, 0), ( "D7", 10, 33, 1), ( "D8", 16, 33, 1), ( "D9", 26, 33, 1), ("D10", 25, 33, 0), ("D11", 28, 33, 1), ("D13", 33, 27, 1), ("D14", 33, 25, 0), ("D15", 33, 27, 0), ( "E2", 0, 24, 0), ( "E3", 0, 28, 1), ( "E4", 0, 30, 1), ( "E5", 0, 27, 1), ( "E6", 0, 25, 1), ( "E9", 26, 33, 0), ("E10", 27, 33, 0), ("E11", 29, 33, 1), ("E13", 33, 28, 0), ("E14", 33, 24, 0), ( "F1", 0, 20, 0), ( "F2", 0, 21, 0), ( "F3", 0, 21, 1), ( "F4", 0, 22, 0), ( "F5", 0, 22, 1), ( "F7", 8, 33, 1), ( "F9", 20, 33, 1), ("F11", 33, 24, 1), ("F12", 33, 23, 1), ("F13", 33, 23, 0), ("F14", 33, 21, 0), ("F15", 33, 22, 0), ( "G2", 0, 20, 1), ( "G4", 0, 17, 0), ( "G5", 0, 18, 1), ("G10", 33, 20, 1), ("G11", 33, 19, 1), ("G12", 33, 21, 1), ("G13", 33, 17, 0), ("G14", 33, 20, 0), ("G15", 33, 19, 0), ( "H1", 0, 16, 0), ( "H2", 0, 18, 0), ( "H3", 0, 14, 1), ( "H4", 0, 13, 1), ( "H5", 0, 16, 1), ( "H6", 0, 17, 1), ("H11", 33, 14, 1), ("H12", 33, 16, 1), ("H13", 33, 15, 1), ("H14", 33, 15, 0), ( "J1", 0, 13, 0), ( "J2", 0, 12, 0), ( "J3", 0, 14, 0), ( "J4", 0, 11, 1), ( "J5", 0, 12, 1), ("J10", 33, 5, 1), ("J11", 33, 10, 1), ("J12", 33, 6, 1), ("J14", 33, 14, 0), ("J15", 33, 13, 0), ( "K1", 0, 11, 0), ( "K4", 0, 4, 0), ( "K5", 0, 6, 1), ( "K9", 20, 0, 1), ("K11", 29, 0, 0), ("K12", 33, 4, 1), ("K13", 33, 5, 0), ("K15", 33, 9, 0), ( "L3", 0, 7, 1), ( "L4", 0, 3, 0), ( "L5", 4, 0, 0), ( "L6", 7, 0, 0), ( "L7", 12, 0, 0), ( "L9", 17, 0, 0), ("L10", 21, 0, 1), ("L11", 30, 0, 1), ("L12", 33, 3, 1), ("L13", 33, 6, 0), ( "M1", 0, 7, 0), ( "M2", 0, 6, 0), ( "M3", 0, 5, 0), ( "M4", 0, 3, 1), ( "M5", 6, 0, 0), ( "M6", 8, 0, 0), ( "M7", 13, 0, 1), ( "M8", 15, 0, 0), ( "M9", 19, 0, 1), ("M11", 30, 0, 0), ("M12", 31, 0, 1), ("M13", 33, 4, 0), ("M15", 33, 3, 0), ( "N2", 0, 5, 1), ( "N3", 2, 0, 0), ( "N4", 3, 0, 0), ( "N5", 9, 0, 1), ( "N6", 12, 0, 1), ( "N7", 16, 0, 1), ( "N9", 20, 0, 0), ("N10", 22, 0, 1), ("N12", 31, 0, 0), ( "P1", 0, 4, 1), ( "P2", 2, 0, 1), ( "P4", 7, 0, 1), ( "P5", 10, 0, 1), ( "P6", 14, 0, 1), ( "P7", 17, 0, 1), ( "P8", 19, 0, 0), ( "P9", 22, 0, 0), ("P10", 23, 0, 0), ("P11", 25, 0, 0), ("P12", 29, 0, 1), ("P13", 27, 0, 0), ("P14", 33, 2, 1), ("P15", 33, 1, 1), ( "R1", 3, 0, 1), ( "R2", 4, 0, 1), ( "R3", 6, 0, 1), ( "R4", 8, 0, 1), ( "R5", 11, 0, 1), ( "R6", 15, 0, 1), ( "R9", 21, 0, 0), ("R10", 24, 0, 0), ("R11", 26, 0, 0), ("R12", 28, 0, 0), ("R14", 33, 2, 0), ("R15", 33, 1, 0), ], "8k-cm81": [ ( "A1", 2, 33, 1), ( "A2", 4, 33, 0), ( "A3", 6, 33, 0), ( "A4", 10, 33, 1), ( "A6", 23, 33, 0), ( "A7", 27, 33, 0), ( "A8", 28, 33, 1), ( "A9", 33, 4, 1), ( "B1", 0, 28, 1), ( "B2", 0, 30, 0), ( "B3", 5, 33, 1), ( "B4", 9, 33, 0), ( "B5", 21, 33, 1), ( "B6", 24, 33, 0), ( "B7", 25, 33, 1), ( "B8", 30, 33, 1), ( "B9", 33, 6, 1), ( "C1", 0, 28, 0), ( "C2", 0, 30, 1), ( "C3", 0, 23, 0), ( "C4", 16, 33, 1), ( "C5", 17, 33, 0), ( "C9", 33, 21, 1), ( "D1", 0, 20, 1), ( "D2", 0, 23, 1), ( "D3", 0, 17, 0), ( "D5", 8, 33, 1), ( "D6", 33, 4, 0), ( "D7", 33, 5, 0), ( "D8", 33, 17, 0), ( "D9", 33, 6, 0), ( "E1", 0, 20, 0), ( "E2", 0, 17, 1), ( "E3", 0, 16, 1), ( "E4", 0, 16, 0), ( "E5", 7, 33, 1), ( "E7", 33, 5, 1), ( "E8", 33, 16, 1), ( "F1", 0, 7, 1), ( "F3", 0, 7, 0), ( "F7", 31, 0, 1), ( "F8", 33, 3, 0), ( "G1", 0, 5, 0), ( "G2", 0, 3, 1), ( "G3", 0, 5, 1), ( "G4", 16, 0, 1), ( "G5", 29, 0, 0), ( "G6", 30, 0, 0), ( "G7", 31, 0, 0), ( "G8", 33, 3, 1), ( "G9", 33, 2, 1), ( "H1", 3, 0, 0), ( "H2", 0, 3, 0), ( "H4", 17, 0, 0), ( "H5", 29, 0, 1), ( "H7", 30, 0, 1), ( "H9", 33, 2, 0), ( "J1", 3, 0, 1), ( "J2", 4, 0, 0), ( "J3", 4, 0, 1), ( "J4", 11, 0, 0), ( "J8", 33, 1, 0), ( "J9", 33, 1, 1), ], "8k-cm121": [ ( "A1", 2, 33, 0), ( "A2", 3, 33, 1), ( "A3", 3, 33, 0), ( "A4", 9, 33, 0), ( "A5", 11, 33, 0), ( "A6", 11, 33, 1), ( "A7", 19, 33, 1), ( "A8", 20, 33, 1), ( "A9", 26, 33, 1), ("A10", 30, 33, 1), ("A11", 31, 33, 1), ( "B1", 0, 30, 1), ( "B2", 0, 30, 0), ( "B3", 4, 33, 0), ( "B4", 5, 33, 0), ( "B5", 10, 33, 1), ( "B6", 16, 33, 1), ( "B7", 17, 33, 0), ( "B8", 27, 33, 0), ( "B9", 28, 33, 1), ("B11", 33, 28, 0), ( "C1", 0, 25, 0), ( "C2", 0, 25, 1), ( "C3", 0, 27, 0), ( "C4", 0, 27, 1), ( "C7", 20, 33, 0), ( "C8", 26, 33, 0), ( "C9", 29, 33, 1), ("C11", 33, 27, 1), ( "D1", 0, 22, 0), ( "D2", 0, 21, 1), ( "D3", 0, 21, 0), ( "D5", 8, 33, 1), ( "D7", 25, 33, 0), ( "D9", 33, 21, 0), ("D10", 33, 24, 1), ("D11", 33, 23, 1), ( "E1", 0, 22, 1), ( "E2", 0, 20, 1), ( "E3", 0, 20, 0), ( "E8", 33, 20, 1), ( "E9", 33, 19, 1), ("E10", 33, 17, 0), ("E11", 33, 21, 1), ( "F1", 0, 18, 1), ( "F2", 0, 18, 0), ( "F3", 0, 17, 0), ( "F4", 0, 17, 1), ( "F9", 33, 15, 0), ("F10", 33, 14, 1), ("F11", 33, 16, 1), ( "G1", 0, 16, 1), ( "G2", 0, 16, 0), ( "G3", 0, 12, 1), ( "G8", 33, 5, 1), ( "G9", 33, 10, 1), ("G10", 33, 6, 1), ("G11", 33, 11, 0), ( "H1", 0, 11, 1), ( "H2", 0, 11, 0), ( "H3", 0, 12, 0), ( "H7", 20, 0, 1), ( "H9", 29, 0, 1), ("H10", 33, 4, 1), ("H11", 33, 6, 0), ( "J1", 0, 6, 1), ( "J2", 0, 4, 0), ( "J3", 4, 0, 1), ( "J4", 8, 0, 0), ( "J5", 15, 0, 0), ( "J7", 20, 0, 0), ( "J8", 22, 0, 1), ( "J9", 30, 0, 1), ("J10", 33, 5, 0), ("J11", 33, 3, 1), ( "K1", 0, 6, 0), ( "K2", 0, 4, 1), ( "K3", 7, 0, 1), ( "K4", 12, 0, 1), ( "K5", 15, 0, 1), ( "K6", 17, 0, 0), ( "K7", 21, 0, 1), ( "K9", 30, 0, 0), ("K10", 31, 0, 1), ("K11", 33, 4, 0), ( "L1", 4, 0, 0), ( "L2", 6, 0, 1), ( "L3", 11, 0, 1), ( "L4", 12, 0, 0), ( "L5", 16, 0, 1), ( "L7", 24, 0, 0), ( "L8", 29, 0, 0), ("L10", 31, 0, 0), ], "8k-cm225": [ ( "A1", 1, 33, 1), ( "A2", 3, 33, 1), ( "A5", 6, 33, 1), ( "A6", 11, 33, 0), ( "A7", 12, 33, 0), ( "A8", 17, 33, 1), ( "A9", 18, 33, 1), ("A10", 21, 33, 0), ("A11", 23, 33, 1), ("A15", 31, 33, 0), ( "B1", 0, 31, 0), ( "B2", 2, 33, 1), ( "B3", 4, 33, 1), ( "B4", 5, 33, 1), ( "B5", 7, 33, 1), ( "B6", 10, 33, 0), ( "B7", 14, 33, 0), ( "B8", 19, 33, 1), ( "B9", 18, 33, 0), ("B10", 22, 33, 0), ("B11", 23, 33, 0), ("B12", 25, 33, 1), ("B13", 27, 33, 1), ("B14", 31, 33, 1), ("B15", 33, 31, 0), ( "C1", 0, 28, 0), ( "C2", 0, 31, 1), ( "C3", 2, 33, 0), ( "C4", 3, 33, 0), ( "C5", 5, 33, 0), ( "C6", 13, 33, 0), ( "C7", 11, 33, 1), ( "C8", 19, 33, 0), ( "C9", 17, 33, 0), ("C10", 20, 33, 0), ("C11", 24, 33, 1), ("C12", 30, 33, 1), ("C13", 30, 33, 0), ("C14", 33, 30, 0), ( "D1", 0, 25, 0), ( "D2", 0, 24, 1), ( "D3", 0, 27, 0), ( "D4", 0, 30, 0), ( "D5", 4, 33, 0), ( "D6", 9, 33, 0), ( "D7", 10, 33, 1), ( "D8", 16, 33, 1), ( "D9", 26, 33, 1), ("D10", 25, 33, 0), ("D11", 28, 33, 1), ("D13", 33, 27, 1), ("D14", 33, 25, 0), ("D15", 33, 27, 0), ( "E2", 0, 24, 0), ( "E3", 0, 28, 1), ( "E4", 0, 30, 1), ( "E5", 0, 27, 1), ( "E6", 0, 25, 1), ( "E9", 26, 33, 0), ("E10", 27, 33, 0), ("E11", 29, 33, 1), ("E13", 33, 28, 0), ("E14", 33, 24, 0), ( "F1", 0, 20, 0), ( "F2", 0, 21, 0), ( "F3", 0, 21, 1), ( "F4", 0, 22, 0), ( "F5", 0, 22, 1), ( "F7", 8, 33, 1), ( "F9", 20, 33, 1), ("F11", 33, 24, 1), ("F12", 33, 23, 1), ("F13", 33, 23, 0), ("F14", 33, 21, 0), ("F15", 33, 22, 0), ( "G1", 0, 19, 0), ( "G2", 0, 20, 1), ( "G3", 0, 19, 1), ( "G4", 0, 17, 0), ( "G5", 0, 18, 1), ("G10", 33, 20, 1), ("G11", 33, 19, 1), ("G12", 33, 21, 1), ("G13", 33, 17, 0), ("G14", 33, 20, 0), ("G15", 33, 19, 0), ( "H1", 0, 16, 0), ( "H2", 0, 18, 0), ( "H3", 0, 14, 1), ( "H4", 0, 13, 1), ( "H5", 0, 16, 1), ( "H6", 0, 17, 1), ("H11", 33, 14, 1), ("H12", 33, 16, 1), ("H13", 33, 15, 1), ("H14", 33, 15, 0), ( "J1", 0, 13, 0), ( "J2", 0, 12, 0), ( "J3", 0, 14, 0), ( "J4", 0, 11, 1), ( "J5", 0, 12, 1), ("J10", 33, 5, 1), ("J11", 33, 10, 1), ("J12", 33, 6, 1), ("J13", 33, 11, 0), ("J14", 33, 14, 0), ("J15", 33, 13, 0), ( "K1", 0, 11, 0), ( "K3", 0, 9, 1), ( "K4", 0, 4, 0), ( "K5", 0, 6, 1), ( "K9", 20, 0, 1), ("K11", 29, 0, 0), ("K12", 33, 4, 1), ("K13", 33, 5, 0), ("K14", 33, 12, 0), ("K15", 33, 9, 0), ( "L1", 0, 9, 0), ( "L3", 0, 7, 1), ( "L4", 0, 3, 0), ( "L5", 4, 0, 0), ( "L6", 7, 0, 0), ( "L7", 12, 0, 0), ( "L9", 17, 0, 0), ("L10", 21, 0, 1), ("L11", 30, 0, 1), ("L12", 33, 3, 1), ("L13", 33, 6, 0), ("L14", 33, 7, 0), ( "M1", 0, 7, 0), ( "M2", 0, 6, 0), ( "M3", 0, 5, 0), ( "M4", 0, 3, 1), ( "M5", 6, 0, 0), ( "M6", 8, 0, 0), ( "M7", 13, 0, 1), ( "M8", 15, 0, 0), ( "M9", 19, 0, 1), ("M11", 30, 0, 0), ("M12", 31, 0, 1), ("M13", 33, 4, 0), ("M14", 33, 8, 0), ("M15", 33, 3, 0), ( "N2", 0, 5, 1), ( "N3", 2, 0, 0), ( "N4", 3, 0, 0), ( "N5", 9, 0, 1), ( "N6", 12, 0, 1), ( "N7", 16, 0, 1), ( "N9", 20, 0, 0), ("N10", 22, 0, 1), ("N12", 31, 0, 0), ( "P1", 0, 4, 1), ( "P2", 2, 0, 1), ( "P4", 7, 0, 1), ( "P5", 10, 0, 1), ( "P6", 14, 0, 1), ( "P7", 17, 0, 1), ( "P8", 19, 0, 0), ( "P9", 22, 0, 0), ("P10", 23, 0, 0), ("P11", 25, 0, 0), ("P12", 29, 0, 1), ("P13", 27, 0, 0), ("P14", 33, 2, 1), ("P15", 33, 1, 1), ( "R1", 3, 0, 1), ( "R2", 4, 0, 1), ( "R3", 6, 0, 1), ( "R4", 8, 0, 1), ( "R5", 11, 0, 1), ( "R6", 15, 0, 1), ( "R9", 21, 0, 0), ("R10", 24, 0, 0), ("R11", 26, 0, 0), ("R12", 28, 0, 0), ("R14", 33, 2, 0), ("R15", 33, 1, 0), ], "8k-cb132": [ ( "A1", 2, 33, 0), ( "A2", 3, 33, 0), ( "A3", 3, 33, 1), ( "A4", 5, 33, 0), ( "A5", 10, 33, 1), ( "A6", 16, 33, 1), ( "A7", 17, 33, 0), ("A10", 25, 33, 0), ("A11", 26, 33, 0), ("A12", 30, 33, 1), ( "B1", 0, 30, 1), ("B14", 33, 28, 0), ( "C1", 0, 30, 0), ( "C3", 0, 27, 1), ( "C4", 4, 33, 0), ( "C5", 8, 33, 1), ( "C6", 11, 33, 1), ( "C7", 14, 33, 1), ( "C9", 20, 33, 1), ("C10", 22, 33, 1), ("C11", 28, 33, 1), ("C12", 29, 33, 1), ("C14", 33, 24, 1), ( "D1", 0, 25, 1), ( "D3", 0, 27, 0), ( "D4", 0, 22, 1), ( "D5", 9, 33, 0), ( "D6", 11, 33, 0), ( "D7", 13, 33, 1), ( "D9", 21, 33, 1), ("D10", 27, 33, 0), ("D11", 26, 33, 1), ("D12", 33, 27, 1), ("D14", 33, 23, 1), ( "E1", 0, 25, 0), ( "E4", 0, 22, 0), ("E11", 33, 20, 1), ("E12", 33, 21, 0), ("E14", 33, 21, 1), ( "F3", 0, 21, 0), ( "F4", 0, 21, 1), ("F11", 33, 19, 1), ("F12", 33, 15, 0), ("F14", 33, 16, 1), ( "G1", 0, 17, 0), ( "G3", 0, 17, 1), ( "G4", 0, 20, 0), ("G11", 33, 14, 1), ("G12", 33, 11, 0), ("G14", 33, 17, 0), ( "H1", 0, 16, 1), ( "H3", 0, 16, 0), ( "H4", 0, 20, 1), ("H11", 33, 10, 1), ("H12", 33, 6, 1), ( "J1", 0, 18, 0), ( "J3", 0, 18, 1), ("J11", 33, 6, 0), ("J12", 33, 5, 1), ( "K3", 0, 11, 1), ( "K4", 0, 11, 0), ("K11", 33, 4, 1), ("K12", 33, 4, 0), ("K14", 33, 5, 0), ( "L1", 0, 6, 1), ( "L4", 12, 0, 0), ( "L5", 11, 0, 1), ( "L6", 15, 0, 0), ( "L8", 20, 0, 1), ( "L9", 29, 0, 0), ("L12", 33, 2, 0), ("L14", 33, 3, 1), ( "M1", 0, 6, 0), ( "M3", 8, 0, 0), ( "M4", 7, 0, 1), ( "M6", 14, 0, 1), ( "M7", 15, 0, 1), ( "M9", 22, 0, 1), ("M11", 30, 0, 0), ("M12", 33, 1, 0), ( "N1", 0, 4, 1), ("N14", 33, 2, 1), ( "P1", 0, 4, 0), ( "P2", 4, 0, 0), ( "P3", 5, 0, 1), ( "P4", 12, 0, 1), ( "P5", 13, 0, 0), ( "P7", 16, 0, 1), ( "P8", 17, 0, 0), ( "P9", 21, 0, 1), ("P10", 29, 0, 1), ("P11", 30, 0, 1), ("P12", 31, 0, 0), ("P13", 31, 0, 1), ("P14", 33, 1, 1), ], "8k-ct256": [ ( "A1", 4, 33, 1), ( "A2", 5, 33, 1), ( "A5", 8, 33, 0), ( "A6", 9, 33, 0), ( "A7", 12, 33, 0), ( "A9", 18, 33, 1), ("A10", 22, 33, 1), ("A11", 22, 33, 0), ("A15", 27, 33, 0), ("A16", 27, 33, 1), ( "B1", 0, 30, 0), ( "B2", 0, 31, 0), ( "B3", 3, 33, 0), ( "B4", 6, 33, 1), ( "B5", 7, 33, 1), ( "B6", 10, 33, 1), ( "B7", 11, 33, 0), ( "B8", 13, 33, 0), ( "B9", 16, 33, 0), ("B10", 24, 33, 0), ("B11", 23, 33, 1), ("B12", 24, 33, 1), ("B13", 26, 33, 1), ("B14", 30, 33, 0), ("B15", 31, 33, 0), ("B16", 33, 30, 0), ( "C1", 0, 28, 1), ( "C2", 0, 28, 0), ( "C3", 1, 33, 0), ( "C4", 3, 33, 1), ( "C5", 4, 33, 0), ( "C6", 10, 33, 0), ( "C7", 11, 33, 1), ( "C8", 17, 33, 0), ( "C9", 20, 33, 0), ("C10", 23, 33, 0), ("C11", 25, 33, 1), ("C12", 29, 33, 1), ("C13", 28, 33, 1), ("C14", 31, 33, 1), ("C16", 33, 28, 0), ( "D1", 0, 25, 0), ( "D2", 0, 27, 0), ( "D3", 1, 33, 1), ( "D4", 2, 33, 1), ( "D5", 5, 33, 0), ( "D6", 8, 33, 1), ( "D7", 9, 33, 1), ( "D8", 14, 33, 1), ( "D9", 19, 33, 0), ("D10", 20, 33, 1), ("D11", 25, 33, 0), ("D13", 30, 33, 1), ("D14", 33, 31, 0), ("D15", 33, 26, 0), ("D16", 33, 24, 0), ( "E2", 0, 23, 0), ( "E3", 0, 24, 0), ( "E4", 0, 31, 1), ( "E5", 2, 33, 0), ( "E6", 7, 33, 0), ( "E9", 19, 33, 1), ("E10", 26, 33, 0), ("E11", 29, 33, 0), ("E13", 33, 30, 1), ("E14", 33, 27, 1), ("E16", 33, 23, 0), ( "F1", 0, 20, 0), ( "F2", 0, 21, 0), ( "F3", 0, 22, 0), ( "F4", 0, 27, 1), ( "F5", 0, 30, 1), ( "F7", 16, 33, 1), ( "F9", 17, 33, 1), ("F11", 33, 26, 1), ("F12", 33, 25, 1), ("F13", 33, 28, 1), ("F14", 33, 25, 0), ("F15", 33, 22, 0), ("F16", 33, 21, 0), ( "G1", 0, 17, 0), ( "G2", 0, 19, 0), ( "G3", 0, 22, 1), ( "G4", 0, 24, 1), ( "G5", 0, 25, 1), ("G10", 33, 20, 1), ("G11", 33, 21, 1), ("G12", 33, 24, 1), ("G13", 33, 23, 1), ("G14", 33, 22, 1), ("G15", 33, 20, 0), ("G16", 33, 19, 0), ( "H1", 0, 16, 0), ( "H2", 0, 18, 0), ( "H3", 0, 21, 1), ( "H4", 0, 19, 1), ( "H5", 0, 23, 1), ( "H6", 0, 20, 1), ("H11", 33, 16, 1), ("H12", 33, 19, 1), ("H13", 33, 16, 0), ("H14", 33, 17, 1), ("H16", 33, 17, 0), ( "J1", 0, 14, 0), ( "J2", 0, 14, 1), ( "J3", 0, 16, 1), ( "J4", 0, 18, 1), ( "J5", 0, 17, 1), ("J10", 33, 7, 1), ("J11", 33, 9, 1), ("J12", 33, 14, 1), ("J13", 33, 15, 0), ("J14", 33, 13, 1), ("J15", 33, 11, 1), ("J16", 33, 15, 1), ( "K1", 0, 13, 1), ( "K3", 0, 13, 0), ( "K4", 0, 11, 1), ( "K5", 0, 9, 1), ( "K9", 17, 0, 0), ("K11", 29, 0, 0), ("K12", 33, 6, 1), ("K13", 33, 10, 1), ("K14", 33, 11, 0), ("K15", 33, 12, 0), ("K16", 33, 13, 0), ( "L1", 0, 12, 0), ( "L3", 0, 10, 0), ( "L4", 0, 12, 1), ( "L5", 0, 6, 1), ( "L6", 0, 10, 1), ( "L7", 0, 8, 1), ( "L9", 13, 0, 0), ("L10", 19, 0, 1), ("L11", 26, 0, 1), ("L12", 33, 4, 1), ("L13", 33, 5, 1), ("L14", 33, 6, 0), ("L16", 33, 10, 0), ( "M1", 0, 11, 0), ( "M2", 0, 9, 0), ( "M3", 0, 7, 0), ( "M4", 0, 5, 0), ( "M5", 0, 4, 0), ( "M6", 0, 7, 1), ( "M7", 8, 0, 0), ( "M8", 10, 0, 0), ( "M9", 16, 0, 0), ("M11", 23, 0, 1), ("M12", 27, 0, 1), ("M13", 33, 3, 1), ("M14", 33, 4, 0), ("M15", 33, 8, 0), ("M16", 33, 7, 0), ( "N2", 0, 8, 0), ( "N3", 0, 6, 0), ( "N4", 0, 3, 0), ( "N5", 4, 0, 0), ( "N6", 2, 0, 0), ( "N7", 9, 0, 0), ( "N9", 15, 0, 0), ("N10", 20, 0, 1), ("N12", 26, 0, 0), ("N16", 33, 5, 0), ( "P1", 0, 5, 1), ( "P2", 0, 4, 1), ( "P4", 3, 0, 0), ( "P5", 5, 0, 0), ( "P6", 9, 0, 1), ( "P7", 14, 0, 1), ( "P8", 12, 0, 0), ( "P9", 17, 0, 1), ("P10", 20, 0, 0), ("P11", 30, 0, 1), ("P12", 30, 0, 0), ("P13", 29, 0, 1), ("P14", 33, 2, 0), ("P15", 33, 2, 1), ("P16", 33, 3, 0), ( "R1", 0, 3, 1), ( "R2", 3, 0, 1), ( "R3", 5, 0, 1), ( "R4", 7, 0, 1), ( "R5", 6, 0, 0), ( "R6", 11, 0, 1), ( "R9", 16, 0, 1), ("R10", 19, 0, 0), ("R11", 31, 0, 0), ("R12", 31, 0, 1), ("R14", 33, 1, 0), ("R15", 33, 1, 1), ("R16", 28, 0, 0), ( "T1", 2, 0, 1), ( "T2", 4, 0, 1), ( "T3", 6, 0, 1), ( "T5", 10, 0, 1), ( "T6", 12, 0, 1), ( "T7", 13, 0, 1), ( "T8", 14, 0, 0), ( "T9", 15, 0, 1), ("T10", 21, 0, 0), ("T11", 21, 0, 1), ("T13", 24, 0, 0), ("T14", 23, 0, 0), ("T15", 22, 0, 1), ("T16", 27, 0, 0), ], "384-qn32": [ ( "1", 0, 7, 0), ( "2", 0, 7, 1), ( "5", 0, 5, 1), ( "6", 0, 5, 0), ( "7", 0, 4, 0), ( "8", 0, 4, 1), ( "12", 5, 0, 0), ( "13", 5, 0, 1), ( "14", 6, 0, 1), ( "15", 6, 0, 0), ( "18", 7, 4, 0), ( "19", 7, 4, 1), ( "20", 7, 5, 0), ( "22", 7, 6, 0), ( "23", 7, 6, 1), ( "26", 6, 9, 0), ( "27", 5, 9, 0), ( "29", 4, 9, 0), ( "30", 3, 9, 1), ( "31", 2, 9, 0), ( "32", 2, 9, 1), ], "384-cm36": [ ( "A1", 0, 7, 0), ( "A2", 2, 9, 1), ( "A3", 3, 9, 1), ( "B1", 0, 7, 1), ( "B3", 4, 9, 0), ( "B4", 7, 5, 0), ( "B5", 7, 5, 1), ( "B6", 7, 6, 0), ( "C1", 0, 5, 0), ( "C2", 0, 5, 1), ( "C3", 2, 9, 0), ( "C5", 7, 4, 1), ( "C6", 7, 6, 1), ( "D1", 0, 4, 1), ( "D5", 6, 0, 1), ( "D6", 7, 4, 0), ( "E1", 0, 4, 0), ( "E2", 3, 0, 1), ( "E3", 4, 0, 0), ( "E4", 5, 0, 0), ( "E5", 6, 0, 0), ( "E6", 7, 3, 1), ( "F2", 3, 0, 0), ( "F3", 4, 0, 1), ( "F5", 5, 0, 1), ], "384-cm49": [ ( "A1", 0, 7, 1), ( "A2", 2, 9, 1), ( "A3", 3, 9, 0), ( "A4", 4, 9, 1), ( "A5", 5, 9, 0), ( "A6", 6, 9, 0), ( "A7", 6, 9, 1), ( "B1", 0, 7, 0), ( "B2", 0, 6, 0), ( "B3", 2, 9, 0), ( "B4", 4, 9, 0), ( "C1", 0, 5, 1), ( "C2", 0, 6, 1), ( "C4", 3, 9, 1), ( "C5", 7, 6, 1), ( "C6", 7, 5, 1), ( "C7", 7, 6, 0), ( "D1", 0, 4, 0), ( "D2", 0, 5, 0), ( "D3", 0, 2, 0), ( "D4", 5, 9, 1), ( "D6", 7, 4, 1), ( "D7", 7, 5, 0), ( "E2", 0, 4, 1), ( "E6", 6, 0, 1), ( "E7", 7, 4, 0), ( "F1", 0, 2, 1), ( "F2", 0, 1, 0), ( "F3", 3, 0, 1), ( "F4", 4, 0, 0), ( "F5", 5, 0, 0), ( "F6", 6, 0, 0), ( "F7", 7, 3, 1), ( "G1", 0, 1, 1), ( "G3", 3, 0, 0), ( "G4", 4, 0, 1), ( "G6", 5, 0, 1), ], "5k-sg48": [ ( "2", 8, 0, 0), ( "3", 9, 0, 1), ( "4", 9, 0, 0), ( "6", 13, 0, 1), ( "9", 15, 0, 0), ( "10", 16, 0, 0), ( "11", 17, 0, 0), ( "12", 18, 0, 0), ( "13", 19, 0, 0), ( "14", 23, 0, 0), ( "15", 24, 0, 0), ( "16", 24, 0, 1), ( "17", 23, 0, 1), ( "18", 22, 0, 1), ( "19", 21, 0, 1), ( "20", 19, 0, 1), ( "21", 18, 0, 1), ( "23", 19, 31, 0), ( "25", 19, 31, 1), ( "26", 18, 31, 0), ( "27", 18, 31, 1), ( "28", 17, 31, 0), ( "31", 16, 31, 1), ( "32", 16, 31, 0), ( "34", 13, 31, 1), ( "35", 12, 31, 1), ( "36", 9, 31, 1), ( "37", 13, 31, 0), ( "38", 8, 31, 1), ( "39", 4, 31, 0), ( "40", 5, 31, 0), ( "41", 6, 31, 0), ( "42", 8, 31, 0), ( "43", 9, 31, 0), ( "44", 6, 0, 1), ( "45", 7, 0, 1), ( "46", 5, 0, 0), ( "47", 6, 0, 0), ( "48", 7, 0, 0), ], } iotile_full_db = parse_db(iceboxdb.database_io_txt) logictile_db = parse_db(iceboxdb.database_logic_txt, "1k") logictile_5k_db = parse_db(iceboxdb.database_logic_txt, "5k") logictile_8k_db = parse_db(iceboxdb.database_logic_txt, "8k") logictile_384_db = parse_db(iceboxdb.database_logic_txt, "384") rambtile_db = parse_db(iceboxdb.database_ramb_txt, "1k") ramttile_db = parse_db(iceboxdb.database_ramt_txt, "1k") rambtile_5k_db = parse_db(iceboxdb.database_ramb_5k_txt, "5k") ramttile_5k_db = parse_db(iceboxdb.database_ramt_5k_txt, "5k") rambtile_8k_db = parse_db(iceboxdb.database_ramb_8k_txt, "8k") ramttile_8k_db = parse_db(iceboxdb.database_ramt_8k_txt, "8k") iotile_l_db = list() iotile_r_db = list() iotile_t_db = list() iotile_b_db = list() for entry in iotile_full_db: if entry[1] == "buffer" and entry[2].startswith("IO_L."): new_entry = entry[:] new_entry[2] = new_entry[2][5:] iotile_l_db.append(new_entry) elif entry[1] == "buffer" and entry[2].startswith("IO_R."): new_entry = entry[:] new_entry[2] = new_entry[2][5:] iotile_r_db.append(new_entry) elif entry[1] == "buffer" and entry[2].startswith("IO_T."): new_entry = entry[:] new_entry[2] = new_entry[2][5:] iotile_t_db.append(new_entry) elif entry[1] == "buffer" and entry[2].startswith("IO_B."): new_entry = entry[:] new_entry[2] = new_entry[2][5:] iotile_b_db.append(new_entry) else: iotile_l_db.append(entry) iotile_r_db.append(entry) iotile_t_db.append(entry) iotile_b_db.append(entry) logictile_db.append([["B1[49]"], "buffer", "carry_in", "carry_in_mux"]) logictile_db.append([["B1[50]"], "CarryInSet"]) logictile_8k_db.append([["B1[49]"], "buffer", "carry_in", "carry_in_mux"]) logictile_8k_db.append([["B1[50]"], "CarryInSet"]) logictile_384_db.append([["B1[49]"], "buffer", "carry_in", "carry_in_mux"]) logictile_384_db.append([["B1[50]"], "CarryInSet"]) for db in [iotile_l_db, iotile_r_db, iotile_t_db, iotile_b_db, logictile_db, logictile_5k_db, logictile_8k_db, logictile_384_db, rambtile_db, ramttile_db, rambtile_5k_db, ramttile_5k_db, rambtile_8k_db, ramttile_8k_db]: for entry in db: if entry[1] in ("buffer", "routing"): entry[2] = netname_normalize(entry[2], ramb=(db == rambtile_db), ramt=(db == ramttile_db), ramb_8k=(db in (rambtile_8k_db, rambtile_5k_db)), ramt_8k=(db in (ramttile_8k_db, ramttile_5k_db))) entry[3] = netname_normalize(entry[3], ramb=(db == rambtile_db), ramt=(db == ramttile_db), ramb_8k=(db in (rambtile_8k_db, rambtile_5k_db)), ramt_8k=(db in (ramttile_8k_db, ramttile_5k_db))) unique_entries = dict() while db: entry = db.pop() key = " ".join(entry[1:]) + str(entry) unique_entries[key] = entry for key in sorted(unique_entries): db.append(unique_entries[key]) if __name__ == "__main__": run_checks()
#! /usr/bin/env python # --*-- coding:utf-8 --*-- import os import sys import time import json import traceback from bs4 import BeautifulSoup import requests import logging import logging.config from config.setting import * def get_datatime(value): return time.strftime(TIME_FORMAT, time.localtime(value)) def get_now(): return time.strftime('%Y-%m-%dT%H:%M:%S',time.localtime(time.time())) def get_unixtime_range(): start = int(time.mktime(time.strptime(get_now(), '%Y-%m-%dT%H:%M:%S'))) - 120 end = start + unix_end_offset_seconds return start, end def datetime_timestamp(datetime): return int(time.mktime(time.strptime(datetime, '%Y-%m-%d %H:%M:%S'))) def get_clickid(content): soup = BeautifulSoup(content) for link in soup.find_all('a'): return link.get('href').split('=')[1] def getLogger(): logging.config.fileConfig(os.path.join(os.path.split(sys.path[0])[0],'config/logging.conf')) logger = logging.getLogger("eredar") return logger def getDruidDetailResult(start_time, end_time, transaction_id_list): logger = getLogger() param = param_template % (start_time, end_time, transaction_id_list) if "'" in param: param = param.replace("'",'"') geturl = query_url + param try: r = requests.get(geturl) data = json.loads(r.text).get('data').get('data') if len(data[1:]) == len(offer_aff_combination) * cycletimes: logger.info('get detail result success, druid detail data count equal to (offer_aff_combination * cycletimes)') else: logger.info('get detail result failed, druid detail data count not equal to (offer_aff_combination * cycletimes)') return data[0], data[1:] except Exception as ex: logger.error('get druid detail result failed: {0}'.format(ex)) sys.exit() else: return None def getResponse(param): url = query_url + param try: r = requests.get(url) except Exception as ex: traceback.print_exc() else: return r.text def getTaskFlag(): return 'tf{0}'.format(int(time.time())) def unicode2str(unicodeList): strList = list() if unicodeList: for u in unicodeList: if not isinstance(u, basestring): strList.append(u) else: strList.append(u.encode()) return tuple(strList) def getVaildColumn(column): if isinstance(column, list): columnString = ','.join(column) return '({0})'.format(columnString) if __name__ == '__main__': print get_unixtime_range() add detail data check rule when get druid detail result #! /usr/bin/env python # --*-- coding:utf-8 --*-- import os import sys import time import json import traceback from bs4 import BeautifulSoup import requests import logging import logging.config from config.setting import * def get_datatime(value): return time.strftime(TIME_FORMAT, time.localtime(value)) def get_now(): return time.strftime('%Y-%m-%dT%H:%M:%S',time.localtime(time.time())) def get_unixtime_range(): start = int(time.mktime(time.strptime(get_now(), '%Y-%m-%dT%H:%M:%S'))) - 120 end = start + unix_end_offset_seconds return start, end def datetime_timestamp(datetime): return int(time.mktime(time.strptime(datetime, '%Y-%m-%d %H:%M:%S'))) def get_clickid(content): soup = BeautifulSoup(content) for link in soup.find_all('a'): return link.get('href').split('=')[1] def getLogger(): logging.config.fileConfig(os.path.join(os.path.split(sys.path[0])[0],'config/logging.conf')) logger = logging.getLogger("eredar") return logger def getDruidDetailResult(start_time, end_time, transaction_id_list): logger = getLogger() param = param_template % (start_time, end_time, transaction_id_list) if "'" in param: param = param.replace("'",'"') geturl = query_url + param try: r = requests.get(geturl) data = json.loads(r.text).get('data').get('data') if len(data[1:]) == len(offer_aff_combination) * cycletimes: logger.info('get detail result success, druid detail data count equal to (offer_aff_combination * cycletimes)') else: logger.info('get detail result failed, druid detail data count not equal to (offer_aff_combination * cycletimes)') sys.exit() return data[0], data[1:] except Exception as ex: logger.error('get druid detail result failed: {0}'.format(ex)) sys.exit() else: return None def getResponse(param): url = query_url + param try: r = requests.get(url) except Exception as ex: traceback.print_exc() else: return r.text def getTaskFlag(): return 'tf{0}'.format(int(time.time())) def unicode2str(unicodeList): strList = list() if unicodeList: for u in unicodeList: if not isinstance(u, basestring): strList.append(u) else: strList.append(u.encode()) return tuple(strList) def getVaildColumn(column): if isinstance(column, list): columnString = ','.join(column) return '({0})'.format(columnString) if __name__ == '__main__': print get_unixtime_range()
#!/usr/bin/python import sys import subprocess import os import shutil SPACING = " " * 30 command_list = { "satoshi": ( "MISC", "Convert Bitcoins into Satoshis.", """\ Usage: sx satoshi BTC Convert Bitcoins into Satoshis.\ """ ), "btc": ( "MISC", "Convert Satoshis into Bitcoins.", """\ Usage: sx btc SATOSHIS Convert Satoshis into Bitcoins.\ """ ), "showscript": ( "TRANSACTION PARSING", "Show the details of a raw script.", """\ Usage: sx showscript Show the details of a raw script.\ """ ), "scripthash": ( "MULTISIG ADDRESSES", "Create BIP 16 script hash address from raw script hex.", """\ Usage: sx scripthash Create BIP 16 script hash address from raw script hex (from STDIN). EXAMPLE: # generate an address for 2-of-3 multisig transactions for n in 1 2 3; do echo 'b220b5bd2909df1d74b71c9e664233bf' | sx genpriv $n > key${n}; done sx rawscript 2 [ $(cat key1 | sx pubkey) ] [ $(cat key2 | sx pubkey) ] [ $(cat key3 | sx pubkey) ] 3 checkmultisig | sx scripthash 33opBmv3oJTXu6rxtzsr571SL2Srtw9Cg8 """ ), "rawscript": ( "CREATE TRANSACTIONS", "Create the raw hex representation from a script.", """\ Usage: sx rawscript [ARGS]... Create the raw hex representation from a script.\ EXAMPLE: $ sx rawscript dup # translate a single opcode just for demonstration, see OP_DUP in https://en.bitcoin.it/wik 76 """ ), "initchain": ( "MISC", "Initialize a new blockchain.", """\ Usage: sx initchain DIRECTORY Initialize a new blockchain.\ """ ), "wallet": ( "MISC", "Experimental command line wallet.", """\ Usage: sx wallet SEED This is an experimental prototype.\ """ ), "monitor": ( "BLOCKCHAIN WATCHING", "Monitor an address.", """\ Usage: sx monitor ADDRESS Monitor an address.\ """ ), "validaddr": ( "FORMAT", "Validate an address.", """\ Usage: sx validaddr ADDRESS Validate an address.\ """ ), "validtx": ( "BLOCKCHAIN QUERIES", "Validate a transaction.", """\ Usage: sx validtx FILENAME Query blockchain whether transaction has been confirmed.\ """ ), "pubkey": ( "LOOSE KEYS AND ADDRESSES", "See the public part of a private key.", """\ Usage: sx pubkey Read private key from STDIN and output the public key.\ """ ), "addr": ( "LOOSE KEYS AND ADDRESSES", "See Bitcoin address of a private key.", """\ Usage: sx addr Read private key from STDIN and output Bitcoin address.\ """ ), "ripemd-hash": ( "FORMAT", "RIPEMD hash data from STDIN.", """\ Usage: sx ripemd-hash RIPEMD hash data from STDIN.\ """ ), "wrap": ( "FORMAT", "Adds version byte and checksum to hexstring.", """\ Usage: sx wrap HEXSTRING VERSION_BYTE <or> echo HEXSTRING | sx wrap VERSION_BYTE Adds version byte and checksum to hexstring.\ """ ), "unwrap": ( "FORMAT", "Validates checksum and recovers version byte and original data from hexstring.", """\ Usage: sx wrap HEXSTRING VERSION_BYTE <or> echo HEXSTRING | sx wrap VERSION_BYTE Validates checksum and recovers version byte and original data from hexstring.\ """ ), "base58-decode": ( "FORMAT", "Convert from base58 to hex", """\ Usage: sx base58-decode B58STRING <or> echo B58STRING | sx base58-decode Convert from base58 to hex.\ """ ), "base58-encode": ( "FORMAT", "Convert from hex to base58", """\ Usage: sx base58-encode HEXSTRING <or> echo HEXSTRING | sx base58-encode Convert from hex to base58.\ """ ), "base58check-decode": ( "FORMAT", "Convert from base58check to hex", """\ Usage: sx base58check-decode B58STRING <or> echo B58STRING | sx base58check-decode Convert from base58check to hex.\ """ ), "base58check-encode": ( "FORMAT", "Convert from hex to base58check", """\ Usage: sx base58check-encode HEXSTRING <or> echo HEXSTRING | sx base58check-encode Convert from hex to base58check.\ """ ), "sendtx-obelisk": ( "BLOCKCHAIN UPDATES", "Send tx to obelisk server.", """\ Usage: sx sendtx-obelisk FILENAME Broadcast the transaction to an obelisk server for the network. $ sx sendtx-obelisk txfile.tx \ """ ), "sendtx-p2p": ( "BLOCKCHAIN UPDATES", "Send tx to bitcoin network.", """\ Usage: sx sendtx-p2p FILENAME Broadcast the transaction to the Bitcoin network. $ sx sendtx-p2p txfile.tx \ """ ), "sendtx-bci": ( "BLOCKCHAIN UPDATES", "Send tx to blockchain.info/pushtx.", """\ Usage: sx bci-push-tx FILENAME Push tx to blockchain.info/pushtx. $ sx sendtx-bci txfile.tx \ """ ), "blke-fetch-transaction": ( "BLOCKCHAIN QUERIES (blockexplorer.com)", "Fetches a transaction from blockexplorer.com", """\ Usage: sx blke-fetch-transaction HASH Fetches a transaction from blockexplorer.com $ sx blke-fetch-transaction HASH \ """ ), "genpriv": ( "DETERMINISTIC KEYS AND ADDRESSES", "Generate a private key deterministically from a seed.", """\ Usage: sx genpriv N [CHANGE] Generate private keys from a wallet seed. $ cat wallet.seed | sx genpriv 0 5Jmb4EYzEqj63rkPwADFY7WyGV2kga3YB1HfDAzg9dHNG57NMPu $ cat wallet.seed | sx genpriv 1 5KjCYpPyxU2e88S57b1naKUsJ1JNjCudkFSQPxqcYyBYgzzahNe \ """ ), "genpub": ( "DETERMINISTIC KEYS AND ADDRESSES", "Generate a public key deterministically from a wallet\n" + SPACING + "seed or master public key.", """\ Usage: sx genpub N [CHANGE] Generate public key from a wallet seed or master public key. $ cat wallet.seed | sx genpub 0 040a053d0a42d58b7e34346daae9d40ce33fad5d65bbaa6c615a2b76447734b2c712b5d45de839b2e5e7ac00201cbea3d2d376cfcc7a3f3f508f1e6761f6c271bf \ """ ), "genaddr": ( "DETERMINISTIC KEYS AND ADDRESSES", "Generate a Bitcoin address deterministically from a wallet\n" + SPACING + "seed or master public key.", """\ Usage: sx genaddr N [CHANGE] Generate Bitcoin addresses from a wallet seed or master public key. $ cat wallet.seed | sx genaddr 0 1a4b47AC4ydSnAAcTNH1qozHq2pwJb644 \ """ ), "qrcode": ( "MISC", "Generate Bitcoin QR codes offline.", """\ Usage: sx qrcode Make sure you have the program 'qrencode' installed first. $ sudo apt-get install qrencode $ sx qrcode 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe qrcode.png \ """ ), "fetch-block-header": ( "BLOCKCHAIN QUERIES", "Fetch raw block header.", """\ Usage: sx fetch-block-header [HASH] [HEIGHT] The fetch-block-header tool uses a network connection to make requests against the load balancer backend.\ """ ), "fetch-last-height": ( "BLOCKCHAIN QUERIES", "Fetch the last block height.", """\ Usage: sx fetch-last-height The fetch-last-height tool uses a network connection to make requests against the load balancer backend.\ """ ), "bci-fetch-last-height": ( "BLOCKCHAIN QUERIES (blockchain.info)", "Fetch the last block height using blockchain.info.", """\ Usage: sx bci-fetch-last-height Fetch the last block height using blockchain.info.\ """ ), "fetch-transaction": ( "BLOCKCHAIN QUERIES", "Fetch a raw transaction using a network connection to make requests against the obelisk load balancer backend.", """\ Fetch a raw transaction using a network connection to make requests against the obelisk load balancer backend. Usage: sx fetch-transaction HASH EXAMPLE: $ sx fetch-transaction 69735d70ada1be32ff39b49c6fc2390b03e9d5eed8918ed10fe42c8cbabf62d4 # fetches raw data \ """ ), "fetch-transaction-index": ( "BLOCKCHAIN QUERIES", "Fetch block height and index in block of transaction.", """\ Usage: sx fetch-transaction-index HASH The fetch-transaction-index tool uses a network connection to make requests against the load balancer backend.\ """ ), "balance": ( "BLOCKCHAIN QUERIES", "Show balance of a Bitcoin address in satoshis.", """\ Usage: sx balance [-j] ADDRESS1 [ADDRESS2...] The balance tool uses a network connection to make requests against the load balancer backend. -j, --json Enable json parseable output. Example: $ echo 134HfD2fdeBTohfx8YANxEpsYXsv5UoWyz | sx balance Address: 134HfD2fdeBTohfx8YANxEpsYXsv5UoWyz Paid balance: 0 Pending balance: 0 Total received: 100000 \ """ ), "history": ( "BLOCKCHAIN QUERIES", "Get list of output points, values, and their spends for an\n" + SPACING + "address. grep can filter for just unspent outputs which can\n" + SPACING + "be fed into mktx.", """\ Usage: sx history [-j] ADDRESS1 [ADDRESS2...] The history tool uses a network connection to make requests against the load balancer backend. -j, --json Enable json parseable output. Example: $ echo 134HfD2fdeBTohfx8YANxEpsYXsv5UoWyz | sx history Address: 134HfD2fdeBTohfx8YANxEpsYXsv5UoWyz output: 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:1 output_height: 247683 value: 100000 spend: b7354b8b9cc9a856aedaa349cffa289ae9917771f4e06b2386636b3c073df1b5:0 spend_height: 247742 \ """ ), "bci-history": ( "BLOCKCHAIN QUERIES (blockchain.info)", "Get list of output points, values, and their spends\n" + SPACING + "from blockchain.info", """\ Usage: sx bci-history SATOSHIS Get list of output points, values and spends using blockchain.info.\ """ ), "get-utxo": ( "BLOCKCHAIN QUERIES", "Get enough unspent transaction outputs from a given set of\n" + SPACING + "addresses to pay a given number of satoshis", """\ Usage: sx get-utxo ADDRESS1 ADDRESS2... SATOSHIS Get enough unspent transaction outputs from a given set of addresses to pay a given number of satoshis\ """ ), "get-pubkey": ( "LOOSE KEYS AND ADDRESSES", "Get the pubkey of an address if available", """\ Usage: sx get-pubkey ADDRESS Get the pubkey of an address if available\ """ ), "mktx": ( "CREATE TRANSACTIONS", "Create an unsigned tx.", """\ Usage: sx mktx FILENAME [-i TXHASH:INDEX]... [-o ADDRESS:VALUE] [-o HEXSCRIPT:VALUE] -i, --input TXHASH:INDEX Add input to transaction. -o, --output ADDRESS:VALUE or HEXSCRIPT:VALUE Add output to transaction. Construct the transaction: $ sx mktx txfile.tx -i 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:1 -o 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe:90000 FILENAME denotes the output file. If FILENAME is - (a single dash), then output is written to stdout. The VALUE field is in Satoshis.\ """ ), "secret-to-wif": ( "STEALTH", "Convert a secret exponent value to Wallet. Import. Format.", """\ Usage: echo SECRET | sx secret-to-wif \ """ ), "mpk": ( "DETERMINISTIC KEYS AND ADDRESSES", "Extract a master public key from a deterministic wallet seed.", """\ Usage: sx mpk Extract a master public key from a deterministic wallet seed. $ sx newseed > wallet.seed $ cat wallet.seed b220b5bd2909df1d74b71c9e664233bf $ cat wallet.seed | sx mpk > master_public.key \ """ ), "newkey": ( "LOOSE KEYS AND ADDRESSES", "Create a new private key.", """\ Usage: sx newkey $ sx newkey 5KPFsatiYrJcvCSRrDbtx61822vZjeGGGx3wu38pQDHRF8eVJ8H \ """ ), "newseed": ( "DETERMINISTIC KEYS AND ADDRESSES", "Create a new deterministic wallet seed.", """\ Usage: sx newseed $ sx newseed b220b5bd2909df1d74b71c9e664233bf \ """ ), "sendtx-node": ( "BLOCKCHAIN UPDATES", "Send transaction to a single node.", """\ Usage: sx sendtx-node FILENAME [HOST] [PORT] HOST and PORT default to localhost:8333. Send transaction to one Bitcoin node on localhost port 4009: $ sx sendtx-node txfile.tx localhost 4009 \ """ ), "showblkhead": ( "MISC", "Show the details of a block header.", """\ Usage: sx showblkhead FILENAME 'showblkhead' allows inspecting of block headers. $ sx showblkhead headerfile.blk hash: 4d25b18ed094ad68f75f21692d8540f45ceb90b240a521b8f191e95d8b6b8bb0 version: 1 locktime: 0 Input: previous output: 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:0 script: sequence: 4294967295 Output: value: 90000 script: dup hash160 [ 18c0bd8d1818f1bf99cb1df2269c645318ef7b73 ] equalverify checksig address: 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe \ """ ), "showtx": ( "TRANSACTION PARSING", "Show the details of a transaction.", """\ Usage: sx showtx [-j] FILENAME 'showtx' allows inspecting of tx files. -j, --json Enable json parseable output. Example: $ sx fetch-transaction cd484f683bc99c94948613a7f7254880e9c98cd74f2760a2d2c4e372fda1bc6a | sx showtx hash: cd484f683bc99c94948613a7f7254880e9c98cd74f2760a2d2c4e372fda1bc6a version: 1 locktime: 0 Input: previous output: f97367c5dc9e521a4c541327cbff69d118e35a2d0b67f91eb7771741a6374b20:0 script: [ 3046022100f63b1109e1b04c0a4b5230e6f6c75f5e2a10c16d022cdf93de9b3cc946e6e24a022100ae3da40f05504521f2f3557e736a2d1724d6d1d8c18b66a64990bf1afee78dba01 ] [ 028a2adb719bbf7e9cf0cb868d4f30b10551f2a4402eb2ece9b177b49e68e90511 ] sequence: 4294967295 address: 1NYMePixLjAATLaz55vN7FfTLUfFB23Tt Output: value: 2676400 script: dup hash160 [ 6ff00bd374abb3a3f19d1576bb36520b2cb15e2d ] equalverify checksig address: 1BCsZziw8Q1sMhxr2DjAR7Rmt1qQvYwXSU Output: value: 1000000 script: hash160 [ 0db1635fe975792a9a7b6f2d4061b730478dc6b9 ] equal address: 32wRDBezxnazSBxMrMqLWqD1ajwEqnDnMc \ """ ), "decode-addr": ( "FORMAT", "Decode an address to its internal RIPEMD representation.", """\ Usage: sx decode-addr ADDRESS Decode an address to its internal RIPEMD representation.\ """), "embed-addr": ( "FORMAT", "Generate an address used for embedding record of data into the blockchain.", """\ Usage: sx embed-addr Generate an address used for embedding record of data into the blockchain. Example: $ cat my_sculpture.jpg | sx embed-addr 1N9v8AKBqst9MNceV3gLmFKsgkKv1bZcBU Now send some Bitcoin to that address and it'll be embedded in the blockchain as a record of the data passed in. \ """), "encode-addr": ( "FORMAT", "Encode an address to base58check form.", """\ Usage: sx encode-addr HASH [VERSION] Encode an address to base58check form.\ """), "validsig": ( "VALIDATE", "Validate a transaction input's signature.", """\ Usage: sx validsig FILENAME INDEX SCRIPT_CODE SIGNATURE Validate a transaction input's signature.\ """), "brainwallet": ( "BRAINWALLET", "Make a private key from a brainwallet", """\ Usage: sx brainwallet password sx brainwallet username password sx brainwallet password --algo slowsha sx brainwallet username password --algo slowsha Make a private key from a brainwallet.\ """ ), "set-input": ( "CREATE TRANSACTIONS", "Set a transaction input.", """\ Usage: sx set-input TXFILENAME INPUTINDEX SIGNATURE_AND_PUBKEY_SCRIPT Set a transaction input. See sx help sign-input for an example.\ """), "sign-input": ( "CREATE TRANSACTIONS", "Sign a transaction input.", """\ Usage: cat secret.key | sx sign-input FILENAME INDEX PREVOUT_SCRIPT Sign a transaction input. Note how the input script in the following transaction is empty. $ sx mktx txfile.tx -i 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:0 -o 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe:90000 $ sx showtx txfile.tx hash: 4d25b18ed094ad68f75f21692d8540f45ceb90b240a521b8f191e95d8b6b8bb0 version: 1 locktime: 0 Input: previous output: 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:0 script: sequence: 4294967295 Output: value: 90000 script: dup hash160 [ 18c0bd8d1818f1bf99cb1df2269c645318ef7b73 ] equalverify checksig address: 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe We will now sign the first input using our private key. $ echo '5KPFsatiYrJcvCSRrDbtx61822vZjeGGGx3wu38pQDHRF8eVJ8H' > private.key $ DECODED_ADDR=$(cat private.key | sx addr | sx decode-addr) $ PREVOUT_SCRIPT=$(sx rawscript dup hash160 [ $DECODED_ADDR ] equalverify checksig) $ SIGNATURE=$(cat private.key | sx sign-input txfile.tx 0 $PREVOUT_SCRIPT) $ SIGNATURE_AND_PUBKEY_SCRIPT=$(sx rawscript [ $SIGNATURE ] [ $(cat private.key | sx pubkey) ]) $ sx set-input txfile.tx 0 $SIGNATURE_AND_PUBKEY_SCRIPT > txfile.tx.signed # the first input has index 0 Note how the input script in the following transaction is now filled. $ cat txfile.tx.signed | sx showtx hash: cc5650c69173e7607c095200f4ff36265f9fbb45e112b60cd467d696b2724488 version: 1 locktime: 0 Input: previous output: 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:0 script: [ 3045022100b778f7fb270b751491ba7e935a6978eaea2a44795b3f6636ea583939697b1ca102203ce47d3ecb0b7e832114e88e549fce476d4ea120ca1e60c508fe8083889a9cba01 ] [ 04c40cbd64c9c608df2c9730f49b0888c4db1c436e\ 8b2b74aead6c6afbd10428c0adb73f303ae1682415253f4411777224ab477ad098347ddb7e0b94d49261e613 ] sequence: 4294967295 address: 1MyKMeDsom7rYcp69KpbKn4DcyuvLMkLYJ Output: value: 90000 script: dup hash160 [ 18c0bd8d1818f1bf99cb1df2269c645318ef7b73 ] equalverify checksig address: 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe Now the input script is prepared, and the transaction is signed. It can be sent by $ sx broadcast-tx txfile.tx.signed \ """ ), "mnemonic": ( "BRAINWALLET", "Work with Electrum compatible mnemonics (12 words wallet seed).", """\ Usage: sx mnemonic Electrum compatible 12 word seeds. $ echo 148f0a1d77e20dbaee3ff920ca40240d | sx mnemonic people blonde admit dart couple different truth common alas stumble time cookie $ echo "people blonde admit dart couple different truth common alas stumble time cookie" | sx mnemonic 148f0a1d77e20dbaee3ff920ca40240d \ """ ), "watchtx": ( "BLOCKCHAIN WATCHING", "Watch transactions from the network searching for a certain hash.", """\ Usage: sx watchtx [TXHASH]... Watch transactions from the network searching for a certain hash.\ """ ), "stealth-new": ( "STEALTH", "Generate a new master stealth secret.", """\ Usage: sx stealth-new Generate a new stealth secret.\ """ ), "stealth-recv": ( "STEALTH", "Regenerate the secret from your master secret and provided nonce.", """\ Usage: sx stealth-recv SECRET NONCE Regenerate the secret from your master secret and provided nonce.\ """ ), "stealth-send": ( "STEALTH", "Generate a new sending address and a stealth nonce.", """\ Usage: sx stealth-send PUBKEY Generate a new sending address and a stealth nonce.\ """ ), } def display_usage(): print "Usage: sx COMMAND [ARGS]..." print print " -c, --config Specify a config file" print print "The sx commands are:" print categorised = {} for cmd in sorted(command_list.iterkeys()): category = command_list[cmd][0] if category not in categorised: categorised[category] = [] short_desc = command_list[cmd][1] line = " %s" % cmd line += " " * (len(SPACING) - len(cmd) - 3) line += short_desc categorised[category].append(line) for category, lines in categorised.iteritems(): print category for line in lines: print line print print "See 'sx help COMMAND' for more information on a specific command." print print "SpesmiloXchange home page: <http://sx.dyne.org/>" def display_help(command): assert command in command_list long_desc = command_list[command][2] print long_desc return 0 def display_bad(command): print "sx: '%s' is not a sx command. See 'sx --help'." % command return 1 def create_cfg_if_not_exist(): home = os.path.expanduser("~") cfg_path = os.path.join(home, ".sx.cfg") if not os.path.exists(cfg_path): shutil.copyfile("@cfgdefault@", cfg_path) print "Created SX config file:", cfg_path def main(argv): if len(argv) == 1: display_usage() return 1 args = argv[1:] if args and (args[0] == "-c" or args[0] == "--config"): if len(args) < 3: display_usage() return 1 use_cfg = args[1] if not os.path.isfile(use_cfg): print >> sys.stderr, \ "sx: config file '%s' doesn't exist!" % use_cfg return 2 args = args[2:] os.environ["SX_CFG"] = use_cfg #print "Using config file:", use_cfg else: create_cfg_if_not_exist() if not args: display_usage() return 1 command = args[0] # args as one string we can pass to the sx sub-command args = args[1:] if command == "help" or command == "--help" or command == "-h": if not args: display_usage() return 0 return display_help(args[0]) elif command in command_list: # make will come and substitute @corebindir@ binary = "@corebindir@/sx-%s" % command return subprocess.call([binary] + args) else: return display_bad(command) return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) fix help for sx-addr command, so it includes fact that this will work for public as well as private key #!/usr/bin/python import sys import subprocess import os import shutil SPACING = " " * 30 command_list = { "satoshi": ( "MISC", "Convert Bitcoins into Satoshis.", """\ Usage: sx satoshi BTC Convert Bitcoins into Satoshis.\ """ ), "btc": ( "MISC", "Convert Satoshis into Bitcoins.", """\ Usage: sx btc SATOSHIS Convert Satoshis into Bitcoins.\ """ ), "showscript": ( "TRANSACTION PARSING", "Show the details of a raw script.", """\ Usage: sx showscript Show the details of a raw script.\ """ ), "scripthash": ( "MULTISIG ADDRESSES", "Create BIP 16 script hash address from raw script hex.", """\ Usage: sx scripthash Create BIP 16 script hash address from raw script hex (from STDIN). EXAMPLE: # generate an address for 2-of-3 multisig transactions for n in 1 2 3; do echo 'b220b5bd2909df1d74b71c9e664233bf' | sx genpriv $n > key${n}; done sx rawscript 2 [ $(cat key1 | sx pubkey) ] [ $(cat key2 | sx pubkey) ] [ $(cat key3 | sx pubkey) ] 3 checkmultisig | sx scripthash 33opBmv3oJTXu6rxtzsr571SL2Srtw9Cg8 """ ), "rawscript": ( "CREATE TRANSACTIONS", "Create the raw hex representation from a script.", """\ Usage: sx rawscript [ARGS]... Create the raw hex representation from a script.\ EXAMPLE: $ sx rawscript dup # translate a single opcode just for demonstration, see OP_DUP in https://en.bitcoin.it/wik 76 """ ), "initchain": ( "MISC", "Initialize a new blockchain.", """\ Usage: sx initchain DIRECTORY Initialize a new blockchain.\ """ ), "wallet": ( "MISC", "Experimental command line wallet.", """\ Usage: sx wallet SEED This is an experimental prototype.\ """ ), "monitor": ( "BLOCKCHAIN WATCHING", "Monitor an address.", """\ Usage: sx monitor ADDRESS Monitor an address.\ """ ), "validaddr": ( "FORMAT", "Validate an address.", """\ Usage: sx validaddr ADDRESS Validate an address.\ """ ), "validtx": ( "BLOCKCHAIN QUERIES", "Validate a transaction.", """\ Usage: sx validtx FILENAME Query blockchain whether transaction has been confirmed.\ """ ), "pubkey": ( "LOOSE KEYS AND ADDRESSES", "See the public part of a private key.", """\ Usage: sx pubkey Read private key from STDIN and output the public key.\ """ ), "addr": ( "LOOSE KEYS AND ADDRESSES", "See Bitcoin address of a public or private key.", """\ Usage: sx addr Read public or private key from STDIN and output Bitcoin address.\ """ ), "ripemd-hash": ( "FORMAT", "RIPEMD hash data from STDIN.", """\ Usage: sx ripemd-hash RIPEMD hash data from STDIN.\ """ ), "wrap": ( "FORMAT", "Adds version byte and checksum to hexstring.", """\ Usage: sx wrap HEXSTRING VERSION_BYTE <or> echo HEXSTRING | sx wrap VERSION_BYTE Adds version byte and checksum to hexstring.\ """ ), "unwrap": ( "FORMAT", "Validates checksum and recovers version byte and original data from hexstring.", """\ Usage: sx wrap HEXSTRING VERSION_BYTE <or> echo HEXSTRING | sx wrap VERSION_BYTE Validates checksum and recovers version byte and original data from hexstring.\ """ ), "base58-decode": ( "FORMAT", "Convert from base58 to hex", """\ Usage: sx base58-decode B58STRING <or> echo B58STRING | sx base58-decode Convert from base58 to hex.\ """ ), "base58-encode": ( "FORMAT", "Convert from hex to base58", """\ Usage: sx base58-encode HEXSTRING <or> echo HEXSTRING | sx base58-encode Convert from hex to base58.\ """ ), "base58check-decode": ( "FORMAT", "Convert from base58check to hex", """\ Usage: sx base58check-decode B58STRING <or> echo B58STRING | sx base58check-decode Convert from base58check to hex.\ """ ), "base58check-encode": ( "FORMAT", "Convert from hex to base58check", """\ Usage: sx base58check-encode HEXSTRING <or> echo HEXSTRING | sx base58check-encode Convert from hex to base58check.\ """ ), "sendtx-obelisk": ( "BLOCKCHAIN UPDATES", "Send tx to obelisk server.", """\ Usage: sx sendtx-obelisk FILENAME Broadcast the transaction to an obelisk server for the network. $ sx sendtx-obelisk txfile.tx \ """ ), "sendtx-p2p": ( "BLOCKCHAIN UPDATES", "Send tx to bitcoin network.", """\ Usage: sx sendtx-p2p FILENAME Broadcast the transaction to the Bitcoin network. $ sx sendtx-p2p txfile.tx \ """ ), "sendtx-bci": ( "BLOCKCHAIN UPDATES", "Send tx to blockchain.info/pushtx.", """\ Usage: sx bci-push-tx FILENAME Push tx to blockchain.info/pushtx. $ sx sendtx-bci txfile.tx \ """ ), "blke-fetch-transaction": ( "BLOCKCHAIN QUERIES (blockexplorer.com)", "Fetches a transaction from blockexplorer.com", """\ Usage: sx blke-fetch-transaction HASH Fetches a transaction from blockexplorer.com $ sx blke-fetch-transaction HASH \ """ ), "genpriv": ( "DETERMINISTIC KEYS AND ADDRESSES", "Generate a private key deterministically from a seed.", """\ Usage: sx genpriv N [CHANGE] Generate private keys from a wallet seed. $ cat wallet.seed | sx genpriv 0 5Jmb4EYzEqj63rkPwADFY7WyGV2kga3YB1HfDAzg9dHNG57NMPu $ cat wallet.seed | sx genpriv 1 5KjCYpPyxU2e88S57b1naKUsJ1JNjCudkFSQPxqcYyBYgzzahNe \ """ ), "genpub": ( "DETERMINISTIC KEYS AND ADDRESSES", "Generate a public key deterministically from a wallet\n" + SPACING + "seed or master public key.", """\ Usage: sx genpub N [CHANGE] Generate public key from a wallet seed or master public key. $ cat wallet.seed | sx genpub 0 040a053d0a42d58b7e34346daae9d40ce33fad5d65bbaa6c615a2b76447734b2c712b5d45de839b2e5e7ac00201cbea3d2d376cfcc7a3f3f508f1e6761f6c271bf \ """ ), "genaddr": ( "DETERMINISTIC KEYS AND ADDRESSES", "Generate a Bitcoin address deterministically from a wallet\n" + SPACING + "seed or master public key.", """\ Usage: sx genaddr N [CHANGE] Generate Bitcoin addresses from a wallet seed or master public key. $ cat wallet.seed | sx genaddr 0 1a4b47AC4ydSnAAcTNH1qozHq2pwJb644 \ """ ), "qrcode": ( "MISC", "Generate Bitcoin QR codes offline.", """\ Usage: sx qrcode Make sure you have the program 'qrencode' installed first. $ sudo apt-get install qrencode $ sx qrcode 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe qrcode.png \ """ ), "fetch-block-header": ( "BLOCKCHAIN QUERIES", "Fetch raw block header.", """\ Usage: sx fetch-block-header [HASH] [HEIGHT] The fetch-block-header tool uses a network connection to make requests against the load balancer backend.\ """ ), "fetch-last-height": ( "BLOCKCHAIN QUERIES", "Fetch the last block height.", """\ Usage: sx fetch-last-height The fetch-last-height tool uses a network connection to make requests against the load balancer backend.\ """ ), "bci-fetch-last-height": ( "BLOCKCHAIN QUERIES (blockchain.info)", "Fetch the last block height using blockchain.info.", """\ Usage: sx bci-fetch-last-height Fetch the last block height using blockchain.info.\ """ ), "fetch-transaction": ( "BLOCKCHAIN QUERIES", "Fetch a raw transaction using a network connection to make requests against the obelisk load balancer backend.", """\ Fetch a raw transaction using a network connection to make requests against the obelisk load balancer backend. Usage: sx fetch-transaction HASH EXAMPLE: $ sx fetch-transaction 69735d70ada1be32ff39b49c6fc2390b03e9d5eed8918ed10fe42c8cbabf62d4 # fetches raw data \ """ ), "fetch-transaction-index": ( "BLOCKCHAIN QUERIES", "Fetch block height and index in block of transaction.", """\ Usage: sx fetch-transaction-index HASH The fetch-transaction-index tool uses a network connection to make requests against the load balancer backend.\ """ ), "balance": ( "BLOCKCHAIN QUERIES", "Show balance of a Bitcoin address in satoshis.", """\ Usage: sx balance [-j] ADDRESS1 [ADDRESS2...] The balance tool uses a network connection to make requests against the load balancer backend. -j, --json Enable json parseable output. Example: $ echo 134HfD2fdeBTohfx8YANxEpsYXsv5UoWyz | sx balance Address: 134HfD2fdeBTohfx8YANxEpsYXsv5UoWyz Paid balance: 0 Pending balance: 0 Total received: 100000 \ """ ), "history": ( "BLOCKCHAIN QUERIES", "Get list of output points, values, and their spends for an\n" + SPACING + "address. grep can filter for just unspent outputs which can\n" + SPACING + "be fed into mktx.", """\ Usage: sx history [-j] ADDRESS1 [ADDRESS2...] The history tool uses a network connection to make requests against the load balancer backend. -j, --json Enable json parseable output. Example: $ echo 134HfD2fdeBTohfx8YANxEpsYXsv5UoWyz | sx history Address: 134HfD2fdeBTohfx8YANxEpsYXsv5UoWyz output: 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:1 output_height: 247683 value: 100000 spend: b7354b8b9cc9a856aedaa349cffa289ae9917771f4e06b2386636b3c073df1b5:0 spend_height: 247742 \ """ ), "bci-history": ( "BLOCKCHAIN QUERIES (blockchain.info)", "Get list of output points, values, and their spends\n" + SPACING + "from blockchain.info", """\ Usage: sx bci-history SATOSHIS Get list of output points, values and spends using blockchain.info.\ """ ), "get-utxo": ( "BLOCKCHAIN QUERIES", "Get enough unspent transaction outputs from a given set of\n" + SPACING + "addresses to pay a given number of satoshis", """\ Usage: sx get-utxo ADDRESS1 ADDRESS2... SATOSHIS Get enough unspent transaction outputs from a given set of addresses to pay a given number of satoshis\ """ ), "get-pubkey": ( "LOOSE KEYS AND ADDRESSES", "Get the pubkey of an address if available", """\ Usage: sx get-pubkey ADDRESS Get the pubkey of an address if available\ """ ), "mktx": ( "CREATE TRANSACTIONS", "Create an unsigned tx.", """\ Usage: sx mktx FILENAME [-i TXHASH:INDEX]... [-o ADDRESS:VALUE] [-o HEXSCRIPT:VALUE] -i, --input TXHASH:INDEX Add input to transaction. -o, --output ADDRESS:VALUE or HEXSCRIPT:VALUE Add output to transaction. Construct the transaction: $ sx mktx txfile.tx -i 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:1 -o 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe:90000 FILENAME denotes the output file. If FILENAME is - (a single dash), then output is written to stdout. The VALUE field is in Satoshis.\ """ ), "secret-to-wif": ( "STEALTH", "Convert a secret exponent value to Wallet. Import. Format.", """\ Usage: echo SECRET | sx secret-to-wif \ """ ), "mpk": ( "DETERMINISTIC KEYS AND ADDRESSES", "Extract a master public key from a deterministic wallet seed.", """\ Usage: sx mpk Extract a master public key from a deterministic wallet seed. $ sx newseed > wallet.seed $ cat wallet.seed b220b5bd2909df1d74b71c9e664233bf $ cat wallet.seed | sx mpk > master_public.key \ """ ), "newkey": ( "LOOSE KEYS AND ADDRESSES", "Create a new private key.", """\ Usage: sx newkey $ sx newkey 5KPFsatiYrJcvCSRrDbtx61822vZjeGGGx3wu38pQDHRF8eVJ8H \ """ ), "newseed": ( "DETERMINISTIC KEYS AND ADDRESSES", "Create a new deterministic wallet seed.", """\ Usage: sx newseed $ sx newseed b220b5bd2909df1d74b71c9e664233bf \ """ ), "sendtx-node": ( "BLOCKCHAIN UPDATES", "Send transaction to a single node.", """\ Usage: sx sendtx-node FILENAME [HOST] [PORT] HOST and PORT default to localhost:8333. Send transaction to one Bitcoin node on localhost port 4009: $ sx sendtx-node txfile.tx localhost 4009 \ """ ), "showblkhead": ( "MISC", "Show the details of a block header.", """\ Usage: sx showblkhead FILENAME 'showblkhead' allows inspecting of block headers. $ sx showblkhead headerfile.blk hash: 4d25b18ed094ad68f75f21692d8540f45ceb90b240a521b8f191e95d8b6b8bb0 version: 1 locktime: 0 Input: previous output: 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:0 script: sequence: 4294967295 Output: value: 90000 script: dup hash160 [ 18c0bd8d1818f1bf99cb1df2269c645318ef7b73 ] equalverify checksig address: 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe \ """ ), "showtx": ( "TRANSACTION PARSING", "Show the details of a transaction.", """\ Usage: sx showtx [-j] FILENAME 'showtx' allows inspecting of tx files. -j, --json Enable json parseable output. Example: $ sx fetch-transaction cd484f683bc99c94948613a7f7254880e9c98cd74f2760a2d2c4e372fda1bc6a | sx showtx hash: cd484f683bc99c94948613a7f7254880e9c98cd74f2760a2d2c4e372fda1bc6a version: 1 locktime: 0 Input: previous output: f97367c5dc9e521a4c541327cbff69d118e35a2d0b67f91eb7771741a6374b20:0 script: [ 3046022100f63b1109e1b04c0a4b5230e6f6c75f5e2a10c16d022cdf93de9b3cc946e6e24a022100ae3da40f05504521f2f3557e736a2d1724d6d1d8c18b66a64990bf1afee78dba01 ] [ 028a2adb719bbf7e9cf0cb868d4f30b10551f2a4402eb2ece9b177b49e68e90511 ] sequence: 4294967295 address: 1NYMePixLjAATLaz55vN7FfTLUfFB23Tt Output: value: 2676400 script: dup hash160 [ 6ff00bd374abb3a3f19d1576bb36520b2cb15e2d ] equalverify checksig address: 1BCsZziw8Q1sMhxr2DjAR7Rmt1qQvYwXSU Output: value: 1000000 script: hash160 [ 0db1635fe975792a9a7b6f2d4061b730478dc6b9 ] equal address: 32wRDBezxnazSBxMrMqLWqD1ajwEqnDnMc \ """ ), "decode-addr": ( "FORMAT", "Decode an address to its internal RIPEMD representation.", """\ Usage: sx decode-addr ADDRESS Decode an address to its internal RIPEMD representation.\ """), "embed-addr": ( "FORMAT", "Generate an address used for embedding record of data into the blockchain.", """\ Usage: sx embed-addr Generate an address used for embedding record of data into the blockchain. Example: $ cat my_sculpture.jpg | sx embed-addr 1N9v8AKBqst9MNceV3gLmFKsgkKv1bZcBU Now send some Bitcoin to that address and it'll be embedded in the blockchain as a record of the data passed in. \ """), "encode-addr": ( "FORMAT", "Encode an address to base58check form.", """\ Usage: sx encode-addr HASH [VERSION] Encode an address to base58check form.\ """), "validsig": ( "VALIDATE", "Validate a transaction input's signature.", """\ Usage: sx validsig FILENAME INDEX SCRIPT_CODE SIGNATURE Validate a transaction input's signature.\ """), "brainwallet": ( "BRAINWALLET", "Make a private key from a brainwallet", """\ Usage: sx brainwallet password sx brainwallet username password sx brainwallet password --algo slowsha sx brainwallet username password --algo slowsha Make a private key from a brainwallet.\ """ ), "set-input": ( "CREATE TRANSACTIONS", "Set a transaction input.", """\ Usage: sx set-input TXFILENAME INPUTINDEX SIGNATURE_AND_PUBKEY_SCRIPT Set a transaction input. See sx help sign-input for an example.\ """), "sign-input": ( "CREATE TRANSACTIONS", "Sign a transaction input.", """\ Usage: cat secret.key | sx sign-input FILENAME INDEX PREVOUT_SCRIPT Sign a transaction input. Note how the input script in the following transaction is empty. $ sx mktx txfile.tx -i 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:0 -o 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe:90000 $ sx showtx txfile.tx hash: 4d25b18ed094ad68f75f21692d8540f45ceb90b240a521b8f191e95d8b6b8bb0 version: 1 locktime: 0 Input: previous output: 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:0 script: sequence: 4294967295 Output: value: 90000 script: dup hash160 [ 18c0bd8d1818f1bf99cb1df2269c645318ef7b73 ] equalverify checksig address: 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe We will now sign the first input using our private key. $ echo '5KPFsatiYrJcvCSRrDbtx61822vZjeGGGx3wu38pQDHRF8eVJ8H' > private.key $ DECODED_ADDR=$(cat private.key | sx addr | sx decode-addr) $ PREVOUT_SCRIPT=$(sx rawscript dup hash160 [ $DECODED_ADDR ] equalverify checksig) $ SIGNATURE=$(cat private.key | sx sign-input txfile.tx 0 $PREVOUT_SCRIPT) $ SIGNATURE_AND_PUBKEY_SCRIPT=$(sx rawscript [ $SIGNATURE ] [ $(cat private.key | sx pubkey) ]) $ sx set-input txfile.tx 0 $SIGNATURE_AND_PUBKEY_SCRIPT > txfile.tx.signed # the first input has index 0 Note how the input script in the following transaction is now filled. $ cat txfile.tx.signed | sx showtx hash: cc5650c69173e7607c095200f4ff36265f9fbb45e112b60cd467d696b2724488 version: 1 locktime: 0 Input: previous output: 97e06e49dfdd26c5a904670971ccf4c7fe7d9da53cb379bf9b442fc9427080b3:0 script: [ 3045022100b778f7fb270b751491ba7e935a6978eaea2a44795b3f6636ea583939697b1ca102203ce47d3ecb0b7e832114e88e549fce476d4ea120ca1e60c508fe8083889a9cba01 ] [ 04c40cbd64c9c608df2c9730f49b0888c4db1c436e\ 8b2b74aead6c6afbd10428c0adb73f303ae1682415253f4411777224ab477ad098347ddb7e0b94d49261e613 ] sequence: 4294967295 address: 1MyKMeDsom7rYcp69KpbKn4DcyuvLMkLYJ Output: value: 90000 script: dup hash160 [ 18c0bd8d1818f1bf99cb1df2269c645318ef7b73 ] equalverify checksig address: 13Ft7SkreJY9D823NPm4t6D1cBqLYTJtAe Now the input script is prepared, and the transaction is signed. It can be sent by $ sx broadcast-tx txfile.tx.signed \ """ ), "mnemonic": ( "BRAINWALLET", "Work with Electrum compatible mnemonics (12 words wallet seed).", """\ Usage: sx mnemonic Electrum compatible 12 word seeds. $ echo 148f0a1d77e20dbaee3ff920ca40240d | sx mnemonic people blonde admit dart couple different truth common alas stumble time cookie $ echo "people blonde admit dart couple different truth common alas stumble time cookie" | sx mnemonic 148f0a1d77e20dbaee3ff920ca40240d \ """ ), "watchtx": ( "BLOCKCHAIN WATCHING", "Watch transactions from the network searching for a certain hash.", """\ Usage: sx watchtx [TXHASH]... Watch transactions from the network searching for a certain hash.\ """ ), "stealth-new": ( "STEALTH", "Generate a new master stealth secret.", """\ Usage: sx stealth-new Generate a new stealth secret.\ """ ), "stealth-recv": ( "STEALTH", "Regenerate the secret from your master secret and provided nonce.", """\ Usage: sx stealth-recv SECRET NONCE Regenerate the secret from your master secret and provided nonce.\ """ ), "stealth-send": ( "STEALTH", "Generate a new sending address and a stealth nonce.", """\ Usage: sx stealth-send PUBKEY Generate a new sending address and a stealth nonce.\ """ ), } def display_usage(): print "Usage: sx COMMAND [ARGS]..." print print " -c, --config Specify a config file" print print "The sx commands are:" print categorised = {} for cmd in sorted(command_list.iterkeys()): category = command_list[cmd][0] if category not in categorised: categorised[category] = [] short_desc = command_list[cmd][1] line = " %s" % cmd line += " " * (len(SPACING) - len(cmd) - 3) line += short_desc categorised[category].append(line) for category, lines in categorised.iteritems(): print category for line in lines: print line print print "See 'sx help COMMAND' for more information on a specific command." print print "SpesmiloXchange home page: <http://sx.dyne.org/>" def display_help(command): assert command in command_list long_desc = command_list[command][2] print long_desc return 0 def display_bad(command): print "sx: '%s' is not a sx command. See 'sx --help'." % command return 1 def create_cfg_if_not_exist(): home = os.path.expanduser("~") cfg_path = os.path.join(home, ".sx.cfg") if not os.path.exists(cfg_path): shutil.copyfile("@cfgdefault@", cfg_path) print "Created SX config file:", cfg_path def main(argv): if len(argv) == 1: display_usage() return 1 args = argv[1:] if args and (args[0] == "-c" or args[0] == "--config"): if len(args) < 3: display_usage() return 1 use_cfg = args[1] if not os.path.isfile(use_cfg): print >> sys.stderr, \ "sx: config file '%s' doesn't exist!" % use_cfg return 2 args = args[2:] os.environ["SX_CFG"] = use_cfg #print "Using config file:", use_cfg else: create_cfg_if_not_exist() if not args: display_usage() return 1 command = args[0] # args as one string we can pass to the sx sub-command args = args[1:] if command == "help" or command == "--help" or command == "-h": if not args: display_usage() return 0 return display_help(args[0]) elif command in command_list: # make will come and substitute @corebindir@ binary = "@corebindir@/sx-%s" % command return subprocess.call([binary] + args) else: return display_bad(command) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
"""Cmdlr clawler subsystem.""" import asyncio import random import collections import urllib.parse as UP import aiohttp from . import amgr from . import info from . import config from . import log _DYN_DELAY_TABLE = { # dyn_delay_factor -> second 0: 0, 1: 5, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 90, 9: 120, 10: 180, 11: 240, 12: 300, 13: 600, 14: 900, 15: 1200, 16: 1500, 17: 1800, 18: 2100, 19: 2400, 20: 3600, } _per_host_semaphore_factory = None def _get_default_host(): return {'dyn_delay_factor': 0, 'semaphore': _per_host_semaphore_factory()} _session_pool = {} _host_pool = collections.defaultdict(_get_default_host) _loop = None _semaphore = None def _get_session_init_kwargs(analyzer): analyzer_kwargs = getattr(analyzer, 'session_init_kwargs', {}) default_kwargs = {'headers': { 'user-agent': '{}/{}'.format( info.PROJECT_NAME, info.VERSION) }, 'read_timeout': 120, 'conn_timeout': 120} kwargs = {**default_kwargs, **analyzer_kwargs} return kwargs def _clear_session_pool(): """Close and clear all sessions in pool.""" for session in _session_pool.values(): session.close() _session_pool.clear() def _get_session(curl): """Get session from session pool by comic url.""" analyzer = amgr.get_match_analyzer(curl) aname = amgr.get_analyzer_name(analyzer) if aname not in _session_pool: session_init_kwargs = _get_session_init_kwargs(analyzer) _session_pool[aname] = aiohttp.ClientSession(loop=_loop, **session_init_kwargs) return _session_pool[aname] def _get_host(url): netloc = UP.urlparse(url).netloc return _host_pool[netloc] def _get_delay_sec(dyn_delay_factor, delay): dyn_delay_sec = _DYN_DELAY_TABLE[dyn_delay_factor] static_delay_sec = random.random() * delay return dyn_delay_sec + static_delay_sec def _get_dyn_delay_callbacks(host): dyn_delay_factor = host['dyn_delay_factor'] def success(): if dyn_delay_factor == host['dyn_delay_factor']: host['dyn_delay_factor'] = max(0, dyn_delay_factor - 1) def fail(): if dyn_delay_factor == host['dyn_delay_factor']: host['dyn_delay_factor'] = min(20, dyn_delay_factor + 1) return success, fail def init(loop): """Init the crawler module.""" def per_host_semaphore_factory(): return asyncio.Semaphore(value=config.get_per_host_concurrent(), loop=loop) global _loop _loop = loop global _per_host_semaphore_factory _per_host_semaphore_factory = per_host_semaphore_factory global _semaphore _semaphore = asyncio.Semaphore(value=config.get_max_concurrent(), loop=loop) def close(): """Do recycle.""" _clear_session_pool() def get_request(curl): """Get the request class.""" session = _get_session(curl) proxy = config.get_proxy() max_try = config.get_max_retry() + 1 delay = config.get_delay() class request: """session.request contextmanager.""" def __init__(self, **req_kwargs): """init.""" self.req_kwargs = req_kwargs self.host = _get_host(req_kwargs['url']) self.dd_success = lambda: None self.dd_fail = lambda: None async def __aenter__(self): """Async with enter.""" await self.host['semaphore'].acquire() await _semaphore.acquire() for try_idx in range(max_try): self.dd_success, self.dd_fail = _get_dyn_delay_callbacks( self.host) dyn_delay_factor = self.host['dyn_delay_factor'] delay_sec = _get_delay_sec(dyn_delay_factor, delay) await asyncio.sleep(delay_sec) try: self.resp = await session.request(**{ **{'method': 'GET', 'proxy': proxy}, **self.req_kwargs, }) self.resp.raise_for_status() return self.resp except Exception as e: current_try = try_idx + 1 log.logger.error( 'Request Failed ({}/{}, d{}): {} => {}: {}' .format(current_try, max_try, dyn_delay_factor, self.req_kwargs['url'], type(e).__name__, e)) if current_try == max_try: raise e from None else: self.dd_fail() async def __aexit__(self, exc_type, exc, tb): """Async with exit.""" if exc_type: self.dd_fail() else: self.dd_success() await self.resp.release() _semaphore.release() self.host['semaphore'].release() return request fix: deadlock when request failed """Cmdlr clawler subsystem.""" import asyncio import random import collections import urllib.parse as UP import sys import aiohttp from . import amgr from . import info from . import config from . import log _DYN_DELAY_TABLE = { # dyn_delay_factor -> second 0: 0, 1: 5, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 90, 9: 120, 10: 180, 11: 240, 12: 300, 13: 600, 14: 900, 15: 1200, 16: 1500, 17: 1800, 18: 2100, 19: 2400, 20: 3600, } _per_host_semaphore_factory = None def _get_default_host(): return {'dyn_delay_factor': 0, 'semaphore': _per_host_semaphore_factory()} _session_pool = {} _host_pool = collections.defaultdict(_get_default_host) _loop = None _semaphore = None def _get_session_init_kwargs(analyzer): analyzer_kwargs = getattr(analyzer, 'session_init_kwargs', {}) default_kwargs = {'headers': { 'user-agent': '{}/{}'.format( info.PROJECT_NAME, info.VERSION) }, 'read_timeout': 120, 'conn_timeout': 120} kwargs = {**default_kwargs, **analyzer_kwargs} return kwargs def _clear_session_pool(): """Close and clear all sessions in pool.""" for session in _session_pool.values(): session.close() _session_pool.clear() def _get_session(curl): """Get session from session pool by comic url.""" analyzer = amgr.get_match_analyzer(curl) aname = amgr.get_analyzer_name(analyzer) if aname not in _session_pool: session_init_kwargs = _get_session_init_kwargs(analyzer) _session_pool[aname] = aiohttp.ClientSession(loop=_loop, **session_init_kwargs) return _session_pool[aname] def _get_host(url): netloc = UP.urlparse(url).netloc return _host_pool[netloc] def _get_delay_sec(dyn_delay_factor, delay): dyn_delay_sec = _DYN_DELAY_TABLE[dyn_delay_factor] static_delay_sec = random.random() * delay return dyn_delay_sec + static_delay_sec def _get_dyn_delay_callbacks(host): dyn_delay_factor = host['dyn_delay_factor'] def success(): if dyn_delay_factor == host['dyn_delay_factor']: host['dyn_delay_factor'] = max(0, dyn_delay_factor - 1) def fail(): if dyn_delay_factor == host['dyn_delay_factor']: host['dyn_delay_factor'] = min(20, dyn_delay_factor + 1) return success, fail def init(loop): """Init the crawler module.""" def per_host_semaphore_factory(): return asyncio.Semaphore(value=config.get_per_host_concurrent(), loop=loop) global _loop _loop = loop global _per_host_semaphore_factory _per_host_semaphore_factory = per_host_semaphore_factory global _semaphore _semaphore = asyncio.Semaphore(value=config.get_max_concurrent(), loop=loop) def close(): """Do recycle.""" _clear_session_pool() def get_request(curl): """Get the request class.""" session = _get_session(curl) proxy = config.get_proxy() max_try = config.get_max_retry() + 1 delay = config.get_delay() class request: """session.request contextmanager.""" def __init__(self, **req_kwargs): """init.""" self.req_kwargs = req_kwargs self.host = _get_host(req_kwargs['url']) self.resp = None self.local_locked = False self.global_locked = False self.dd_success = lambda: None self.dd_fail = lambda: None async def acquire(self): self.local_locked = True await self.host['semaphore'].acquire() self.global_locked = True await _semaphore.acquire() def release(self): if self.global_locked: self.global_locked = False _semaphore.release() if self.local_locked: self.local_locked = False self.host['semaphore'].release() async def __aenter__(self): """Async with enter.""" for try_idx in range(max_try): try: await self.acquire() self.dd_success, self.dd_fail = _get_dyn_delay_callbacks( self.host) delay_sec = _get_delay_sec( self.host['dyn_delay_factor'], delay) await asyncio.sleep(delay_sec) self.resp = await session.request(**{ **{'method': 'GET', 'proxy': proxy}, **self.req_kwargs, }) self.resp.raise_for_status() return self.resp except Exception as e: current_try = try_idx + 1 log.logger.error( 'Request Failed ({}/{}, d{}): {} => {}: {}' .format(current_try, max_try, self.host['dyn_delay_factor'], self.req_kwargs['url'], type(e).__name__, e)) await self.__aexit__(*sys.exc_info()) if current_try == max_try: raise e from None async def __aexit__(self, exc_type, exc, tb): """Async with exit.""" if exc_type: if exc_type is not asyncio.CancelledError: self.dd_fail() else: self.dd_success() if self.resp: await self.resp.release() self.release() return request
# # Copyright (c) 2005 rPath, Inc. # # All Rights Reserved # import os.path import tempfile from conary import checkin from conary import conarycfg from conary.repository import netclient from conary import versions from conary.build import cook from imagegen import ImageGenerator from mint import projects class GroupTroveCook(ImageGenerator): def write(self): self.status("Cooking group") groupTrove = self.client.getGroupTrove(self.job.getGroupTroveId()) curDir = os.getcwd() ret = None try: path = tempfile.mkdtemp() projectId = groupTrove.projectId recipe = groupTrove.getRecipe() sourceName = groupTrove.recipeName + ":source" project = self.client.getProject(projectId) cfg = conarycfg.ConaryConfiguration() cfg.name = "rBuilder Online" cfg.contact = "http://www.rpath.org" cfg.quiet = True cfg.buildLabel = versions.Label(project.getLabel()) cfg.initializeFlavors() cfg.repositoryMap = project.getConaryConfig().repositoryMap cfg.repositoryMap.update({'conary.rpath.com': 'http://conary-commits.rpath.com/conary/'}) repos = netclient.NetworkRepositoryClient(cfg.repositoryMap) trvLeaves = repos.getTroveLeavesByLabel({sourceName : {cfg.buildLabel : None} }).get(sourceName, []) os.chdir(path) if trvLeaves: checkin.checkout(repos, cfg, path, groupTrove.recipeName) else: checkin.newTrove(repos, cfg, groupTrove.recipeName, path) recipeFile = open(groupTrove.recipeName + '.recipe', 'w') recipeFile.write(recipe) recipeFile.flush() recipeFile.close() if not trvLeaves: checkin.addFiles([groupTrove.recipeName + '.recipe']) # commit recipe as changeset message = "Auto generated commit from %s." % cfg.name checkin.commit(repos, cfg, message) ret = cook.cookItem(repos, cfg, groupTrove.recipeName) ret = ret[0][0] finally: os.chdir(curDir) if ret: return ret[0], ret[1], ret[2].freeze() else: return None supply the user's comments when building an auto-generated group trove. # # Copyright (c) 2005 rPath, Inc. # # All Rights Reserved # import os.path import tempfile from conary import checkin from conary import conarycfg from conary.repository import netclient from conary import versions from conary.build import cook from imagegen import ImageGenerator from mint import projects class GroupTroveCook(ImageGenerator): def write(self): self.status("Cooking group") groupTrove = self.client.getGroupTrove(self.job.getGroupTroveId()) curDir = os.getcwd() ret = None try: path = tempfile.mkdtemp() projectId = groupTrove.projectId recipe = groupTrove.getRecipe() sourceName = groupTrove.recipeName + ":source" project = self.client.getProject(projectId) cfg = conarycfg.ConaryConfiguration() cfg.name = "rBuilder Online" cfg.contact = "http://www.rpath.org" cfg.quiet = True cfg.buildLabel = versions.Label(project.getLabel()) cfg.initializeFlavors() cfg.repositoryMap = project.getConaryConfig().repositoryMap cfg.repositoryMap.update({'conary.rpath.com': 'http://conary-commits.rpath.com/conary/'}) repos = netclient.NetworkRepositoryClient(cfg.repositoryMap) trvLeaves = repos.getTroveLeavesByLabel({sourceName : {cfg.buildLabel : None} }).get(sourceName, []) os.chdir(path) if trvLeaves: checkin.checkout(repos, cfg, path, groupTrove.recipeName) else: checkin.newTrove(repos, cfg, groupTrove.recipeName, path) recipeFile = open(groupTrove.recipeName + '.recipe', 'w') recipeFile.write(recipe) recipeFile.flush() recipeFile.close() if not trvLeaves: checkin.addFiles([groupTrove.recipeName + '.recipe']) # commit recipe as changeset message = "Auto generated commit from %s.\n%s" % (cfg.name, groupTrove.description) checkin.commit(repos, cfg, message) ret = cook.cookItem(repos, cfg, groupTrove.recipeName) ret = ret[0][0] finally: os.chdir(curDir) if ret: return ret[0], ret[1], ret[2].freeze() else: return None
# Copyright 2018 Google LLC # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd from absl import app from absl import flags import dspl2 import jinja2 from pathlib import Path import sys FLAGS = flags.FLAGS flags.DEFINE_boolean('rdf', False, 'Process the JSON-LD as RDF.') def _RenderLocalDspl2(path, rdf): template_dir = Path(dspl2.__file__).parent / 'templates' env = jinja2.Environment(loader=jinja2.FileSystemLoader( template_dir.as_posix())) try: print("Loading template") template = env.get_template('display.html') print("Loading DSPL2") getter = dspl2.LocalFileGetter(path) print("Expanding DSPL2") if rdf: graph = dspl2.Dspl2RdfExpander(getter).Expand() print("Framing DSPL2") json_val = FrameGraph(graph) else: json_val = dspl2.Dspl2JsonLdExpander(getter).Expand() print("Rendering template") return template.render(**dspl2.JsonToKwArgsDict(json_val)) except Exception as e: raise template = loader.load(env, 'error.html') return template.render(action="processing", url=path, text=str(type(e)) + ": " + str(e)) def main(argv): if len(argv) != 3: print(f'Usage: {argv[0]} [input.json] [output.html]', file=sys.stderr) exit(1) with open(argv[2], 'w') as f: print(_RenderLocalDspl2(argv[1], FLAGS.rdf), file=f) if __name__ == '__main__': app.run(main) fix missing package name in pretty-print script # Copyright 2018 Google LLC # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd from absl import app from absl import flags import dspl2 import jinja2 from pathlib import Path import sys FLAGS = flags.FLAGS flags.DEFINE_boolean('rdf', False, 'Process the JSON-LD as RDF.') def _RenderLocalDspl2(path, rdf): template_dir = Path(dspl2.__file__).parent / 'templates' env = jinja2.Environment(loader=jinja2.FileSystemLoader( template_dir.as_posix())) try: print("Loading template") template = env.get_template('display.html') print("Loading DSPL2") getter = dspl2.LocalFileGetter(path) print("Expanding DSPL2") if rdf: graph = dspl2.Dspl2RdfExpander(getter).Expand() print("Framing DSPL2") json_val = dspl2.FrameGraph(graph) else: json_val = dspl2.Dspl2JsonLdExpander(getter).Expand() print("Rendering template") return template.render(**dspl2.JsonToKwArgsDict(json_val)) except Exception as e: raise template = loader.load(env, 'error.html') return template.render(action="processing", url=path, text=str(type(e)) + ": " + str(e)) def main(argv): if len(argv) != 3: print(f'Usage: {argv[0]} [input.json] [output.html]', file=sys.stderr) exit(1) with open(argv[2], 'w') as f: print(_RenderLocalDspl2(argv[1], FLAGS.rdf), file=f) if __name__ == '__main__': app.run(main)
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 coding=utf-8 import os, glob from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.utils.translation import ugettext_lazy from django.contrib.auth.models import User from pyxform.xform2json import create_survey_element_from_xml from odk_logger.models.xform import XForm from odk_logger.models.instance import get_id_string_from_xml_str class Command(BaseCommand): help = ugettext_lazy("Import a folder of xml forms for ODK. Arguments-> forder.name username") option_list = BaseCommand.option_list + ( make_option('-r', '--replace', action='store_true', dest='replace', help=ugettext_lazy("Replace existing form if any")), ) def handle(self, *args, **options): path = args[0] try: username = args[1] except IndexError: raise CommandError("You must provide the username to publish the forms to.") # make sure user exists try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("The user '{}' does not exist.".format(username)) for form in glob.glob( os.path.join(path, "*") ): f = open(form) xml = f.read() id_string = get_id_string_from_xml_str(xml) # check if a form with this id_string exists for this user form_already_exists = XForm.objects.filter(user=user, id_string=id_string).count() > 0 if form_already_exists: if options.has_key('replace') and options['replace']: XForm.objects.filter(user=user, id_string=id_string).delete() else: raise CommandError('form "{}" is already defined, and --replace was not specified.'.format( id_string)) survey = create_survey_element_from_xml(xml) form_json = survey.to_json() XForm.objects.get_or_create(xml=xml, downloadable=True, user=user, id_string=id_string, json=form_json) f.close() publish_xml_forms command error msg #!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 coding=utf-8 import os, glob from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.utils.translation import ugettext_lazy from django.contrib.auth.models import User from pyxform.xform2json import create_survey_element_from_xml from odk_logger.models.xform import XForm from odk_logger.models.instance import get_id_string_from_xml_str class Command(BaseCommand): help = ugettext_lazy("Import a folder of xml forms for ODK. Arguments-> forder.name username") option_list = BaseCommand.option_list + ( make_option('-r', '--replace', action='store_true', dest='replace', help=ugettext_lazy("Replace existing form if any")), ) def handle(self, *args, **options): path = args[0] try: username = args[1] except IndexError: raise CommandError("You must provide the username to publish the forms to.") # make sure user exists try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("The user '{}' does not exist.".format(username)) for form in glob.glob( os.path.join(path, "*") ): print('Publishing form "{}"...'.format(form)) f = open(form) xml = f.read() id_string = get_id_string_from_xml_str(xml) # check if a form with this id_string exists for this user form_already_exists = XForm.objects.filter(user=user, id_string=id_string).count() > 0 if form_already_exists: if options.has_key('replace') and options['replace']: XForm.objects.filter(user=user, id_string=id_string).delete() else: raise CommandError('form "{}" is already defined, and --replace was not specified.'.format( id_string)) try: survey = create_survey_element_from_xml(xml) except AssertionError: raise CommandError('Probable error in xml structure.') form_json = survey.to_json() XForm.objects.get_or_create(xml=xml, downloadable=True, user=user, id_string=id_string, json=form_json) f.close()
# This file is here to trick django-supervisor into finding its config file. Print a useful error msg if someone (mis)uses the dummy manage.py script # This file is here to trick django-supervisor into finding its config file. # Blow up with an explanation if someone tries to use this dummy script if __name__ == "__main__": import os raise Exception( "%s is a placeholder manage.py script, not a real one. Run %s instead." % (os.path.abspath(__file__), os.path.abspath( os.path.join(os.path.basename(__file__), 'bin', 'manage.py'))))
from __future__ import absolute_import import os import sys from os.path import abspath, dirname, join, normpath from django import VERSION import six from leonardo.base import leonardo, default from leonardo.utils.settings import get_conf_from_module, merge, get_leonardo_modules import warnings _file_path = os.path.abspath(os.path.dirname(__file__)).split('/') BASE_DIR = '/'.join(_file_path[0:-2]) EMAIL = { 'HOST': 'mail.domain.com', 'PORT': '25', 'USER': 'username', 'PASSWORD': 'pwd', 'SECURITY': True, } RAVEN_CONFIG = {} ALLOWED_HOSTS = ['*'] USE_TZ = True DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('admin', 'mail@leonardo.cz'), ) DEFAULT_CHARSET = 'utf-8' MANAGERS = ADMINS SITE_ID = 1 SITE_NAME = 'Leonardo' TIME_ZONE = 'Europe/Prague' LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', 'EN'), ('cs', 'CS'), ) USE_I18N = True MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' STATIC_URL = '/static/' if VERSION[:2] >= (1, 8): TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join( os.path.dirname(os.path.realpath(__file__)), 'templates') ], 'OPTIONS': { 'context_processors': default.context_processors, 'loaders': [ 'dbtemplates.loader.Loader', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'horizon.loaders.TemplateLoader', ] }, }, ] else: TEMPLATE_DIRS = [ os.path.join( os.path.dirname(os.path.realpath(__file__)), 'templates') ] TEMPLATE_CONTEXT_PROCESSORS = default.context_processors TEMPLATE_LOADERS = ( 'dbtemplates.loader.Loader', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'horizon.loaders.TemplateLoader', ) DBTEMPLATES_USE_REVERSION = True DBTEMPLATES_MEDIA_PREFIX = '/static-/' DBTEMPLATES_USE_CODEMIRROR = False DBTEMPLATES_USE_TINYMCE = False DBTEMPLATES_AUTO_POPULATE_CONTENT = True DBTEMPLATES_ADD_DEFAULT_SITE = True FILER_ENABLE_PERMISSIONS = True # noqa MIDDLEWARE_CLASSES = default.middlewares ROOT_URLCONF = 'leonardo.urls' LEONARDO_BOOTSTRAP_URL = 'http://github.com/django-leonardo/django-leonardo/raw/develop/contrib/bootstrap/demo.yaml' MARKITUP_FILTER = ('markitup.renderers.render_rest', {'safe_mode': True}) INSTALLED_APPS = default.apps # For easy_thumbnails to support retina displays (recent MacBooks, iOS) FEINCMS_USE_PAGE_ADMIN = False LEONARDO_USE_PAGE_ADMIN = True FEINCMS_DEFAULT_PAGE_MODEL = 'web.Page' CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_CONFIG = {} # enable auto loading packages LEONARDO_MODULE_AUTO_INCLUDE = True # enable system module LEONARDO_SYSTEM_MODULE = True ########################## STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", 'compressor.finders.CompressorFinder', ) LOGIN_URL = '/auth/login/' LOGIN_REDIRECT_URL = '/' LOGOUT_URL = "/auth/logout" LOGOUT_ON_GET = True AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': 'DEBUG', 'handlers': ['console'], }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'leonardo_app.log', 'formatter': 'verbose' }, }, 'loggers': { 'django.request': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'leonardo': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, } } CRISPY_TEMPLATE_PACK = 'bootstrap3' SECRET_KEY = None APPS = [] PAGE_EXTENSIONS = [] # use default leonardo auth urls LEONARDO_AUTH = True try: # full settings from leonardo_site.local.settings import * except ImportError: pass try: # local settings from local_settings import * except ImportError: warnings.warn( 'local_settings was not found in $PYTHONPATH !', ImportWarning) REVERSION_MIDDLEWARE = [ 'reversion.middleware.RevisionMiddleware'] OAUTH_CTP = [ "allauth.socialaccount.context_processors.socialaccount" ] APPS = merge(APPS, default.core) if 'media' in APPS: FILER_IMAGE_MODEL = 'leonardo.module.media.models.Image' try: from leonardo.conf.horizon import * from leonardo.conf.static import * except Exception as e: pass FEINCMS_TIDY_HTML = False APPLICATION_CHOICES = [] ADD_JS_FILES = [] ADD_CSS_FILES = [] ADD_SCSS_FILES = [] ADD_JS_SPEC_FILES = [] ADD_ANGULAR_MODULES = [] ADD_MODULE_ACTIONS = [] ADD_MIGRATION_MODULES = {} CONSTANCE_CONFIG_GROUPS = {} ABSOLUTE_URL_OVERRIDES = {} MODULE_URLS = {} if LEONARDO_SYSTEM_MODULE: APPS = merge(APPS, ['system']) HORIZON_CONFIG['system_module'] = True else: HORIZON_CONFIG['system_module'] = False # override settings try: from leonardo_site.conf.feincms import * except ImportError: pass from django.utils.importlib import import_module # noqa from django.utils.module_loading import module_has_submodule # noqa WIDGETS = {} # critical time to import modules _APPS = leonardo.get_app_modules(APPS) if LEONARDO_MODULE_AUTO_INCLUDE: # fined and merge with defined app modules _APPS = merge(get_leonardo_modules(), _APPS) # sort modules _APPS = sorted(_APPS, key=lambda m: getattr(m, 'LEONARDO_ORDERING', 1000)) for mod in _APPS: try: # load all settings key if module_has_submodule(mod, "settings"): try: settings_mod = import_module( '{0}.settings'.format(mod.__name__)) for k in dir(settings_mod): if not k.startswith("_"): val = getattr(settings_mod, k, None) globals()[k] = val locals()[k] = val except Exception as e: warnings.warn( 'Exception "{}" raised during loading ' 'settings from {}'.format(str(e), mod)) mod_cfg = get_conf_from_module(mod) APPLICATION_CHOICES = merge(APPLICATION_CHOICES, mod_cfg.plugins) INSTALLED_APPS = merge(INSTALLED_APPS, mod_cfg.apps) MIDDLEWARE_CLASSES = merge(MIDDLEWARE_CLASSES, mod_cfg.middlewares) AUTHENTICATION_BACKENDS = merge( AUTHENTICATION_BACKENDS, mod_cfg.auth_backends) PAGE_EXTENSIONS = merge(PAGE_EXTENSIONS, mod_cfg.page_extensions) ADD_JS_FILES = merge(ADD_JS_FILES, mod_cfg.js_files) ADD_MODULE_ACTIONS = merge(ADD_MODULE_ACTIONS, mod_cfg.module_actions) if mod_cfg.urls_conf: MODULE_URLS[mod_cfg.urls_conf] = {'is_public': mod_cfg.public} # TODO move to utils.settings # support for one level nested in config dictionary for config_key, config_value in six.iteritems(mod_cfg.config): if isinstance(config_value, dict): CONSTANCE_CONFIG_GROUPS.update({config_key: config_value}) for c_key, c_value in six.iteritems(config_value): mod_cfg.config[c_key] = c_value # remove from main dict mod_cfg.config.pop(config_key) else: if isinstance(mod_cfg.optgroup, six.string_types): CONSTANCE_CONFIG_GROUPS.update({ mod_cfg.optgroup: mod_cfg.config}) else: CONSTANCE_CONFIG_GROUPS.update({ 'ungrouped': mod_cfg.config}) # import and update absolute overrides for model, method in six.iteritems(mod_cfg.absolute_url_overrides): try: _mod = import_module(".".join(method.split('.')[:-1])) ABSOLUTE_URL_OVERRIDES[model] = getattr(_mod, method.split('.')[-1]) except Exception as e: raise e for nav_extension in mod_cfg.navigation_extensions: try: import_module(nav_extension) except ImportError: pass CONSTANCE_CONFIG.update(mod_cfg.config) ADD_MIGRATION_MODULES.update(mod_cfg.migration_modules) ADD_JS_SPEC_FILES = merge(ADD_JS_SPEC_FILES, mod_cfg.js_spec_files) ADD_CSS_FILES = merge(ADD_CSS_FILES, mod_cfg.css_files) ADD_SCSS_FILES = merge(ADD_SCSS_FILES, mod_cfg.scss_files) ADD_ANGULAR_MODULES = merge( ADD_ANGULAR_MODULES, mod_cfg.angular_modules) if VERSION[:2] >= (1, 8): TEMPLATES[0]['DIRS'] = merge(TEMPLATES[0]['DIRS'], mod_cfg.dirs) cp = TEMPLATES[0]['OPTIONS']['context_processors'] TEMPLATES[0]['OPTIONS']['context_processors'] = merge( cp, mod_cfg.context_processors) else: TEMPLATE_CONTEXT_PROCESSORS = merge( TEMPLATE_CONTEXT_PROCESSORS, mod_cfg.context_processors) TEMPLATE_DIRS = merge(TEMPLATE_DIRS, mod_cfg.dirs) # collect grouped widgets if isinstance(mod_cfg.optgroup, six.string_types): WIDGETS[mod_cfg.optgroup] = merge( getattr(WIDGETS, mod_cfg.optgroup, []), mod_cfg.widgets) else: if DEBUG: warnings.warn('You have ungrouped widgets' ', please specify your ``optgroup``' 'which categorize your widgets') WIDGETS['ungrouped'] = merge( getattr(WIDGETS, 'ungrouped', []), mod_cfg.widgets) except Exception as e: warnings.warn( 'Exception "{}" raised during loading ' 'module {}'.format(str(e), mod)) setattr(leonardo, 'js_files', ADD_JS_FILES) setattr(leonardo, 'css_files', ADD_CSS_FILES) setattr(leonardo, 'scss_files', ADD_SCSS_FILES) setattr(leonardo, 'js_spec_files', ADD_JS_SPEC_FILES) setattr(leonardo, 'angular_modules', ADD_ANGULAR_MODULES) setattr(leonardo, 'module_actions', ADD_MODULE_ACTIONS) setattr(leonardo, 'widgets', WIDGETS) from leonardo.module.web.models import Page from leonardo.module.web.widget import ApplicationWidget # register external apps Page.create_content_type( ApplicationWidget, APPLICATIONS=APPLICATION_CHOICES) # register widgets for optgroup, _widgets in six.iteritems(WIDGETS): for widget in _widgets: Page.create_content_type(widget, optgroup=optgroup) Page.register_extensions(*PAGE_EXTENSIONS) Page.register_default_processors(LEONARDO_FRONTEND_EDITING) # enable reversion for every req if 'reversion' in INSTALLED_APPS: MIDDLEWARE_CLASSES = merge(REVERSION_MIDDLEWARE, MIDDLEWARE_CLASSES) # FINALLY OVERRIDE ALL try: # local settings from local_settings import * except ImportError: warnings.warn( 'Missing local_settings !') try: # full settings from leonardo_site.local.settings import * except ImportError: pass # and again merge core with others APPS = merge(APPS, default.core) setattr(leonardo, 'apps', APPS) setattr(leonardo, 'page_extensions', PAGE_EXTENSIONS) setattr(leonardo, 'plugins', APPLICATION_CHOICES) MIGRATION_MODULES.update(ADD_MIGRATION_MODULES) # Add HORIZON_CONFIG to the context information for offline compression COMPRESS_OFFLINE_CONTEXT = { 'STATIC_URL': STATIC_URL, 'HORIZON_CONFIG': HORIZON_CONFIG, } if DEBUG: # debug try: import debug_toolbar INSTALLED_APPS = merge(INSTALLED_APPS, ['debug_toolbar']) INTERNAL_IPS = ['10.10.10.1', '127.0.0.1'] DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', 'debug_toolbar.panels.profiling.ProfilingPanel' ] except ImportError: if DEBUG: warnings.warn('DEBUG is set to True but, DEBUG tools ' 'is not installed please run ' '"pip install django-leonardo[debug]"') # async messages try: import async_messages INSTALLED_APPS = merge(INSTALLED_APPS, ['async_messages']) MIDDLEWARE_CLASSES = merge(MIDDLEWARE_CLASSES, ['async_messages.middleware.AsyncMiddleware']) except ImportError: pass """ LOG.debug('ASYNC MESSAGES is not installed' ' install for new messaging features ' '"pip install django-async-messages"') """ # use js files instead of horizon HORIZON_CONFIG['js_files'] = leonardo.js_files HORIZON_CONFIG['js_spec_files'] = leonardo.js_spec_files HORIZON_CONFIG['css_files'] = leonardo.css_files HORIZON_CONFIG['scss_files'] = leonardo.scss_files HORIZON_CONFIG['angular_modules'] = leonardo.angular_modules HORIZON_CONFIG['module_actions'] = leonardo.module_actions # path horizon config from horizon import conf conf.HORIZON_CONFIG = HORIZON_CONFIG cleanup imports and configure defalt logging from __future__ import absolute_import import os import six import logging import warnings from django import VERSION from leonardo.base import leonardo, default from leonardo.utils.settings import (get_conf_from_module, merge, get_leonardo_modules) _file_path = os.path.abspath(os.path.dirname(__file__)).split('/') BASE_DIR = '/'.join(_file_path[0:-2]) EMAIL = { 'HOST': 'mail.domain.com', 'PORT': '25', 'USER': 'username', 'PASSWORD': 'pwd', 'SECURITY': True, } RAVEN_CONFIG = {} ALLOWED_HOSTS = ['*'] USE_TZ = True DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('admin', 'mail@leonardo.cz'), ) DEFAULT_CHARSET = 'utf-8' MANAGERS = ADMINS SITE_ID = 1 SITE_NAME = 'Leonardo' TIME_ZONE = 'Europe/Prague' LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', 'EN'), ('cs', 'CS'), ) USE_I18N = True MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' STATIC_URL = '/static/' if VERSION[:2] >= (1, 8): TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join( os.path.dirname(os.path.realpath(__file__)), 'templates') ], 'OPTIONS': { 'context_processors': default.context_processors, 'loaders': [ 'dbtemplates.loader.Loader', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'horizon.loaders.TemplateLoader', ] }, }, ] else: TEMPLATE_DIRS = [ os.path.join( os.path.dirname(os.path.realpath(__file__)), 'templates') ] TEMPLATE_CONTEXT_PROCESSORS = default.context_processors TEMPLATE_LOADERS = ( 'dbtemplates.loader.Loader', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'horizon.loaders.TemplateLoader', ) DBTEMPLATES_USE_REVERSION = True DBTEMPLATES_MEDIA_PREFIX = '/static-/' DBTEMPLATES_USE_CODEMIRROR = False DBTEMPLATES_USE_TINYMCE = False DBTEMPLATES_AUTO_POPULATE_CONTENT = True DBTEMPLATES_ADD_DEFAULT_SITE = True FILER_ENABLE_PERMISSIONS = True # noqa MIDDLEWARE_CLASSES = default.middlewares ROOT_URLCONF = 'leonardo.urls' LEONARDO_BOOTSTRAP_URL = 'http://github.com/django-leonardo/django-leonardo/raw/develop/contrib/bootstrap/demo.yaml' MARKITUP_FILTER = ('markitup.renderers.render_rest', {'safe_mode': True}) INSTALLED_APPS = default.apps # For easy_thumbnails to support retina displays (recent MacBooks, iOS) FEINCMS_USE_PAGE_ADMIN = False LEONARDO_USE_PAGE_ADMIN = True FEINCMS_DEFAULT_PAGE_MODEL = 'web.Page' CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_CONFIG = {} # enable auto loading packages LEONARDO_MODULE_AUTO_INCLUDE = True # enable system module LEONARDO_SYSTEM_MODULE = True ########################## STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", 'compressor.finders.CompressorFinder', ) LOGIN_URL = '/auth/login/' LOGIN_REDIRECT_URL = '/' LOGOUT_URL = "/auth/logout" LOGOUT_ON_GET = True AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': 'DEBUG', 'handlers': ['console'], }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'leonardo_app.log', 'formatter': 'verbose' }, }, 'loggers': { 'django.request': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'leonardo': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, } } CRISPY_TEMPLATE_PACK = 'bootstrap3' SECRET_KEY = None APPS = [] PAGE_EXTENSIONS = [] # use default leonardo auth urls LEONARDO_AUTH = True try: # full settings from leonardo_site.local.settings import * except ImportError: pass try: # local settings from local_settings import * except ImportError: warnings.warn( 'local_settings was not found in $PYTHONPATH !', ImportWarning) REVERSION_MIDDLEWARE = [ 'reversion.middleware.RevisionMiddleware'] OAUTH_CTP = [ "allauth.socialaccount.context_processors.socialaccount" ] APPS = merge(APPS, default.core) if 'media' in APPS: FILER_IMAGE_MODEL = 'leonardo.module.media.models.Image' try: from leonardo.conf.horizon import * from leonardo.conf.static import * except Exception as e: pass FEINCMS_TIDY_HTML = False APPLICATION_CHOICES = [] ADD_JS_FILES = [] ADD_CSS_FILES = [] ADD_SCSS_FILES = [] ADD_JS_SPEC_FILES = [] ADD_ANGULAR_MODULES = [] ADD_MODULE_ACTIONS = [] ADD_MIGRATION_MODULES = {} CONSTANCE_CONFIG_GROUPS = {} ABSOLUTE_URL_OVERRIDES = {} MODULE_URLS = {} if LEONARDO_SYSTEM_MODULE: APPS = merge(APPS, ['system']) HORIZON_CONFIG['system_module'] = True else: HORIZON_CONFIG['system_module'] = False # override settings try: from leonardo_site.conf.feincms import * except ImportError: pass from django.utils.importlib import import_module # noqa from django.utils.module_loading import module_has_submodule # noqa WIDGETS = {} # critical time to import modules _APPS = leonardo.get_app_modules(APPS) if LEONARDO_MODULE_AUTO_INCLUDE: # fined and merge with defined app modules _APPS = merge(get_leonardo_modules(), _APPS) # sort modules _APPS = sorted(_APPS, key=lambda m: getattr(m, 'LEONARDO_ORDERING', 1000)) for mod in _APPS: try: # load all settings key if module_has_submodule(mod, "settings"): try: settings_mod = import_module( '{0}.settings'.format(mod.__name__)) for k in dir(settings_mod): if not k.startswith("_"): val = getattr(settings_mod, k, None) globals()[k] = val locals()[k] = val except Exception as e: warnings.warn( 'Exception "{}" raised during loading ' 'settings from {}'.format(str(e), mod)) mod_cfg = get_conf_from_module(mod) APPLICATION_CHOICES = merge(APPLICATION_CHOICES, mod_cfg.plugins) INSTALLED_APPS = merge(INSTALLED_APPS, mod_cfg.apps) MIDDLEWARE_CLASSES = merge(MIDDLEWARE_CLASSES, mod_cfg.middlewares) AUTHENTICATION_BACKENDS = merge( AUTHENTICATION_BACKENDS, mod_cfg.auth_backends) PAGE_EXTENSIONS = merge(PAGE_EXTENSIONS, mod_cfg.page_extensions) ADD_JS_FILES = merge(ADD_JS_FILES, mod_cfg.js_files) ADD_MODULE_ACTIONS = merge(ADD_MODULE_ACTIONS, mod_cfg.module_actions) if mod_cfg.urls_conf: MODULE_URLS[mod_cfg.urls_conf] = {'is_public': mod_cfg.public} # TODO move to utils.settings # support for one level nested in config dictionary for config_key, config_value in six.iteritems(mod_cfg.config): if isinstance(config_value, dict): CONSTANCE_CONFIG_GROUPS.update({config_key: config_value}) for c_key, c_value in six.iteritems(config_value): mod_cfg.config[c_key] = c_value # remove from main dict mod_cfg.config.pop(config_key) else: if isinstance(mod_cfg.optgroup, six.string_types): CONSTANCE_CONFIG_GROUPS.update({ mod_cfg.optgroup: mod_cfg.config}) else: CONSTANCE_CONFIG_GROUPS.update({ 'ungrouped': mod_cfg.config}) # import and update absolute overrides for model, method in six.iteritems(mod_cfg.absolute_url_overrides): try: _mod = import_module(".".join(method.split('.')[:-1])) ABSOLUTE_URL_OVERRIDES[model] = getattr(_mod, method.split('.')[-1]) except Exception as e: raise e for nav_extension in mod_cfg.navigation_extensions: try: import_module(nav_extension) except ImportError: pass CONSTANCE_CONFIG.update(mod_cfg.config) ADD_MIGRATION_MODULES.update(mod_cfg.migration_modules) ADD_JS_SPEC_FILES = merge(ADD_JS_SPEC_FILES, mod_cfg.js_spec_files) ADD_CSS_FILES = merge(ADD_CSS_FILES, mod_cfg.css_files) ADD_SCSS_FILES = merge(ADD_SCSS_FILES, mod_cfg.scss_files) ADD_ANGULAR_MODULES = merge( ADD_ANGULAR_MODULES, mod_cfg.angular_modules) if VERSION[:2] >= (1, 8): TEMPLATES[0]['DIRS'] = merge(TEMPLATES[0]['DIRS'], mod_cfg.dirs) cp = TEMPLATES[0]['OPTIONS']['context_processors'] TEMPLATES[0]['OPTIONS']['context_processors'] = merge( cp, mod_cfg.context_processors) else: TEMPLATE_CONTEXT_PROCESSORS = merge( TEMPLATE_CONTEXT_PROCESSORS, mod_cfg.context_processors) TEMPLATE_DIRS = merge(TEMPLATE_DIRS, mod_cfg.dirs) # collect grouped widgets if isinstance(mod_cfg.optgroup, six.string_types): WIDGETS[mod_cfg.optgroup] = merge( getattr(WIDGETS, mod_cfg.optgroup, []), mod_cfg.widgets) else: if DEBUG: warnings.warn('You have ungrouped widgets' ', please specify your ``optgroup``' 'which categorize your widgets') WIDGETS['ungrouped'] = merge( getattr(WIDGETS, 'ungrouped', []), mod_cfg.widgets) except Exception as e: warnings.warn( 'Exception "{}" raised during loading ' 'module {}'.format(str(e), mod)) setattr(leonardo, 'js_files', ADD_JS_FILES) setattr(leonardo, 'css_files', ADD_CSS_FILES) setattr(leonardo, 'scss_files', ADD_SCSS_FILES) setattr(leonardo, 'js_spec_files', ADD_JS_SPEC_FILES) setattr(leonardo, 'angular_modules', ADD_ANGULAR_MODULES) setattr(leonardo, 'module_actions', ADD_MODULE_ACTIONS) setattr(leonardo, 'widgets', WIDGETS) from leonardo.module.web.models import Page from leonardo.module.web.widget import ApplicationWidget # register external apps Page.create_content_type( ApplicationWidget, APPLICATIONS=APPLICATION_CHOICES) # register widgets for optgroup, _widgets in six.iteritems(WIDGETS): for widget in _widgets: Page.create_content_type(widget, optgroup=optgroup) Page.register_extensions(*PAGE_EXTENSIONS) Page.register_default_processors(LEONARDO_FRONTEND_EDITING) # enable reversion for every req if 'reversion' in INSTALLED_APPS: MIDDLEWARE_CLASSES = merge(REVERSION_MIDDLEWARE, MIDDLEWARE_CLASSES) # FINALLY OVERRIDE ALL try: # local settings from local_settings import * except ImportError: warnings.warn( 'Missing local_settings !') try: # full settings from leonardo_site.local.settings import * except ImportError: pass # and again merge core with others APPS = merge(APPS, default.core) setattr(leonardo, 'apps', APPS) setattr(leonardo, 'page_extensions', PAGE_EXTENSIONS) setattr(leonardo, 'plugins', APPLICATION_CHOICES) MIGRATION_MODULES.update(ADD_MIGRATION_MODULES) # Add HORIZON_CONFIG to the context information for offline compression COMPRESS_OFFLINE_CONTEXT = { 'STATIC_URL': STATIC_URL, 'HORIZON_CONFIG': HORIZON_CONFIG, } if DEBUG: # debug try: import debug_toolbar INSTALLED_APPS = merge(INSTALLED_APPS, ['debug_toolbar']) INTERNAL_IPS = ['10.10.10.1', '127.0.0.1'] DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', 'debug_toolbar.panels.profiling.ProfilingPanel' ] except ImportError: if DEBUG: warnings.warn('DEBUG is set to True but, DEBUG tools ' 'is not installed please run ' '"pip install django-leonardo[debug]"') # async messages try: import async_messages INSTALLED_APPS = merge(INSTALLED_APPS, ['async_messages']) MIDDLEWARE_CLASSES = merge(MIDDLEWARE_CLASSES, ['async_messages.middleware.AsyncMiddleware']) except ImportError: pass """ LOG.debug('ASYNC MESSAGES is not installed' ' install for new messaging features ' '"pip install django-async-messages"') """ # use js files instead of horizon HORIZON_CONFIG['js_files'] = leonardo.js_files HORIZON_CONFIG['js_spec_files'] = leonardo.js_spec_files HORIZON_CONFIG['css_files'] = leonardo.css_files HORIZON_CONFIG['scss_files'] = leonardo.scss_files HORIZON_CONFIG['angular_modules'] = leonardo.angular_modules HORIZON_CONFIG['module_actions'] = leonardo.module_actions # path horizon config from horizon import conf conf.HORIZON_CONFIG = HORIZON_CONFIG if DEBUG: logging.basicConfig(level=logging.DEBUG)
from datetime import date from itertools import chain from django.conf import settings from django.db.models import Q from django.utils.translation import override from django_cron import CronJobBase, Schedule from sentry_sdk import capture_exception from .models.courses import CourseRegistration from .models.events import EventRegistration class SentryCronJobBase(CronJobBase): def dojob(self): raise NotImplementedError(f'{self.__class__.__name__}.dojob must be implemented.') def do(self): try: with override(settings.LANGUAGE_CODE): return self.dojob() except Exception: capture_exception() raise class SendPaymentRequest(SentryCronJobBase): schedule = Schedule(run_at_times=[settings.CRON_SEND_PAYMENT_REQUEST_TIME]) code = 'leprikon.cronjobs.SendPaymentRequest' def dojob(self): today = date.today() for registration in chain( CourseRegistration.objects.filter( subject__course__school_year_division__periods__due_from=today, approved__isnull=False ).filter(Q(payment_requested=None) | Q(payment_requested__date__lt=today)), EventRegistration.objects.filter( subject__event__due_from=today, approved__isnull=False, ).filter(Q(payment_requested=None) | Q(payment_requested__date__lt=today)), ): registration.request_payment(None) Don't send payment requests for canceled registrations from datetime import date from itertools import chain from django.conf import settings from django.db.models import Q from django.utils.translation import override from django_cron import CronJobBase, Schedule from sentry_sdk import capture_exception from .models.courses import CourseRegistration from .models.events import EventRegistration class SentryCronJobBase(CronJobBase): def dojob(self): raise NotImplementedError(f'{self.__class__.__name__}.dojob must be implemented.') def do(self): try: with override(settings.LANGUAGE_CODE): return self.dojob() except Exception: capture_exception() raise class SendPaymentRequest(SentryCronJobBase): schedule = Schedule(run_at_times=[settings.CRON_SEND_PAYMENT_REQUEST_TIME]) code = 'leprikon.cronjobs.SendPaymentRequest' def dojob(self): today = date.today() for registration in chain( CourseRegistration.objects.filter( subject__course__school_year_division__periods__due_from=today, approved__isnull=False, canceled__isnull=True, ).filter(Q(payment_requested=None) | Q(payment_requested__date__lt=today)), EventRegistration.objects.filter( subject__event__due_from=today, approved__isnull=False, canceled__isnull=True, ).filter(Q(payment_requested=None) | Q(payment_requested__date__lt=today)), ): registration.request_payment(None)
def execute(): import webnotes from webnotes.model.code import get_obj sc_obj = get_obj("Sales Common") si = webnotes.conn.sql("""select si.name from `tabSales Invoice` si, `tabSales Invoice Item` si_item where si_item.parent = si.name and si.docstatus = 1 and ifnull(si.is_pos, 0) = 1 and ifnull(si_item.sales_order, '') != '' """) for d in si: sc_obj.update_prevdoc_detail(1, get_obj("Sales Invoice", d[0], with_children=1)) patch: update % delievered and % billed in SO if pos made against that so def execute(): import webnotes from webnotes.model.code import get_obj sc_obj = get_obj("Sales Common") si = webnotes.conn.sql("""select distinct si.name from `tabSales Invoice` si, `tabSales Invoice Item` si_item where si_item.parent = si.name and si.docstatus = 1 and ifnull(si.is_pos, 0) = 1 and ifnull(si_item.sales_order, '') != '' """) for d in si: sc_obj.update_prevdoc_detail(1, get_obj("Sales Invoice", d[0], with_children=1))
import argparse import locale import curses import time import pcap import sys from .stat_processor import StatProcessor from .display.sessions import SessionsPad from .display.device import DevicePad from . import getstats def _init_colors(): colors = {} curses.start_color() curses.use_default_colors() curses_colors = {"green": curses.COLOR_GREEN, "yellow": curses.COLOR_YELLOW, "red": curses.COLOR_RED, "cyan": curses.COLOR_CYAN, } for index, (color_name, curses_color) in enumerate(curses_colors.iteritems()): curses.init_pair(index + 1, curses_color, -1) colors[color_name] = index + 1 return colors def main(): arg_parser = argparse.ArgumentParser(description="ifstat - network interface statistics utility") arg_parser.add_argument(dest='device', help='The device name to get stats for') arg_parser.add_argument('--interval', '-i', dest='interval', default=1.0, type=float, help='Interval to gather and display stats') args = arg_parser.parse_args() if args.device not in pcap.findalldevs(): sys.stderr.write('Error: No such device %s \n' % (args.device, )) return collector = getstats.StatCollector(args.device) collector.start() raw_stats = collector.get_stats() stat_processor = StatProcessor(raw_stats) window = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(0) window.keypad(1) # XXX: halfdelay is in tenths of seconds curses.halfdelay(int(args.interval * 10)) colors = _init_colors() last_time = time.time() sessions_pad = SessionsPad(colors=colors) device_pad = DevicePad(args.device, colors=colors, ylocation=sessions_pad.get_y_size()) current_stats = {"device": {}, "sessions": []} try: running = True while running: # XXX: Get & process new stats only when the intervals have passed current_time = time.time() if current_time - last_time >= args.interval: raw_stats = collector.get_stats() current_stats = stat_processor.process_new_stats(raw_stats, args.interval) last_time = current_time maxy, maxx = window.getmaxyx() sessions_pad.display(maxy, maxx, current_stats["sessions"]) device_pad.display(maxy, maxx, current_stats["device"]) key = window.getch() if key != -1: sessions_pad.key(key) device_pad.key(key) if key == ord('q'): collector.stop() running = False finally: curses.nocbreak() curses.echo() curses.endwin() Added a locale setting import argparse import locale import curses import time import pcap import sys from .stat_processor import StatProcessor from .display.sessions import SessionsPad from .display.device import DevicePad from . import getstats def _init_colors(): colors = {} curses.start_color() curses.use_default_colors() curses_colors = {"green": curses.COLOR_GREEN, "yellow": curses.COLOR_YELLOW, "red": curses.COLOR_RED, "cyan": curses.COLOR_CYAN, } for index, (color_name, curses_color) in enumerate(curses_colors.iteritems()): curses.init_pair(index + 1, curses_color, -1) colors[color_name] = index + 1 return colors def main(): arg_parser = argparse.ArgumentParser(description="ifstat - network interface statistics utility") arg_parser.add_argument(dest='device', help='The device name to get stats for') arg_parser.add_argument('--interval', '-i', dest='interval', default=1.0, type=float, help='Interval to gather and display stats') args = arg_parser.parse_args() if args.device not in pcap.findalldevs(): sys.stderr.write('Error: No such device %s \n' % (args.device, )) return collector = getstats.StatCollector(args.device) collector.start() raw_stats = collector.get_stats() stat_processor = StatProcessor(raw_stats) locale.setlocale(locale.LC_ALL, '') window = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(0) window.keypad(1) # XXX: halfdelay is in tenths of seconds curses.halfdelay(int(args.interval * 10)) colors = _init_colors() last_time = time.time() sessions_pad = SessionsPad(colors=colors) device_pad = DevicePad(args.device, colors=colors, ylocation=sessions_pad.get_y_size()) current_stats = {"device": {}, "sessions": []} try: running = True while running: # XXX: Get & process new stats only when the intervals have passed current_time = time.time() if current_time - last_time >= args.interval: raw_stats = collector.get_stats() current_stats = stat_processor.process_new_stats(raw_stats, args.interval) last_time = current_time maxy, maxx = window.getmaxyx() sessions_pad.display(maxy, maxx, current_stats["sessions"]) device_pad.display(maxy, maxx, current_stats["device"]) key = window.getch() if key != -1: sessions_pad.key(key) device_pad.key(key) if key == ord('q'): collector.stop() running = False finally: curses.nocbreak() curses.echo() curses.endwin()
'''Image Analogies with Keras Before running this script, download the weights for the VGG16 model at: https://drive.google.com/file/d/0Bz7KyqmuGsilT0J5dmRCM0ROVHc/view?usp=sharing (source: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3) and make sure the variable `weights_path` in this script matches the location of the file. This is adapted from the Keras "neural style transfer" example code. Run the script with: ``` python image_analogy.py path_to_your_base_image_mask.jpg path_to_your_reference.jpg path_to_new_mask prefix_for_results ``` e.g.: ``` python image_analogy.py images/arch-mask.jpg images/arch.jpg images/arch-newmask.jpg ``` It is preferrable to run this script on GPU, for speed. ''' from __future__ import print_function from scipy.misc import imread, imresize, imsave import numpy as np from scipy.optimize import fmin_l_bfgs_b import time import os import argparse import h5py from keras.models import Sequential from keras.layers.convolutional import Convolution2D, ZeroPadding2D, MaxPooling2D from keras import backend as K parser = argparse.ArgumentParser(description='Neural style transfer with Keras.') parser.add_argument('base_mask_image_path', metavar='ref', type=str, help='Path to the reference image mask.') parser.add_argument('base_image_path', metavar='base', type=str, help='Path to the source image.') parser.add_argument('new_mask_image_path', metavar='ref', type=str, help='Path to the new mask for generation.') parser.add_argument('result_prefix', metavar='res_prefix', type=str, help='Prefix for the saved results.') args = parser.parse_args() base_image_path = args.base_image_path base_mask_image_path = args.base_mask_image_path new_mask_image_path = args.new_mask_image_path result_prefix = args.result_prefix weights_path = 'vgg16_weights.h5' # these are the weights of the different loss components total_variation_weight = 1.0 analogy_weight = 1.0 style_weight = 1.0 patch_size = 3 patch_stride = 1 analogy_layers = ['conv3_1', 'conv4_1'] mrf_layers = ['conv3_1', 'conv4_1'] # dimensions of the generated picture. full_img_width = 450 full_img_height = 450 num_iterations_per_scale = 7 num_scales = 3 # run the algorithm at a few different sizes min_scale_factor = 0.25 if num_scales > 1: step_scale_factor = (1 - min_scale_factor) / (num_scales - 1) else: step_scale_factor = 0.0 min_scale_factor = 1.0 # util function to open, resize and format pictures into appropriate tensors def load_and_preprocess_image(image_path, img_width, img_height): img = preprocess_image(imread(image_path), img_width, img_height) return img # util function to open, resize and format pictures into appropriate tensors def preprocess_image(x, img_width, img_height): img = imresize(x, (img_height, img_width)) img = img.transpose((2, 0, 1)).astype('float64') img[:, :, 0] -= 103.939 img[:, :, 1] -= 116.779 img[:, :, 2] -= 123.68 img = np.expand_dims(img, axis=0) return img # util function to convert a tensor into a valid image def deprocess_image(x): x[:, :, 0] += 103.939 x[:, :, 1] += 116.779 x[:, :, 2] += 123.68 x = x.transpose((1, 2, 0)) x = np.clip(x, 0, 255).astype('uint8') return x # loss functions def make_patches(x, patch_size, patch_stride): from theano.tensor.nnet.neighbours import images2neibs x = K.expand_dims(x, 0) patches = images2neibs(x, (patch_size, patch_size), (patch_stride, patch_stride), mode='valid') # neibs are sorted per-channel patches = K.reshape(patches, (K.shape(x)[1], K.shape(patches)[0] // K.shape(x)[1], patch_size, patch_size)) patches = K.permute_dimensions(patches, (1, 0, 2, 3)) patches_norm = K.l2_normalize(patches, 1) return patches, patches_norm def find_patch_matches(a, b): # find the best matching patches # we want cross-correlation here so flip the kernels convs = K.conv2d(a, b[:, :, ::-1, ::-1], border_mode='valid') argmax = K.argmax(convs, axis=1) return argmax # CNNMRF http://arxiv.org/pdf/1601.04589v1.pdf def mrf_loss(style, combination, patch_size=3, patch_stride=1): # extract patches from feature maps combination_patches, combination_patches_norm = make_patches(combination, patch_size, patch_stride) style_patches, style_patches_norm = make_patches(style, patch_size, patch_stride) # find best patches and calculate loss patch_ids = find_patch_matches(combination_patches_norm, style_patches_norm) best_style_patches = K.reshape(style_patches[patch_ids], K.shape(combination_patches)) loss = K.sum(K.square(best_style_patches - combination_patches)) return loss # http://www.mrl.nyu.edu/projects/image-analogies/index.html def analogy_loss(a, b, a_prime, b_prime, patch_size=3, patch_stride=1): # extract patches from feature maps a_patches, a_patches_norm = make_patches(a, patch_size, patch_stride) a_prime_patches, a_prime_patches_norm = make_patches(a_prime, patch_size, patch_stride) b_patches, b_patches_norm = make_patches(b, patch_size, patch_stride) b_prime_patches, b_prime_patches_norm = make_patches(b_prime, patch_size, patch_stride) # find best patches and calculate loss q = find_patch_matches(a_prime_patches_norm, a_patches_norm) best_patches = K.reshape(b_patches[q], K.shape(b_prime_patches)) loss = K.sum(K.square(best_patches - b_prime_patches)) return loss # the 3rd loss function, total variation loss, # designed to keep the generated image locally coherent def total_variation_loss(x, img_width, img_height): assert K.ndim(x) == 4 a = K.square(x[:, :, 1:, :img_width-1] - x[:, :, :img_height-1, :img_width-1]) b = K.square(x[:, :, :img_height-1, 1:] - x[:, :, :img_height-1, :img_width-1]) return K.sum(K.pow(a + b, 1.25)) full_base_image = imread(base_image_path) full_base_mask_image = imread(base_mask_image_path) full_new_mask_image = imread(new_mask_image_path) x = None for scale_i in range(num_scales): scale_factor = (scale_i * step_scale_factor) + min_scale_factor img_width = int(round(full_img_width * scale_factor)) img_height = int(round(full_img_height * scale_factor)) if x is None: x = np.random.uniform(0, 255, (1, 3, img_width, img_height)) else: x = preprocess_image(deprocess_image(x), img_width, img_height) print(img_width, img_height) # get tensor representations of our images base_image = preprocess_image(full_base_image, img_width, img_height) base_mask_image = preprocess_image(full_base_mask_image, img_width, img_height) new_mask_image = preprocess_image(full_new_mask_image, img_width, img_height) # this will contain our generated image vgg_input = K.placeholder((1, 3, img_height, img_width)) # build the VGG16 network first_layer = ZeroPadding2D((1, 1), input_shape=(3, img_height, img_width)) first_layer.input = vgg_input model = Sequential() model.add(first_layer) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(64, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) # load the weights of the VGG16 networks # (trained on ImageNet, won the ILSVRC competition in 2014) # note: when there is a complete match between your model definition # and your weight savefile, you can simply call model.load_weights(filename) assert os.path.exists(weights_path), 'Model weights not found (see "weights_path" variable in script).' f = h5py.File(weights_path) for k in range(f.attrs['nb_layers']): if k >= len(model.layers): # we don't look at the last (fully-connected) layers in the savefile break g = f['layer_{}'.format(k)] weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])] model.layers[k].set_weights(weights) layer = model.layers[k] if isinstance(layer, Convolution2D): layer.W = layer.W[:, :, ::-1, ::-1] f.close() print('Model loaded.') # get the symbolic outputs of each "key" layer (we gave them unique names). outputs_dict = dict([(layer.name, layer.get_output()) for layer in model.layers]) def get_features(x, layers): features = {} for layer_name in layers: f = K.function([vgg_input], outputs_dict[layer_name]) features[layer_name] = f([x]) return features print('Precomputing static features...') all_base_mask_features = get_features(base_mask_image, set(analogy_layers + mrf_layers)) all_base_image_features = get_features(base_image, set(analogy_layers + mrf_layers)) all_new_mask_features = get_features(new_mask_image, set(analogy_layers + mrf_layers)) # combine the loss functions into a single scalar print('Building loss function...') loss = K.variable(0.) for layer_name in analogy_layers: layer_features = outputs_dict[layer_name] base_mask_features = K.variable(all_base_mask_features[layer_name][0]) base_image_features = K.variable(all_base_image_features[layer_name][0]) new_mask_features = K.variable(all_new_mask_features[layer_name][0]) combination_features = layer_features[0, :, :, :] al = analogy_loss(base_mask_features, base_image_features, new_mask_features, combination_features) loss += (analogy_weight / len(analogy_layers)) * al for layer_name in mrf_layers: layer_features = outputs_dict[layer_name] base_image_features = K.variable(all_base_image_features[layer_name][0]) combination_features = layer_features[0, :, :, :] sl = mrf_loss(base_image_features, combination_features, patch_size=patch_size, patch_stride=patch_stride) loss += (style_weight / len(mrf_layers)) * sl loss += total_variation_weight * total_variation_loss(vgg_input, img_width, img_height) # get the gradients of the generated image wrt the loss grads = K.gradients(loss, vgg_input) outputs = [loss] if type(grads) in {list, tuple}: outputs += grads else: outputs.append(grads) f_outputs = K.function([vgg_input], outputs) def eval_loss_and_grads(x): x = x.reshape((1, 3, img_height, img_width)) outs = f_outputs([x]) loss_value = outs[0] if len(outs[1:]) == 1: grad_values = outs[1].flatten().astype('float64') else: grad_values = np.array(outs[1:]).flatten().astype('float64') return loss_value, grad_values # this Evaluator class makes it possible # to compute loss and gradients in one pass # while retrieving them via two separate functions, # "loss" and "grads". This is done because scipy.optimize # requires separate functions for loss and gradients, # but computing them separately would be inefficient. class Evaluator(object): def __init__(self): self.loss_value = None self.grads_values = None def loss(self, x): assert self.loss_value is None loss_value, grad_values = eval_loss_and_grads(x) self.loss_value = loss_value self.grad_values = grad_values return self.loss_value def grads(self, x): assert self.loss_value is not None grad_values = np.copy(self.grad_values) self.loss_value = None self.grad_values = None return grad_values evaluator = Evaluator() # run scipy-based optimization (L-BFGS) over the pixels of the generated image # so as to minimize the neural style loss for i in range(num_iterations_per_scale): # scale_i + 2): # print('Start of iteration', scale_i, i) start_time = time.time() x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(), fprime=evaluator.grads, maxfun=20) print('Current loss value:', min_val) # save current generated image x = x.reshape((3, img_height, img_width)) img = deprocess_image(x) fname = result_prefix + '_at_iteration_%d_%d.png' % (scale_i, i) imsave(fname, img) end_time = time.time() print('Image saved as', fname) print('Iteration %d completed in %ds' % (i, end_time - start_time)) Subtracting the mean pixel value is somehow causing that white border artifact '''Image Analogies with Keras Before running this script, download the weights for the VGG16 model at: https://drive.google.com/file/d/0Bz7KyqmuGsilT0J5dmRCM0ROVHc/view?usp=sharing (source: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3) and make sure the variable `weights_path` in this script matches the location of the file. This is adapted from the Keras "neural style transfer" example code. Run the script with: ``` python image_analogy.py path_to_your_base_image_mask.jpg path_to_your_reference.jpg path_to_new_mask prefix_for_results ``` e.g.: ``` python image_analogy.py images/arch-mask.jpg images/arch.jpg images/arch-newmask.jpg ``` It is preferrable to run this script on GPU, for speed. ''' from __future__ import print_function from scipy.misc import imread, imresize, imsave import numpy as np from scipy.optimize import fmin_l_bfgs_b import time import os import argparse import h5py from keras.models import Sequential from keras.layers.convolutional import Convolution2D, ZeroPadding2D, MaxPooling2D from keras import backend as K parser = argparse.ArgumentParser(description='Neural style transfer with Keras.') parser.add_argument('base_mask_image_path', metavar='ref', type=str, help='Path to the reference image mask.') parser.add_argument('base_image_path', metavar='base', type=str, help='Path to the source image.') parser.add_argument('new_mask_image_path', metavar='ref', type=str, help='Path to the new mask for generation.') parser.add_argument('result_prefix', metavar='res_prefix', type=str, help='Prefix for the saved results.') args = parser.parse_args() base_image_path = args.base_image_path base_mask_image_path = args.base_mask_image_path new_mask_image_path = args.new_mask_image_path result_prefix = args.result_prefix weights_path = 'vgg16_weights.h5' # these are the weights of the different loss components total_variation_weight = 1.0 analogy_weight = 1.0 style_weight = 1.0 patch_size = 3 patch_stride = 1 analogy_layers = ['conv3_1', 'conv4_1'] mrf_layers = ['conv3_1', 'conv4_1'] # dimensions of the generated picture. full_img_width = 450 full_img_height = 450 num_iterations_per_scale = 7 num_scales = 3 # run the algorithm at a few different sizes min_scale_factor = 0.25 if num_scales > 1: step_scale_factor = (1 - min_scale_factor) / (num_scales - 1) else: step_scale_factor = 0.0 min_scale_factor = 1.0 # util function to open, resize and format pictures into appropriate tensors def load_and_preprocess_image(image_path, img_width, img_height): img = preprocess_image(imread(image_path), img_width, img_height) return img # util function to open, resize and format pictures into appropriate tensors def preprocess_image(x, img_width, img_height): img = imresize(x, (img_height, img_width)) img = img.transpose((2, 0, 1)).astype('float64') # img[:, :, 0] -= 103.939 # img[:, :, 1] -= 116.779 # img[:, :, 2] -= 123.68 img = np.expand_dims(img, axis=0) return img # util function to convert a tensor into a valid image def deprocess_image(x): # x[:, :, 0] += 103.939 # x[:, :, 1] += 116.779 # x[:, :, 2] += 123.68 x = x.transpose((1, 2, 0)) x = np.clip(x, 0, 255).astype('uint8') return x # loss functions def make_patches(x, patch_size, patch_stride): from theano.tensor.nnet.neighbours import images2neibs x = K.expand_dims(x, 0) patches = images2neibs(x, (patch_size, patch_size), (patch_stride, patch_stride), mode='valid') # neibs are sorted per-channel patches = K.reshape(patches, (K.shape(x)[1], K.shape(patches)[0] // K.shape(x)[1], patch_size, patch_size)) patches = K.permute_dimensions(patches, (1, 0, 2, 3)) patches_norm = K.l2_normalize(patches, 1) return patches, patches_norm def find_patch_matches(a, b): # find the best matching patches # we want cross-correlation here so flip the kernels convs = K.conv2d(a, b[:, :, ::-1, ::-1], border_mode='valid') argmax = K.argmax(convs, axis=1) return argmax # CNNMRF http://arxiv.org/pdf/1601.04589v1.pdf def mrf_loss(style, combination, patch_size=3, patch_stride=1): # extract patches from feature maps combination_patches, combination_patches_norm = make_patches(combination, patch_size, patch_stride) style_patches, style_patches_norm = make_patches(style, patch_size, patch_stride) # find best patches and calculate loss patch_ids = find_patch_matches(combination_patches_norm, style_patches_norm) best_style_patches = K.reshape(style_patches[patch_ids], K.shape(combination_patches)) loss = K.sum(K.square(best_style_patches - combination_patches)) return loss # http://www.mrl.nyu.edu/projects/image-analogies/index.html def analogy_loss(a, b, a_prime, b_prime, patch_size=3, patch_stride=1): # extract patches from feature maps a_patches, a_patches_norm = make_patches(a, patch_size, patch_stride) a_prime_patches, a_prime_patches_norm = make_patches(a_prime, patch_size, patch_stride) b_patches, b_patches_norm = make_patches(b, patch_size, patch_stride) b_prime_patches, b_prime_patches_norm = make_patches(b_prime, patch_size, patch_stride) # find best patches and calculate loss q = find_patch_matches(a_prime_patches_norm, a_patches_norm) best_patches = K.reshape(b_patches[q], K.shape(b_prime_patches)) loss = K.sum(K.square(best_patches - b_prime_patches)) return loss # the 3rd loss function, total variation loss, # designed to keep the generated image locally coherent def total_variation_loss(x, img_width, img_height): assert K.ndim(x) == 4 a = K.square(x[:, :, 1:, :img_width-1] - x[:, :, :img_height-1, :img_width-1]) b = K.square(x[:, :, :img_height-1, 1:] - x[:, :, :img_height-1, :img_width-1]) return K.sum(K.pow(a + b, 1.25)) full_base_image = imread(base_image_path) full_base_mask_image = imread(base_mask_image_path) full_new_mask_image = imread(new_mask_image_path) x = None for scale_i in range(num_scales): scale_factor = (scale_i * step_scale_factor) + min_scale_factor img_width = int(round(full_img_width * scale_factor)) img_height = int(round(full_img_height * scale_factor)) if x is None: x = np.random.uniform(0, 255, (1, 3, img_width, img_height)) else: x = preprocess_image(deprocess_image(x), img_width, img_height) print(img_width, img_height) # get tensor representations of our images base_image = preprocess_image(full_base_image, img_width, img_height) base_mask_image = preprocess_image(full_base_mask_image, img_width, img_height) new_mask_image = preprocess_image(full_new_mask_image, img_width, img_height) # this will contain our generated image vgg_input = K.placeholder((1, 3, img_height, img_width)) # build the VGG16 network first_layer = ZeroPadding2D((1, 1), input_shape=(3, img_height, img_width)) first_layer.input = vgg_input model = Sequential() model.add(first_layer) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(64, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) # load the weights of the VGG16 networks # (trained on ImageNet, won the ILSVRC competition in 2014) # note: when there is a complete match between your model definition # and your weight savefile, you can simply call model.load_weights(filename) assert os.path.exists(weights_path), 'Model weights not found (see "weights_path" variable in script).' f = h5py.File(weights_path) for k in range(f.attrs['nb_layers']): if k >= len(model.layers): # we don't look at the last (fully-connected) layers in the savefile break g = f['layer_{}'.format(k)] weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])] model.layers[k].set_weights(weights) layer = model.layers[k] if isinstance(layer, Convolution2D): layer.W = layer.W[:, :, ::-1, ::-1] f.close() print('Model loaded.') # get the symbolic outputs of each "key" layer (we gave them unique names). outputs_dict = dict([(layer.name, layer.get_output()) for layer in model.layers]) def get_features(x, layers): features = {} for layer_name in layers: f = K.function([vgg_input], outputs_dict[layer_name]) features[layer_name] = f([x]) return features print('Precomputing static features...') all_base_mask_features = get_features(base_mask_image, set(analogy_layers + mrf_layers)) all_base_image_features = get_features(base_image, set(analogy_layers + mrf_layers)) all_new_mask_features = get_features(new_mask_image, set(analogy_layers + mrf_layers)) # combine the loss functions into a single scalar print('Building loss function...') loss = K.variable(0.) for layer_name in analogy_layers: layer_features = outputs_dict[layer_name] base_mask_features = K.variable(all_base_mask_features[layer_name][0]) base_image_features = K.variable(all_base_image_features[layer_name][0]) new_mask_features = K.variable(all_new_mask_features[layer_name][0]) combination_features = layer_features[0, :, :, :] al = analogy_loss(base_mask_features, base_image_features, new_mask_features, combination_features) loss += (analogy_weight / len(analogy_layers)) * al for layer_name in mrf_layers: layer_features = outputs_dict[layer_name] base_image_features = K.variable(all_base_image_features[layer_name][0]) combination_features = layer_features[0, :, :, :] sl = mrf_loss(base_image_features, combination_features, patch_size=patch_size, patch_stride=patch_stride) loss += (style_weight / len(mrf_layers)) * sl loss += total_variation_weight * total_variation_loss(vgg_input, img_width, img_height) # get the gradients of the generated image wrt the loss grads = K.gradients(loss, vgg_input) outputs = [loss] if type(grads) in {list, tuple}: outputs += grads else: outputs.append(grads) f_outputs = K.function([vgg_input], outputs) def eval_loss_and_grads(x): x = x.reshape((1, 3, img_height, img_width)) outs = f_outputs([x]) loss_value = outs[0] if len(outs[1:]) == 1: grad_values = outs[1].flatten().astype('float64') else: grad_values = np.array(outs[1:]).flatten().astype('float64') return loss_value, grad_values # this Evaluator class makes it possible # to compute loss and gradients in one pass # while retrieving them via two separate functions, # "loss" and "grads". This is done because scipy.optimize # requires separate functions for loss and gradients, # but computing them separately would be inefficient. class Evaluator(object): def __init__(self): self.loss_value = None self.grads_values = None def loss(self, x): assert self.loss_value is None loss_value, grad_values = eval_loss_and_grads(x) self.loss_value = loss_value self.grad_values = grad_values return self.loss_value def grads(self, x): assert self.loss_value is not None grad_values = np.copy(self.grad_values) self.loss_value = None self.grad_values = None return grad_values evaluator = Evaluator() # run scipy-based optimization (L-BFGS) over the pixels of the generated image # so as to minimize the neural style loss for i in range(num_iterations_per_scale): # scale_i + 2): # print('Start of iteration', scale_i, i) start_time = time.time() x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(), fprime=evaluator.grads, maxfun=20) print('Current loss value:', min_val) # save current generated image x = x.reshape((3, img_height, img_width)) img = deprocess_image(x) fname = result_prefix + '_at_iteration_%d_%d.png' % (scale_i, i) imsave(fname, img) end_time = time.time() print('Image saved as', fname) print('Iteration %d completed in %ds' % (i, end_time - start_time))
""" Quick test script to show how the automatic sleep optimization works. Change the engine_sleep parameter to see different sleep times. """ import openpathsampling.engines as peng import openpathsampling as paths import numpy as np import os import logging def build_engine(template): opts = { 'n_frames_max' : 10000, # 'engine_sleep' : 20, 'engine_sleep' : 500, 'name_prefix' : "microtest", 'engine_directory' : os.path.dirname(os.path.realpath(__file__)) } engine = peng.ExternalEngine(opts, template) return engine def run(): template = peng.toy.Snapshot(coordinates=np.array([[0.0]]), velocities=np.array([[1.0]])) ensemble = paths.LengthEnsemble(20) engine = build_engine(template) logging.basicConfig(level=logging.INFO) engine.generate_forward(template, ensemble) if __name__ == "__main__": run() Update microtest.py for (long-ago) changed API """ Quick test script to show how the automatic sleep optimization works. Change the engine_sleep parameter to see different sleep times. """ import openpathsampling.engines as peng import openpathsampling as paths import numpy as np import os import logging def build_engine(template): opts = { 'n_frames_max' : 10000, # 'engine_sleep' : 20, 'engine_sleep' : 500, 'name_prefix' : "microtest", 'engine_directory' : os.path.dirname(os.path.realpath(__file__)) } engine = peng.ExternalEngine(opts, template) return engine def run(): template = peng.toy.Snapshot(coordinates=np.array([[0.0]]), velocities=np.array([[1.0]])) ensemble = paths.LengthEnsemble(20) engine = build_engine(template) logging.basicConfig(level=logging.INFO) engine.generate(template, ensemble.can_append, direction=+1) if __name__ == "__main__": run()
import os import sys import tarfile import cStringIO class GlideinTar: """ potential exception needs to be caught by calling routine """ def __init__(self): self.strings = {} self.files = [] def add_file(self, filename, arc_dirname): if os.path.exists(filename): self.files.append((filename, dirname)) def add_string(self, name, string_data): self.strings[name] = string_data def create_tar(self, tf): for file in self.files: file, dirname = file if dirname: tf.add(file, arcname=os.path.join(dirname, os.path.split(file)[-1])) else: tf.add(file) for filename, string in self.strings.items(): fd_str = cStringIO.StringIO(string) fd_str.seek(0) ti = tarfile.TarInfo() ti.size = len(string) ti.name = filename ti.type = tarfile.REGTYPE tf.addfile(ti, fd_str) def create_tar_file(self, fd): tf = tarfile.open(fileobj=fd, mode="w:gz") self.create_tar(tf) tf.close() def create_tar_blob(self): from cStringIO import StringIO file_out = StringIO() tf = tarfile.open(fileobj=file_out, mode="w:gz") self.create_tar(tf) tf.close() return file_out.getvalue() Document and add functionality for tar support. Needed for cloud support. import os import sys import tarfile import cStringIO class FileDoesNotExist(Exception): """File does not exist exception @note: Include the file name in the full_path @ivar full_path: The full path to the missing file. Includes the file name """ def __init__(self, full_path): message = "The file, %s, does not exist." % full_path # Call the base class constructor with the parameters it needs Exception.__init__(self, message) class GlideinTar: """This class provides a container for creating tarballs. The class provides methods to add files and string data (ends up as a file in the tarball). The tarball can be written to a file on disk or written to memory. """ def __init__(self): """Set up the strings dict and the files list The strings dict will hold string data that is to be added to the tar file. The key will be the file name and the value will be the file data. The files list contains a list of file paths that will be added to the tar file. """ self.strings = {} self.files = [] def add_file(self, filename, arc_dirname): if os.path.exists(filename): self.files.append((filename, arc_dirname)) else: raise FileDoesNotExist(filename) def add_string(self, name, string_data): self.strings[name] = string_data def create_tar(self, tf): """Takes the provided tar file object and adds all the specified data to it. The strings dictionary is parsed such that the key name is the file name and the value is the file data in the tar file. """ for file in self.files: file, dirname = file if dirname: tf.add(file, arcname=os.path.join(dirname, os.path.split(file)[-1])) else: tf.add(file) for filename, string in self.strings.items(): fd_str = cStringIO.StringIO(string) fd_str.seek(0) ti = tarfile.TarInfo() ti.size = len(string) ti.name = filename ti.type = tarfile.REGTYPE tf.addfile(ti, fd_str) def create_tar_file(self, fd, compression="gz"): """Creates a tarball and writes it out to the file specified in fd @Note: we don't have to worry about ReadError, since we don't allow appending. We only write to a tarball on create. @param fd: The file that the tarball will be written to @param compression: The type of compression that should be used @raise tarfile.CompressionError: This exception can be raised is an invalid compression type has been passed in """ tar_mode = "w:%s" % compression tf = tarfile.open(fileobj=fd, mode=tar_mode) self.create_tar(tf) tf.close() def create_tar_blob(self, compression="gz"): """Creates a tarball and writes it out to memory @Note: we don't have to worry about ReadError, since we don't allow appending. We only write to a tarball on create. @param fd: The file that the tarball will be written to @param compression: The type of compression that should be used @raise tarfile.CompressionError: This exception can be raised is an invalid compression type has been passed in """ from cStringIO import StringIO tar_mode = "w:%s" % compression file_out = StringIO() tf = tarfile.open(fileobj=file_out, mode="w:gz") self.create_tar(tf) tf.close() return file_out.getvalue() def is_tarfile(self, full_path): """Checks to see if the tar file specified is valid and can be read. Returns True if the file is a valid tar file and it can be read. Returns False if not valid or it cannot be read. @param full_path: The full path to the tar file. Includes the file name @return: True/False """ return tarfile.is_tarfile(full_path)
""" Two-dimensional pattern generators drawing from various random distributions. """ __version__='$Revision$' import numpy from numpy.oldnumeric import zeros,floor,where,choose,less,greater,Int,random_array import param from param.parameterized import ParamOverrides from patterngenerator import PatternGenerator from . import Composite, Gaussian from sheetcoords import SheetCoordinateSystem def seed(seed=None): """ Set the seed on the shared RandomState instance. Convenience function: shortcut to RandomGenerator.random_generator.seed(). """ RandomGenerator.random_generator.seed(seed) class RandomGenerator(PatternGenerator): """2D random noise pattern generator abstract class.""" __abstract = True # The orientation is ignored, so we don't show it in # auto-generated lists of parameters (e.g. in the GUI) orientation = param.Number(precedence=-1) random_generator = param.Parameter( default=numpy.random.RandomState(seed=(500,500)),precedence=-1,doc= """ numpy's RandomState provides methods for generating random numbers (see RandomState's help for more information). Note that all instances will share this RandomState object, and hence its state. To create a RandomGenerator that has its own state, set this parameter to a new RandomState instance. """) def _distrib(self,shape,p): """Method for subclasses to override with a particular random distribution.""" raise NotImplementedError # Optimization: We use a simpler __call__ method here to skip the # coordinate transformations (which would have no effect anyway) def __call__(self,**params_to_override): p = ParamOverrides(self,params_to_override) shape = SheetCoordinateSystem(p.bounds,p.xdensity,p.ydensity).shape result = self._distrib(shape,p) self._apply_mask(p,result) for of in p.output_fns: of(result) return result class UniformRandom(RandomGenerator): """2D uniform random noise pattern generator.""" def _distrib(self,shape,p): return p.random_generator.uniform(p.offset, p.offset+p.scale, shape) class BinaryUniformRandom(RandomGenerator): """ 2D binary uniform random noise pattern generator. Generates an array of random numbers that are 1.0 with the given on_probability, or else 0.0, then scales it and adds the offset as for other patterns. For the default scale and offset, the result is a binary mask where some elements are on at random. """ on_probability = param.Number(default=0.5,bounds=[0.0,1.0],doc=""" Probability (in the range 0.0 to 1.0) that the binary value (before scaling) is on rather than off (1.0 rather than 0.0).""") def _distrib(self,shape,p): rmin = p.on_probability-0.5 return p.offset+p.scale*(p.random_generator.uniform(rmin,rmin+1.0,shape).round()) class GaussianRandom(RandomGenerator): """ 2D Gaussian random noise pattern generator. Each pixel is chosen independently from a Gaussian distribution of zero mean and unit variance, then multiplied by the given scale and adjusted by the given offset. """ scale = param.Number(default=0.25,softbounds=(0.0,2.0)) offset = param.Number(default=0.50,softbounds=(-2.0,2.0)) def _distrib(self,shape,p): return p.offset+p.scale*p.random_generator.standard_normal(shape) # CEBALERT: in e.g. script_repr, an instance of this class appears to # have only pattern.Constant() in its list of generators, which might # be confusing. The Constant pattern has no effect because the # generators list is overridden in __call__. Shouldn't the generators # parameter be hidden for this class (and possibly for others based on # pattern.Composite)? For that to be safe, we'd at least have to have # a warning if someone ever sets a hidden parameter, so that having it # revert to the default value would always be ok. class GaussianCloud(Composite): """Uniform random noise masked by a circular Gaussian.""" operator = param.Parameter(numpy.multiply) gaussian_size = param.Number(default=1.0,doc="Size of the Gaussian pattern.") aspect_ratio = param.Number(default=1.0,bounds=(0.0,None),softbounds=(0.0,2.0), precedence=0.31,doc=""" Ratio of gaussian width to height; width is gaussian_size*aspect_ratio.""") def __call__(self,**params_to_override): p = ParamOverrides(self,params_to_override) p.generators=[Gaussian(aspect_ratio=p.aspect_ratio,size=p.gaussian_size), UniformRandom()] return super(GaussianCloud,self).__call__(**p) ### JABHACKALERT: This code seems to work fine when the input regions ### are all the same size and shape, but for ### e.g. examples/hierarchical.ty the resulting images in the Test ### Pattern preview window are square (instead of the actual ### rectangular shapes), matching between the eyes (instead of the ### actual two different rectangles), and with dot sizes that don't ### match between the eyes. It's not clear why this happens. class RandomDotStereogram(PatternGenerator): """ Random dot stereogram using rectangular black and white patches. Based on Matlab code originally from Jenny Read, reimplemented in Python by Tikesh Ramtohul (2006). """ # Suppress unused parameters x = param.Number(precedence=-1) y = param.Number(precedence=-1) size = param.Number(precedence=-1) orientation = param.Number(precedence=-1) # Override defaults to make them appropriate scale = param.Number(default=0.5) offset = param.Number(default=0.5) # New parameters for this pattern #JABALERT: Should rename xdisparity and ydisparity to x and y, and simply #set them to different values for each pattern to get disparity xdisparity = param.Number(default=0.0,bounds=(-1.0,1.0),softbounds=(-0.5,0.5), precedence=0.50,doc="Disparity in the horizontal direction.") ydisparity = param.Number(default=0.0,bounds=(-1.0,1.0),softbounds=(-0.5,0.5), precedence=0.51,doc="Disparity in the vertical direction.") dotdensity = param.Number(default=0.5,bounds=(0.0,None),softbounds=(0.1,0.9), precedence=0.52,doc="Number of dots per unit area; 0.5=50% coverage.") dotsize = param.Number(default=0.1,bounds=(0.0,None),softbounds=(0.05,0.15), precedence=0.53,doc="Edge length of each square dot.") random_seed=param.Integer(default=500,bounds=(0,1000), precedence=0.54,doc="Seed value for the random position of the dots.") def __call__(self,**params_to_override): p = ParamOverrides(self,params_to_override) xsize,ysize = SheetCoordinateSystem(p.bounds,p.xdensity,p.ydensity).shape xsize,ysize = int(round(xsize)),int(round(ysize)) xdisparity = int(round(xsize*p.xdisparity)) ydisparity = int(round(xsize*p.ydisparity)) dotsize = int(round(xsize*p.dotsize)) bigxsize = 2*xsize bigysize = 2*ysize ndots=int(round(p.dotdensity * (bigxsize+2*dotsize) * (bigysize+2*dotsize) / min(dotsize,xsize) / min(dotsize,ysize))) halfdot = floor(dotsize/2) # Choose random colors and locations of square dots random_seed = p.random_seed random_array.seed(random_seed*12,random_seed*99) col=where(random_array.random((ndots))>=0.5, 1.0, -1.0) random_array.seed(random_seed*122,random_seed*799) xpos=floor(random_array.random((ndots))*(bigxsize+2*dotsize)) - halfdot random_array.seed(random_seed*1243,random_seed*9349) ypos=floor(random_array.random((ndots))*(bigysize+2*dotsize)) - halfdot # Construct arrays of points specifying the boundaries of each # dot, cropping them by the big image size (0,0) to (bigxsize,bigysize) x1=xpos.astype(Int) ; x1=choose(less(x1,0),(x1,0)) y1=ypos.astype(Int) ; y1=choose(less(y1,0),(y1,0)) x2=(xpos+(dotsize-1)).astype(Int) ; x2=choose(greater(x2,bigxsize),(x2,bigxsize)) y2=(ypos+(dotsize-1)).astype(Int) ; y2=choose(greater(y2,bigysize),(y2,bigysize)) # Draw each dot in the big image, on a blank background bigimage = zeros((bigysize,bigxsize)) for i in range(ndots): bigimage[y1[i]:y2[i]+1,x1[i]:x2[i]+1] = col[i] result = p.offset + p.scale*bigimage[ (ysize/2)+ydisparity:(3*ysize/2)+ydisparity , (xsize/2)+xdisparity:(3*xsize/2)+xdisparity ] for of in p.output_fns: of(result) return result Update random.py Getting rid of oldnumeric dependency """ Two-dimensional pattern generators drawing from various random distributions. """ __version__='$Revision$' import numpy from numpy import zeros,floor,where,choose,less,greater,random_array import param from param.parameterized import ParamOverrides from patterngenerator import PatternGenerator from . import Composite, Gaussian from sheetcoords import SheetCoordinateSystem def seed(seed=None): """ Set the seed on the shared RandomState instance. Convenience function: shortcut to RandomGenerator.random_generator.seed(). """ RandomGenerator.random_generator.seed(seed) class RandomGenerator(PatternGenerator): """2D random noise pattern generator abstract class.""" __abstract = True # The orientation is ignored, so we don't show it in # auto-generated lists of parameters (e.g. in the GUI) orientation = param.Number(precedence=-1) random_generator = param.Parameter( default=numpy.random.RandomState(seed=(500,500)),precedence=-1,doc= """ numpy's RandomState provides methods for generating random numbers (see RandomState's help for more information). Note that all instances will share this RandomState object, and hence its state. To create a RandomGenerator that has its own state, set this parameter to a new RandomState instance. """) def _distrib(self,shape,p): """Method for subclasses to override with a particular random distribution.""" raise NotImplementedError # Optimization: We use a simpler __call__ method here to skip the # coordinate transformations (which would have no effect anyway) def __call__(self,**params_to_override): p = ParamOverrides(self,params_to_override) shape = SheetCoordinateSystem(p.bounds,p.xdensity,p.ydensity).shape result = self._distrib(shape,p) self._apply_mask(p,result) for of in p.output_fns: of(result) return result class UniformRandom(RandomGenerator): """2D uniform random noise pattern generator.""" def _distrib(self,shape,p): return p.random_generator.uniform(p.offset, p.offset+p.scale, shape) class BinaryUniformRandom(RandomGenerator): """ 2D binary uniform random noise pattern generator. Generates an array of random numbers that are 1.0 with the given on_probability, or else 0.0, then scales it and adds the offset as for other patterns. For the default scale and offset, the result is a binary mask where some elements are on at random. """ on_probability = param.Number(default=0.5,bounds=[0.0,1.0],doc=""" Probability (in the range 0.0 to 1.0) that the binary value (before scaling) is on rather than off (1.0 rather than 0.0).""") def _distrib(self,shape,p): rmin = p.on_probability-0.5 return p.offset+p.scale*(p.random_generator.uniform(rmin,rmin+1.0,shape).round()) class GaussianRandom(RandomGenerator): """ 2D Gaussian random noise pattern generator. Each pixel is chosen independently from a Gaussian distribution of zero mean and unit variance, then multiplied by the given scale and adjusted by the given offset. """ scale = param.Number(default=0.25,softbounds=(0.0,2.0)) offset = param.Number(default=0.50,softbounds=(-2.0,2.0)) def _distrib(self,shape,p): return p.offset+p.scale*p.random_generator.standard_normal(shape) # CEBALERT: in e.g. script_repr, an instance of this class appears to # have only pattern.Constant() in its list of generators, which might # be confusing. The Constant pattern has no effect because the # generators list is overridden in __call__. Shouldn't the generators # parameter be hidden for this class (and possibly for others based on # pattern.Composite)? For that to be safe, we'd at least have to have # a warning if someone ever sets a hidden parameter, so that having it # revert to the default value would always be ok. class GaussianCloud(Composite): """Uniform random noise masked by a circular Gaussian.""" operator = param.Parameter(numpy.multiply) gaussian_size = param.Number(default=1.0,doc="Size of the Gaussian pattern.") aspect_ratio = param.Number(default=1.0,bounds=(0.0,None),softbounds=(0.0,2.0), precedence=0.31,doc=""" Ratio of gaussian width to height; width is gaussian_size*aspect_ratio.""") def __call__(self,**params_to_override): p = ParamOverrides(self,params_to_override) p.generators=[Gaussian(aspect_ratio=p.aspect_ratio,size=p.gaussian_size), UniformRandom()] return super(GaussianCloud,self).__call__(**p) ### JABHACKALERT: This code seems to work fine when the input regions ### are all the same size and shape, but for ### e.g. examples/hierarchical.ty the resulting images in the Test ### Pattern preview window are square (instead of the actual ### rectangular shapes), matching between the eyes (instead of the ### actual two different rectangles), and with dot sizes that don't ### match between the eyes. It's not clear why this happens. class RandomDotStereogram(PatternGenerator): """ Random dot stereogram using rectangular black and white patches. Based on Matlab code originally from Jenny Read, reimplemented in Python by Tikesh Ramtohul (2006). """ # Suppress unused parameters x = param.Number(precedence=-1) y = param.Number(precedence=-1) size = param.Number(precedence=-1) orientation = param.Number(precedence=-1) # Override defaults to make them appropriate scale = param.Number(default=0.5) offset = param.Number(default=0.5) # New parameters for this pattern #JABALERT: Should rename xdisparity and ydisparity to x and y, and simply #set them to different values for each pattern to get disparity xdisparity = param.Number(default=0.0,bounds=(-1.0,1.0),softbounds=(-0.5,0.5), precedence=0.50,doc="Disparity in the horizontal direction.") ydisparity = param.Number(default=0.0,bounds=(-1.0,1.0),softbounds=(-0.5,0.5), precedence=0.51,doc="Disparity in the vertical direction.") dotdensity = param.Number(default=0.5,bounds=(0.0,None),softbounds=(0.1,0.9), precedence=0.52,doc="Number of dots per unit area; 0.5=50% coverage.") dotsize = param.Number(default=0.1,bounds=(0.0,None),softbounds=(0.05,0.15), precedence=0.53,doc="Edge length of each square dot.") random_seed=param.Integer(default=500,bounds=(0,1000), precedence=0.54,doc="Seed value for the random position of the dots.") def __call__(self,**params_to_override): p = ParamOverrides(self,params_to_override) xsize,ysize = SheetCoordinateSystem(p.bounds,p.xdensity,p.ydensity).shape xsize,ysize = int(round(xsize)),int(round(ysize)) xdisparity = int(round(xsize*p.xdisparity)) ydisparity = int(round(xsize*p.ydisparity)) dotsize = int(round(xsize*p.dotsize)) bigxsize = 2*xsize bigysize = 2*ysize ndots=int(round(p.dotdensity * (bigxsize+2*dotsize) * (bigysize+2*dotsize) / min(dotsize,xsize) / min(dotsize,ysize))) halfdot = floor(dotsize/2) # Choose random colors and locations of square dots random_seed = p.random_seed random_array.seed(random_seed*12,random_seed*99) col=where(random_array.random((ndots))>=0.5, 1.0, -1.0) random_array.seed(random_seed*122,random_seed*799) xpos=floor(random_array.random((ndots))*(bigxsize+2*dotsize)) - halfdot random_array.seed(random_seed*1243,random_seed*9349) ypos=floor(random_array.random((ndots))*(bigysize+2*dotsize)) - halfdot # Construct arrays of points specifying the boundaries of each # dot, cropping them by the big image size (0,0) to (bigxsize,bigysize) x1=xpos.astype(numpy.int) ; x1=choose(less(x1,0),(x1,0)) y1=ypos.astype(numpy.int) ; y1=choose(less(y1,0),(y1,0)) x2=(xpos+(dotsize-1)).astype(numpy.int) ; x2=choose(greater(x2,bigxsize),(x2,bigxsize)) y2=(ypos+(dotsize-1)).astype(numpy.int) ; y2=choose(greater(y2,bigysize),(y2,bigysize)) # Draw each dot in the big image, on a blank background bigimage = zeros((bigysize,bigxsize)) for i in range(ndots): bigimage[y1[i]:y2[i]+1,x1[i]:x2[i]+1] = col[i] result = p.offset + p.scale*bigimage[ (ysize/2)+ydisparity:(3*ysize/2)+ydisparity , (xsize/2)+xdisparity:(3*xsize/2)+xdisparity ] for of in p.output_fns: of(result) return result
# -*- coding: utf-8 -*- from logging import getLogger from openprocurement.api.utils import opresource, json_view, get_file LOGGER = getLogger(__name__) from openprocurement.tender.openua.views.bid_document import TenderUaBidDocumentResource @opresource(name='Tender EU Bid Documents', collection_path='/tenders/{tender_id}/bids/{bid_id}/documents', path='/tenders/{tender_id}/bids/{bid_id}/documents/{document_id}', procurementMethodType='aboveThresholdEU', description="Tender EU bidder documents") class TenderEUBidDocumentResource(TenderUaBidDocumentResource): @json_view(permission='view_tender') def collection_get(self): """Tender Bid Documents List""" if self.request.validated['tender_status'] == 'active.tendering' and self.request.authenticated_role != 'bid_owner': self.request.errors.add('body', 'data', 'Can\'t view bid documents in current ({}) tender status'.format(self.request.validated['tender_status'])) self.request.errors.status = 403 return if self.request.params.get('all', ''): collection_data = [i.serialize("view") for i in self.context.documents] else: collection_data = sorted(dict([ (i.id, i.serialize("view")) for i in self.context.documents ]).values(), key=lambda i: i['dateModified']) return {'data': collection_data} @json_view(permission='view_tender') def get(self): """Tender Bid Document Read""" if self.request.validated['tender_status'] == 'active.tendering' and self.request.authenticated_role != 'bid_owner': self.request.errors.add('body', 'data', 'Can\'t view bid document in current ({}) tender status'.format(self.request.validated['tender_status'])) self.request.errors.status = 403 return if self.request.params.get('download'): return get_file(self.request) document = self.request.validated['document'] document_data = document.serialize("view") document_data['previousVersions'] = [ i.serialize("view") for i in self.request.validated['documents'] if i.url != document.url ] return {'data': document_data} added resources for additional bid documents handling # -*- coding: utf-8 -*- from logging import getLogger from openprocurement.api.utils import ( get_file, save_tender, upload_file, apply_patch, update_file_content_type, opresource, json_view, context_unpack, ) from openprocurement.api.validation import ( validate_file_update, validate_file_upload, validate_patch_document_data, ) from openprocurement.tender.openeu.utils import ( bid_financial_documents_resource, bid_eligibility_documents_resource, bid_qualification_documents_resource) LOGGER = getLogger(__name__) from openprocurement.tender.openua.views.bid_document import TenderUaBidDocumentResource @opresource(name='Tender EU Bid Documents', collection_path='/tenders/{tender_id}/bids/{bid_id}/documents', path='/tenders/{tender_id}/bids/{bid_id}/documents/{document_id}', procurementMethodType='aboveThresholdEU', description="Tender EU bidder documents") class TenderEUBidDocumentResource(TenderUaBidDocumentResource): @json_view(permission='view_tender') def collection_get(self): """Tender Bid Documents List""" if self.request.validated['tender_status'] == 'active.tendering' and self.request.authenticated_role != 'bid_owner': self.request.errors.add('body', 'data', 'Can\'t view bid documents in current ({}) tender status'.format(self.request.validated['tender_status'])) self.request.errors.status = 403 return if self.request.params.get('all', ''): collection_data = [i.serialize("view") for i in self.context.documents] else: collection_data = sorted(dict([ (i.id, i.serialize("view")) for i in self.context.documents ]).values(), key=lambda i: i['dateModified']) return {'data': collection_data} @json_view(permission='view_tender') def get(self): """Tender Bid Document Read""" if self.request.validated['tender_status'] == 'active.tendering' and self.request.authenticated_role != 'bid_owner': self.request.errors.add('body', 'data', 'Can\'t view bid document in current ({}) tender status'.format(self.request.validated['tender_status'])) self.request.errors.status = 403 return if self.request.params.get('download'): return get_file(self.request) document = self.request.validated['document'] document_data = document.serialize("view") document_data['previousVersions'] = [ i.serialize("view") for i in self.request.validated['documents'] if i.url != document.url ] return {'data': document_data} @bid_financial_documents_resource( name='Tender EU Bid Financial Documents', collection_path='/tenders/{tender_id}/bids/{bid_id}/financial_documents', path='/tenders/{tender_id}/bids/{bid_id}/financial_documents/{document_id}', procurementMethodType='aboveThresholdEU', description="Tender EU bidder financial documents") class TenderEUBidFinancialDocumentResource(TenderEUBidDocumentResource): """ Tender EU Bid Financial Documents """ container = "financialDocuments" view_forbidden_states = ['active.tendering', 'active.pre-qualification', 'active.pre-qualification.stand-still', 'active.auction'] @json_view(permission='view_tender') def collection_get(self): """Tender Bid Documents List""" if self.request.validated['tender_status'] in self.view_forbidden_states and self.request.authenticated_role != 'bid_owner': self.request.errors.add('body', 'data', 'Can\'t view bid documents in current ({}) tender status'.format(self.request.validated['tender_status'])) self.request.errors.status = 403 return if self.request.params.get('all', ''): collection_data = [i.serialize("view") for i in getattr(self.context, self.container)] else: collection_data = sorted(dict([ (i.id, i.serialize("view")) for i in getattr(self.context, self.container) ]).values(), key=lambda i: i['dateModified']) return {'data': collection_data} @json_view(permission='view_tender') def get(self): """Tender Bid Document Read""" if self.request.validated['tender_status'] in self.view_forbidden_states and self.request.authenticated_role != 'bid_owner': self.request.errors.add('body', 'data', 'Can\'t view bid document in current ({}) tender status'.format(self.request.validated['tender_status'])) self.request.errors.status = 403 return if self.request.params.get('download'): return get_file(self.request) document = self.request.validated['document'] document_data = document.serialize("view") document_data['previousVersions'] = [ i.serialize("view") for i in self.request.validated['documents'] if i.url != document.url ] return {'data': document_data} @json_view(validators=(validate_file_upload,), permission='edit_bid') def collection_post(self): """Tender Bid Document Upload """ if self.request.validated['tender_status'] not in ['active.tendering', 'active.qualification']: self.request.errors.add('body', 'data', 'Can\'t add document in current ({}) tender status'.format(self.request.validated['tender_status'])) self.request.errors.status = 403 return if self.request.validated['tender_status'] == 'active.qualification' and not [i for i in self.request.validated['tender'].awards if i.status == 'pending' and i.bid_id == self.request.validated['bid_id']]: self.request.errors.add('body', 'data', 'Can\'t add document because award of bid is not in pending state') self.request.errors.status = 403 return document = upload_file(self.request) getattr(self.context, self.container).append(document) if save_tender(self.request): LOGGER.info('Created tender bid document {}'.format(document.id), extra=context_unpack(self.request, {'MESSAGE_ID': 'tender_bid_document_create'}, {'document_id': document.id})) self.request.response.status = 201 document_route = self.request.matched_route.name.replace("collection_", "") self.request.response.headers['Location'] = self.request.current_route_url(_route_name=document_route, document_id=document.id, _query={}) return {'data': document.serialize("view")} @json_view(validators=(validate_file_update,), permission='edit_bid') def put(self): """Tender Bid Document Update""" if self.request.validated['tender_status'] not in ['active.tendering', 'active.qualification']: self.request.errors.add('body', 'data', 'Can\'t update document in current ({}) tender status'.format(self.request.validated['tender_status'])) self.request.errors.status = 403 return if self.request.validated['tender_status'] == 'active.qualification' and not [i for i in self.request.validated['tender'].awards if i.status == 'pending' and i.bid_id == self.request.validated['bid_id']]: self.request.errors.add('body', 'data', 'Can\'t update document because award of bid is not in pending state') self.request.errors.status = 403 return document = upload_file(self.request) getattr(self.request.validated['bid'], self.container).append(document) if save_tender(self.request): LOGGER.info('Updated tender bid document {}'.format(self.request.context.id), extra=context_unpack(self.request, {'MESSAGE_ID': 'tender_bid_document_put'})) return {'data': document.serialize("view")} @json_view(content_type="application/json", validators=(validate_patch_document_data,), permission='edit_bid') def patch(self): """Tender Bid Document Update""" if self.request.validated['tender_status'] not in ['active.tendering', 'active.qualification']: self.request.errors.add('body', 'data', 'Can\'t update document in current ({}) tender status'.format(self.request.validated['tender_status'])) self.request.errors.status = 403 return if self.request.validated['tender_status'] == 'active.qualification' and not [i for i in self.request.validated['tender'].awards if i.status == 'pending' and i.bid_id == self.request.validated['bid_id']]: self.request.errors.add('body', 'data', 'Can\'t update document because award of bid is not in pending state') self.request.errors.status = 403 return if apply_patch(self.request, src=self.request.context.serialize()): update_file_content_type(self.request) LOGGER.info('Updated tender bid document {}'.format(self.request.context.id), extra=context_unpack(self.request, {'MESSAGE_ID': 'tender_bid_document_patch'})) return {'data': self.request.context.serialize("view")} @bid_eligibility_documents_resource(name='Tender EU Bid Eligibility Documents', collection_path='/tenders/{tender_id}/bids/{bid_id}/eligibility_documents', path='/tenders/{tender_id}/bids/{bid_id}/eligibility_documents/{document_id}', procurementMethodType='aboveThresholdEU', description="Tender EU bidder eligibility documents") class TenderEUBidEligibilityDocumentResource(TenderEUBidFinancialDocumentResource): """ Tender EU Bid Eligibility Documents """ container = "eligibilityDocuments" @bid_qualification_documents_resource(name='Tender EU Bid Qualification Documents', collection_path='/tenders/{tender_id}/bids/{bid_id}/qualification_documents', path='/tenders/{tender_id}/bids/{bid_id}/qualification_documents/{document_id}', procurementMethodType='aboveThresholdEU', description="Tender EU bidder qualification documents") class TenderEUBidQualificationDocumentResource(TenderEUBidFinancialDocumentResource): """ Tender EU Bid Qualification Documents """ container = "qualificationDocuments"
#!/usr/bin/python2 # coding: utf-8 import lurklib import glob import sys import logging import logging.handlers import os from os.path import basename, join class Plugger(object): def __init__(self, bot, path): self.bot = bot if not path in sys.path: sys.path.append(os.path.join(os.getcwd(),path)) self.path = path def load_plugins(self): for plugin in glob.glob("%s/*.py" % self.path): logging.debug("Loading %s" % plugin) self.load_plugin(basename(plugin), py=True) def load_plugin(self, name, py=False): # Is there ".py in name? if not py: name = name + ".py" logging.debug("Trying to load %s" % name) plug = __import__(name[:-3]) plug.Plugin(self.bot) class Bot(lurklib.Client): def __init__(self, server, admin, port=None, nick='lalal', user='lalala', real_name='lalilu', password=None, tls=False, tls_verify=False, encoding='UTF-8', hide_called_events=True, UTC=False, channel="#lalala", version="lala 0.1", debug=True, debugformat= "%(levelname)s %(filename)s: %(funcName)s:%(lineno)d %(message)s", log=True, logfolder="~/.lala/logs", plugins=['last', 'quotes', 'base'], nickserv=None ): self._admins = admin if log: logfolder = os.path.expanduser(logfolder) self._logfile = join(logfolder, "lala.log") if not os.path.exists(logfolder): os.makedirs(logfolder) self._logger = logging.getLogger("MessageLog") handler = logging.handlers.TimedRotatingFileHandler( encoding="utf-8", filename=self._logfile, when="midnight") self._logger.setLevel(logging.INFO) handler.setFormatter( logging.Formatter("%(asctime)s %(message)s", "%Y-%m-%d %H:%m")) self._logger.addHandler(handler) if debug: logging.basicConfig(format=debugformat, level=logging.DEBUG) self._channel = channel self._callbacks = {} self._join_callbacks = list() self._regexes = {} self._cbprefix = "!" self.__version__ = version self._nickserv_password = nickserv self.plugger = Plugger(self, "lala/plugins") for plugin in plugins: self.plugger.load_plugin(plugin) self.plugger.load_plugin("base") lurklib.Client.__init__(self, server = server, port = port, nick = nick, real_name = real_name, password = password, tls = tls, tls_verify = tls_verify, encoding = encoding, hide_called_events = hide_called_events, UTC = UTC ) def on_connect(self): if self._nickserv_password: logging.debug("Identifying with %s" % self._nickserv_password) self.privmsg("NickServ", "identify %s" % self._nickserv_password) def on_privmsg(self, event): user = event[0][0] text = event[2] if event[1] == self.current_nick: channel = user else: channel = event[1] self._logger.info("%s: %s" % (user, text)) try: if text.startswith(self._cbprefix): command = text.split()[0].replace(self._cbprefix, "") if command in self._callbacks: self._callbacks[command]( self, # bot user, channel, # channel text) for regex in self._regexes: match = regex.search(text) if match is not None: self._regexes[regex]( self, user, channel, text, match) except (lurklib.exceptions._Exceptions.NotInChannel, lurklib.exceptions._Exceptions.NotOnChannel): # Some plugin tried to send to a channel it's not in # This should not happen, but anyway: pass # Catch TypeError: some command parameter was not correct # TODO Find a way to tell people about wrong parameters except TypeError, e: pass def on_notice(self, event): user = event[0][0] text = event[2] self._logger.info("NOTICE from %s: %s" % (user, text)) def on_join(self, event): self._logger.info("%s joined" % event[0][0]) for cb in self._join_callbacks: cb(self, event) def on_ctcp(self, event): if event[2] == "VERSION": logging.debug("VERSION request from %s" % event[0][0]) self.notice(event[0][0], self.ctcp_encode("VERSION %s" % self.__version__)) def on_part(self, event): user = event[0][0] channel = event[1] reason = event[2] self._logger.info("%s parted: %s" % (user, reason)) def on_quit(self, event): user = event[0][0] reason = event[1] self._logger.info("%s left: %s" % (user, reason)) def register_callback(self, trigger, func): """ Adds func to the callbacks for trigger """ logging.debug("Registering callback for %s" % trigger) self._callbacks[trigger] = func def register_join_callback(self, func): self._join_callbacks.append(func) def register_regex(self, regex, func): self._regexes[regex] = func def privmsg(self, target, message): self._logger.info("%s: %s" % (self.current_nick, message)) lurklib.Client.privmsg(self, target, message) if __name__ == '__main__': bot = Bot() bot.mainloop() Fix the plugin path #!/usr/bin/python2 # coding: utf-8 import lurklib import glob import sys import logging import logging.handlers import os from os.path import basename, join class Plugger(object): def __init__(self, bot, path): self.bot = bot if not path in sys.path: sys.path.append(os.path.join(os.path.dirname(__file__),path)) self.path = path def load_plugins(self): for plugin in glob.glob("%s/*.py" % self.path): logging.debug("Loading %s" % plugin) self.load_plugin(basename(plugin), py=True) def load_plugin(self, name, py=False): # Is there ".py in name? if not py: name = name + ".py" logging.debug("Trying to load %s" % name) plug = __import__(name[:-3]) plug.Plugin(self.bot) class Bot(lurklib.Client): def __init__(self, server, admin, port=None, nick='lalal', user='lalala', real_name='lalilu', password=None, tls=False, tls_verify=False, encoding='UTF-8', hide_called_events=True, UTC=False, channel="#lalala", version="lala 0.1", debug=True, debugformat= "%(levelname)s %(filename)s: %(funcName)s:%(lineno)d %(message)s", log=True, logfolder="~/.lala/logs", plugins=['last', 'quotes', 'base'], nickserv=None ): self._admins = admin if log: logfolder = os.path.expanduser(logfolder) self._logfile = join(logfolder, "lala.log") if not os.path.exists(logfolder): os.makedirs(logfolder) self._logger = logging.getLogger("MessageLog") handler = logging.handlers.TimedRotatingFileHandler( encoding="utf-8", filename=self._logfile, when="midnight") self._logger.setLevel(logging.INFO) handler.setFormatter( logging.Formatter("%(asctime)s %(message)s", "%Y-%m-%d %H:%m")) self._logger.addHandler(handler) if debug: logging.basicConfig(format=debugformat, level=logging.DEBUG) self._channel = channel self._callbacks = {} self._join_callbacks = list() self._regexes = {} self._cbprefix = "!" self.__version__ = version self._nickserv_password = nickserv self.plugger = Plugger(self, "plugins") for plugin in plugins: self.plugger.load_plugin(plugin) self.plugger.load_plugin("base") lurklib.Client.__init__(self, server = server, port = port, nick = nick, real_name = real_name, password = password, tls = tls, tls_verify = tls_verify, encoding = encoding, hide_called_events = hide_called_events, UTC = UTC ) def on_connect(self): if self._nickserv_password: logging.debug("Identifying with %s" % self._nickserv_password) self.privmsg("NickServ", "identify %s" % self._nickserv_password) def on_privmsg(self, event): user = event[0][0] text = event[2] if event[1] == self.current_nick: channel = user else: channel = event[1] self._logger.info("%s: %s" % (user, text)) try: if text.startswith(self._cbprefix): command = text.split()[0].replace(self._cbprefix, "") if command in self._callbacks: self._callbacks[command]( self, # bot user, channel, # channel text) for regex in self._regexes: match = regex.search(text) if match is not None: self._regexes[regex]( self, user, channel, text, match) except (lurklib.exceptions._Exceptions.NotInChannel, lurklib.exceptions._Exceptions.NotOnChannel): # Some plugin tried to send to a channel it's not in # This should not happen, but anyway: pass # Catch TypeError: some command parameter was not correct # TODO Find a way to tell people about wrong parameters except TypeError, e: pass def on_notice(self, event): user = event[0][0] text = event[2] self._logger.info("NOTICE from %s: %s" % (user, text)) def on_join(self, event): self._logger.info("%s joined" % event[0][0]) for cb in self._join_callbacks: cb(self, event) def on_ctcp(self, event): if event[2] == "VERSION": logging.debug("VERSION request from %s" % event[0][0]) self.notice(event[0][0], self.ctcp_encode("VERSION %s" % self.__version__)) def on_part(self, event): user = event[0][0] channel = event[1] reason = event[2] self._logger.info("%s parted: %s" % (user, reason)) def on_quit(self, event): user = event[0][0] reason = event[1] self._logger.info("%s left: %s" % (user, reason)) def register_callback(self, trigger, func): """ Adds func to the callbacks for trigger """ logging.debug("Registering callback for %s" % trigger) self._callbacks[trigger] = func def register_join_callback(self, func): self._join_callbacks.append(func) def register_regex(self, regex, func): self._regexes[regex] = func def privmsg(self, target, message): self._logger.info("%s: %s" % (self.current_nick, message)) lurklib.Client.privmsg(self, target, message) if __name__ == '__main__': bot = Bot() bot.mainloop()
# Copyright 2015 CloudFounders NV # # 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. """ OpenStack Cinder driver - interface to Open vStorage - uses Open vStorage library calls (VDiskController) - uses Cinder logging """ import socket import time # External libs: Open vStorage try: from ovs.dal.hybrids import vdisk as vdiskhybrid from ovs.dal.lists import pmachinelist from ovs.dal.lists import vdisklist from ovs.dal.lists import vpoollist from ovs.lib import vdisk as vdisklib except ImportError: # CI Testing, all external libs are mocked # or using the driver without all required libs vdiskhybrid = None pmachinelist = None vdisklist = None vpoollist = None vdisklib = None from oslo_config import cfg import six from cinder import exception from cinder.i18n import _ from cinder.image import image_utils from cinder.openstack.common import log as logging from cinder.volume import driver LOG = logging.getLogger(__name
cask 'maratis' do version '3.21-beta' sha256 '7ec6dd97f1ce1ce09e08df0947fcb6ceb7a9f63024998f44afed3d3965829707' # storage.googleapis.com is the official download host per the vendor homepage url "https://storage.googleapis.com/google-code-archive-downloads/v1/code.google.com/maratis/Maratis-#{version}-osx10.6.zip" name 'Maratis' homepage 'http://www.maratis3d.org/' license :oss app 'Maratis.app' app 'MaratisPlayer.app' end Update Maratis download link (#20480) cask 'maratis' do version '3.21-beta' sha256 '7ec6dd97f1ce1ce09e08df0947fcb6ceb7a9f63024998f44afed3d3965829707' # storage.googleapis.com is the official download host per the vendor homepage url "https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/maratis/Maratis-#{version}-osx10.6.zip" name 'Maratis' homepage 'http://www.maratis3d.org/' license :oss app 'Maratis.app' app 'MaratisPlayer.app' end
cask :v1 => 'mcs783x' do version '1.1.0' sha256 'ea1d6245b5accabf041060886f16cc00b43d3e6e7e032f4154b487e96ab05569' module Utils def self.basename "MCS783x_Mac_OSX_10.5_to_10.7_driver_v#{Mcs783x.version}_Binary" end end url "http://www.asix.com.tw/FrootAttach/driver/#{Utils.basename}.zip" homepage 'http://www.asix.com.tw/products.php?op=ProductList&PLine=74&PSeries=109' license :unknown container :nested => "#{Utils.basename}/MCS7830_v#{version}.dmg" pkg "MCS7830 v#{version}.pkg" # todo, is "uninstal" below (one "l") a typo, or is that really the # file in the package? uninstall :script => { :executable => 'uninstal driver' }, :pkgutil => 'asix.com.moschipUsbEthernet.pkg' end blank before uninstall in mcs783x cask :v1 => 'mcs783x' do version '1.1.0' sha256 'ea1d6245b5accabf041060886f16cc00b43d3e6e7e032f4154b487e96ab05569' module Utils def self.basename "MCS783x_Mac_OSX_10.5_to_10.7_driver_v#{Mcs783x.version}_Binary" end end url "http://www.asix.com.tw/FrootAttach/driver/#{Utils.basename}.zip" homepage 'http://www.asix.com.tw/products.php?op=ProductList&PLine=74&PSeries=109' license :unknown container :nested => "#{Utils.basename}/MCS7830_v#{version}.dmg" pkg "MCS7830 v#{version}.pkg" # todo, is "uninstal" below (one "l") a typo, or is that really the # file in the package? uninstall :script => { :executable => 'uninstal driver' }, :pkgutil => 'asix.com.moschipUsbEthernet.pkg' end
# # Author:: Adam Jacob (<adam@chef.io>) # Author:: Charles Johnson (<charles@chef.io>) # Copyright:: Copyright (c) 2011-2015 CHEF Software, Inc. # # All Rights Reserved # # Create all nginx dirs nginx_log_dir = node['private_chef']['nginx']['log_directory'] nginx_dir = node['private_chef']['nginx']['dir'] nginx_ca_dir = File.join(nginx_dir, 'ca') nginx_cache_dir = File.join(nginx_dir, 'cache') nginx_cache_tmp_dir = File.join(nginx_dir, 'cache-tmp') nginx_etc_dir = File.join(nginx_dir, 'etc') nginx_addon_dir = File.join(nginx_etc_dir, 'addon.d') nginx_d_dir = File.join(nginx_etc_dir, 'nginx.d') nginx_scripts_dir = File.join(nginx_etc_dir, 'scripts') nginx_html_dir = File.join(nginx_dir, 'html') nginx_tempfile_dir = File.join(nginx_dir, 'tmp') [ nginx_log_dir, nginx_dir, nginx_ca_dir, nginx_cache_dir, nginx_cache_tmp_dir, nginx_etc_dir, nginx_addon_dir, nginx_d_dir, nginx_scripts_dir, nginx_html_dir, nginx_tempfile_dir ].each do |dir_name| directory dir_name do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode node['private_chef']['service_dir_perms'] recursive true end end # Create empty error log files %w(access.log error.log current).each do |logfile| file File.join(nginx_log_dir, logfile) do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '0644' end end # Generate self-signed SSL certificate unless the user has provided one if (node['private_chef']['nginx']['ssl_certificate'].nil? && node['private_chef']['nginx']['ssl_certificate_key'].nil?) ssl_keyfile = File.join(nginx_ca_dir, "#{node['private_chef']['nginx']['server_name']}.key") ssl_crtfile = File.join(nginx_ca_dir, "#{node['private_chef']['nginx']['server_name']}.crt") server_name = node['private_chef']['nginx']['server_name'] server_name_type = if OmnibusHelper.is_ip?(server_name) "IP" else "DNS" end openssl_x509 ssl_crtfile do common_name server_name org node['private_chef']['nginx']['ssl_company_name'] org_unit node['private_chef']['nginx']['ssl_organizational_unit_name'] country node['private_chef']['nginx']['ssl_country_name'] key_length node['private_chef']['nginx']['ssl_key_length'] expire node['private_chef']['nginx']['ssl_duration'] subject_alt_name [ "#{server_name_type}:#{server_name}" ] owner 'root' group 'root' mode '0644' end node.default['private_chef']['nginx']['ssl_certificate'] = ssl_crtfile node.default['private_chef']['nginx']['ssl_certificate_key'] = ssl_keyfile end # Copy the required_recipe source into the nginx static root directory and # ensure that it's only modifiable by root. if node['private_chef']['required_recipe']['enable'] remote_file ::File.join(nginx_html_dir, 'required_recipe') do source "file://#{node['private_chef']['required_recipe']['path']}" owner 'root' group 'root' mode '0644' end end # Generate dhparam.pem unless the user has provided a dhparam file if node['private_chef']['nginx']['ssl_dhparam'].nil? ssl_dhparam = File.join(nginx_ca_dir, 'dhparams.pem') openssl_dhparam ssl_dhparam do key_length node['private_chef']['nginx']['dhparam_key_length'] generator node['private_chef']['nginx']['dhparam_generator_id'] owner 'root' group 'root' mode '0644' end node.default['private_chef']['nginx']['ssl_dhparam'] = ssl_dhparam end # Create static html directory remote_directory nginx_html_dir do source 'html' files_backup false files_owner 'root' files_group 'root' files_mode '0644' owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode node['private_chef']['service_dir_perms'] end # Create nginx config chef_lb_configs = { :chef_https_config => File.join(nginx_etc_dir, 'chef_https_lb.conf'), :chef_http_config => File.join(nginx_etc_dir, 'chef_http_lb.conf'), :script_path => nginx_scripts_dir } nginx_vars = node['private_chef']['nginx'].to_hash nginx_vars = nginx_vars.merge(:helper => NginxErb.new(node)) # Chef API lb config for HTTPS and HTTP lbconf = node['private_chef']['lb'].to_hash.merge(nginx_vars).merge( :redis_host => node['private_chef']['redis_lb']['vip'], :redis_port => node['private_chef']['redis_lb']['port'], :omnihelper => OmnibusHelper.new(node) ) ['config.lua', 'dispatch.lua', 'resolver.lua', 'route_checks.lua', 'routes.lua', 'dispatch_route.lua', 'validator.lua' ].each do |script| template File.join(nginx_scripts_dir, script) do source "nginx/scripts/#{script}.erb" owner 'root' group 'root' mode '0644' variables lbconf # Note that due to JIT compile of lua resources, any # changes to them will require a full restart to be picked up. # This includes any embedded lua. notifies :restart, 'runit_service[nginx]' unless backend_secondary? end end %w(https http).each do |server_proto| config_key = "chef_#{server_proto}_config".to_sym lb_config = chef_lb_configs[config_key] template lb_config do source 'nginx/nginx_chef_api_lb.conf.erb' owner 'root' group 'root' mode '0644' variables(lbconf.merge( :server_proto => server_proto, :script_path => nginx_scripts_dir, # Compliance endpoint to forward profiles calls to the Automate API: # /organizations/ORG/owners/OWNER/compliance[/PROFILE] # Supports the legacy(chef-gate) URLs as well: # /compliance/organizations/ORG/owners/OWNER/compliance[/PROFILE] :compliance_proxy_regex => '(?:/compliance)?/organizations/([^/]+)/owners/([^/]+)/compliance(.*)' ) ) notifies :restart, 'runit_service[nginx]' unless backend_secondary? end end # top-level and internal load balancer config nginx_config = File.join(nginx_etc_dir, 'nginx.conf') template nginx_config do source 'nginx/nginx.conf.erb' owner 'root' group 'root' mode '0644' variables(lbconf.merge(chef_lb_configs).merge(:temp_dir => nginx_tempfile_dir)) notifies :restart, 'runit_service[nginx]' unless backend_secondary? end # Write out README.md for addons dir cookbook_file File.join(nginx_addon_dir, 'README.md') do source 'nginx/nginx-addons.README.md' owner 'root' group 'root' mode '0644' end # Set up runit service for nginx component component_runit_service 'nginx' # log rotation template '/etc/opscode/logrotate.d/nginx' do source 'logrotate.erb' owner 'root' group 'root' mode '0644' variables(node['private_chef']['nginx'].to_hash.merge( 'postrotate' => "/opt/opscode/embedded/sbin/nginx -c #{nginx_config} -s reopen", 'owner' => OmnibusHelper.new(node).ownership['owner'], 'group' => OmnibusHelper.new(node).ownership['group'] )) end Set the correct owner and permissions for SSL certificate and key This is a follow up to https://github.com/chef/chef-server/pull/1366 and https://github.com/chef/chef-server/pull/1368. This patch will set the owner of the ssl certificate and key to the user that is running rabbitmq/nginx. In #1366, we discovered that rabbitmq was expecting certs to be in the nginx directory, however that wasn't necessarily the case when the ssl certificate was not generated by private-chef-cookbooks. In these cases, the rabbitmq management interface would be completely broken as the certs we asked it to use were not there. After fixing that, #1368 was required because the custom certificate that was being set for the accpetance environment was owned by root and had the permissions 600, which meant the opscode user could not read it. Rabbitmq does not start as root like nginx, so rabitmq was unable to read the certificate. While #1368 got our environment working, I suspect others may run into a similar issue unless we explicitly set the owner and permissions on the files to what we expect. Signed-off-by: Jay Mundrawala <14c87d485949d83cd94b58aa92882ffbfa7532e0@chef.io> # # Author:: Adam Jacob (<adam@chef.io>) # Author:: Charles Johnson (<charles@chef.io>) # Copyright:: Copyright (c) 2011-2015 CHEF Software, Inc. # # All Rights Reserved # # Create all nginx dirs nginx_log_dir = node['private_chef']['nginx']['log_directory'] nginx_dir = node['private_chef']['nginx']['dir'] nginx_ca_dir = File.join(nginx_dir, 'ca') nginx_cache_dir = File.join(nginx_dir, 'cache') nginx_cache_tmp_dir = File.join(nginx_dir, 'cache-tmp') nginx_etc_dir = File.join(nginx_dir, 'etc') nginx_addon_dir = File.join(nginx_etc_dir, 'addon.d') nginx_d_dir = File.join(nginx_etc_dir, 'nginx.d') nginx_scripts_dir = File.join(nginx_etc_dir, 'scripts') nginx_html_dir = File.join(nginx_dir, 'html') nginx_tempfile_dir = File.join(nginx_dir, 'tmp') [ nginx_log_dir, nginx_dir, nginx_ca_dir, nginx_cache_dir, nginx_cache_tmp_dir, nginx_etc_dir, nginx_addon_dir, nginx_d_dir, nginx_scripts_dir, nginx_html_dir, nginx_tempfile_dir ].each do |dir_name| directory dir_name do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode node['private_chef']['service_dir_perms'] recursive true end end # Create empty error log files %w(access.log error.log current).each do |logfile| file File.join(nginx_log_dir, logfile) do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '0644' end end # Generate self-signed SSL certificate unless the user has provided one if (node['private_chef']['nginx']['ssl_certificate'].nil? && node['private_chef']['nginx']['ssl_certificate_key'].nil?) ssl_keyfile = File.join(nginx_ca_dir, "#{node['private_chef']['nginx']['server_name']}.key") ssl_crtfile = File.join(nginx_ca_dir, "#{node['private_chef']['nginx']['server_name']}.crt") server_name = node['private_chef']['nginx']['server_name'] server_name_type = if OmnibusHelper.is_ip?(server_name) "IP" else "DNS" end openssl_x509 ssl_crtfile do common_name server_name org node['private_chef']['nginx']['ssl_company_name'] org_unit node['private_chef']['nginx']['ssl_organizational_unit_name'] country node['private_chef']['nginx']['ssl_country_name'] key_length node['private_chef']['nginx']['ssl_key_length'] expire node['private_chef']['nginx']['ssl_duration'] subject_alt_name [ "#{server_name_type}:#{server_name}" ] owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '0600' end node.default['private_chef']['nginx']['ssl_certificate'] = ssl_crtfile node.default['private_chef']['nginx']['ssl_certificate_key'] = ssl_keyfile end # The cert and key must be readable by the opscode user since rabbitmq also reads it file node['private_chef']['nginx']['ssl_certificate'] do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '0600' end file node['private_chef']['nginx']['ssl_certificate_key'] do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '0600' end # Copy the required_recipe source into the nginx static root directory and # ensure that it's only modifiable by root. if node['private_chef']['required_recipe']['enable'] remote_file ::File.join(nginx_html_dir, 'required_recipe') do source "file://#{node['private_chef']['required_recipe']['path']}" owner 'root' group 'root' mode '0644' end end # Generate dhparam.pem unless the user has provided a dhparam file if node['private_chef']['nginx']['ssl_dhparam'].nil? ssl_dhparam = File.join(nginx_ca_dir, 'dhparams.pem') openssl_dhparam ssl_dhparam do key_length node['private_chef']['nginx']['dhparam_key_length'] generator node['private_chef']['nginx']['dhparam_generator_id'] owner 'root' group 'root' mode '0644' end node.default['private_chef']['nginx']['ssl_dhparam'] = ssl_dhparam end # Create static html directory remote_directory nginx_html_dir do source 'html' files_backup false files_owner 'root' files_group 'root' files_mode '0644' owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode node['private_chef']['service_dir_perms'] end # Create nginx config chef_lb_configs = { :chef_https_config => File.join(nginx_etc_dir, 'chef_https_lb.conf'), :chef_http_config => File.join(nginx_etc_dir, 'chef_http_lb.conf'), :script_path => nginx_scripts_dir } nginx_vars = node['private_chef']['nginx'].to_hash nginx_vars = nginx_vars.merge(:helper => NginxErb.new(node)) # Chef API lb config for HTTPS and HTTP lbconf = node['private_chef']['lb'].to_hash.merge(nginx_vars).merge( :redis_host => node['private_chef']['redis_lb']['vip'], :redis_port => node['private_chef']['redis_lb']['port'], :omnihelper => OmnibusHelper.new(node) ) ['config.lua', 'dispatch.lua', 'resolver.lua', 'route_checks.lua', 'routes.lua', 'dispatch_route.lua', 'validator.lua' ].each do |script| template File.join(nginx_scripts_dir, script) do source "nginx/scripts/#{script}.erb" owner 'root' group 'root' mode '0644' variables lbconf # Note that due to JIT compile of lua resources, any # changes to them will require a full restart to be picked up. # This includes any embedded lua. notifies :restart, 'runit_service[nginx]' unless backend_secondary? end end %w(https http).each do |server_proto| config_key = "chef_#{server_proto}_config".to_sym lb_config = chef_lb_configs[config_key] template lb_config do source 'nginx/nginx_chef_api_lb.conf.erb' owner 'root' group 'root' mode '0644' variables(lbconf.merge( :server_proto => server_proto, :script_path => nginx_scripts_dir, # Compliance endpoint to forward profiles calls to the Automate API: # /organizations/ORG/owners/OWNER/compliance[/PROFILE] # Supports the legacy(chef-gate) URLs as well: # /compliance/organizations/ORG/owners/OWNER/compliance[/PROFILE] :compliance_proxy_regex => '(?:/compliance)?/organizations/([^/]+)/owners/([^/]+)/compliance(.*)' ) ) notifies :restart, 'runit_service[nginx]' unless backend_secondary? end end # top-level and internal load balancer config nginx_config = File.join(nginx_etc_dir, 'nginx.conf') template nginx_config do source 'nginx/nginx.conf.erb' owner 'root' group 'root' mode '0644' variables(lbconf.merge(chef_lb_configs).merge(:temp_dir => nginx_tempfile_dir)) notifies :restart, 'runit_service[nginx]' unless backend_secondary? end # Write out README.md for addons dir cookbook_file File.join(nginx_addon_dir, 'README.md') do source 'nginx/nginx-addons.README.md' owner 'root' group 'root' mode '0644' end # Set up runit service for nginx component component_runit_service 'nginx' # log rotation template '/etc/opscode/logrotate.d/nginx' do source 'logrotate.erb' owner 'root' group 'root' mode '0644' variables(node['private_chef']['nginx'].to_hash.merge( 'postrotate' => "/opt/opscode/embedded/sbin/nginx -c #{nginx_config} -s reopen", 'owner' => OmnibusHelper.new(node).ownership['owner'], 'group' => OmnibusHelper.new(node).ownership['group'] )) end
class Moreamp < Cask version '0.1.28' sha256 '2f07c82bb5b29e12185cd35c3f3cd9c472e8cc837fe426af1c82af9428c89695' url 'https://downloads.sourceforge.net/project/moreamp/moreamp/MoreAmp-0.1.28/MoreAmp-0.1.28-binOSXintel.dmg' homepage 'http://sourceforge.net/projects/moreamp/' link 'MoreAmp.app' end app stanza in moreamp.rb class Moreamp < Cask version '0.1.28' sha256 '2f07c82bb5b29e12185cd35c3f3cd9c472e8cc837fe426af1c82af9428c89695' url 'https://downloads.sourceforge.net/project/moreamp/moreamp/MoreAmp-0.1.28/MoreAmp-0.1.28-binOSXintel.dmg' homepage 'http://sourceforge.net/projects/moreamp/' app 'MoreAmp.app' end
# # Author:: James Casey <james@chef.io> # Copyright:: Copyright (c) 2014-2015 Chef Software, Inc. # # All Rights Reserved # If no sign_up_url is defined, use the server URL. # # We don't have a clear way to detect whether Manage is installed or running or # whether it's running on an alternate host/port, short of slurping the # manage-running.json, so there's not an easy way to detect what the *actual* # sign up URL is or whether we have one (which we won't if Manage is not # installed), so we use the api_fqdn by default, which is the default location # if Manage is installed with its default settings. # # In the long term, sign up is going to be moved into oc-id anyway, so this will # not be an issue. In the short term, we will provide a way to disable sign up # (see https://github.com/chef/oc-id/issues/41.) # # For now, if the sign up URL for Manage is anything different than what we # default to here, you'll need to define it explicitly. sign_up_url = node['private_chef']['oc_id']['sign_up_url'] unless sign_up_url sign_up_url = "https://#{node['private_chef']['api_fqdn']}/signup" end app_settings = { 'chef' => { 'endpoint' => "https://#{node['private_chef']['lb_internal']['vip']}", 'superuser' => 'pivotal', # # Why is this verify_none? # # Since we set the endpoint to 'localhost', even if we set the # trusted_cert_dir to include the user-provided or self-signed # cert in use by nginx, we will likely fail verification since # those are certs for the api_fqdn and not localhost. # 'ssl_verify_mode' => 'verify_none' }, 'doorkeeper' => { 'administrators' => node['private_chef']['oc_id']['administrators'] || [] }, 'sentry_dsn' => node['private_chef']['oc_id']['sentry_dsn'], 'sign_up_url' => sign_up_url, 'email_from_address' => node['private_chef']['oc_id']['email_from_address'], 'origin' => node['private_chef']['oc_id']['origin'] } oc_id_dir = node['private_chef']['oc_id']['dir'] oc_id_config_dir = File.join(oc_id_dir, "config") oc_id_tmp_dir = File.join(oc_id_dir, "tmp") oc_id_log_dir = node['private_chef']['oc_id']['log_directory'] [ oc_id_dir, oc_id_config_dir, oc_id_tmp_dir, oc_id_log_dir, ].each do |dir_name| directory dir_name do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode node['private_chef']['service_dir_perms'] recursive true end end %w{log tmp}.each do |dir| full_dir = "/opt/opscode/embedded/service/oc_id/#{dir}" directory full_dir do action :delete recursive true not_if { File.symlink?(full_dir) } end end link "/opt/opscode/embedded/service/oc_id/log" do to oc_id_log_dir end link "/opt/opscode/embedded/service/oc_id/tmp" do to oc_id_tmp_dir end # this is needed to allow for attributes which are lists to be marshalled # properly mutable_hash = JSON.parse(app_settings.dup.to_json) file "#{oc_id_config_dir}/production.yml" do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' content mutable_hash.to_yaml notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end # ## Symlink settings file into the rails service directory # settings_file = "/opt/opscode/embedded/service/oc_id/config/settings/production.yml" file settings_file do action :delete not_if { File.symlink?(settings_file) } end link settings_file do to "#{oc_id_config_dir}/production.yml" end template "#{oc_id_config_dir}/secret_token.rb" do source "oc_id.secret_token.rb" owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end secrets_file = "/opt/opscode/embedded/service/oc_id/config/initializers/secret_token.rb" file secrets_file do action :delete not_if { File.symlink?(secrets_file) } end link secrets_file do to "#{oc_id_config_dir}/secret_token.rb" end template "#{oc_id_config_dir}/database.yml" do source "oc_id.database.yml.erb" owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end database_file = "/opt/opscode/embedded/service/oc_id/config/database.yml" file database_file do action :delete not_if { File.symlink?(database_file) } end link database_file do to "#{node['private_chef']['oc_id']['dir']}/config/database.yml" end # Ensure log files are owned by opscode. In Chef 12.14 the svlogd # service was changed to run as opscode rather than root. This is done # as an execute to avoid issues with the `current` file not being # there on the first run. execute "chown -R #{OmnibusHelper.new(node).ownership['owner']}:#{OmnibusHelper.new(node).ownership['group']} #{oc_id_log_dir}" veil_helper_args = "--use-file -s chef-server.webui_key -s oc_id.sql_password -s oc_id.secret_key_base" execute "oc_id_schema" do command "veil-env-helper #{veil_helper_args} -- bundle exec --keep-file-descriptors rake db:migrate" cwd "/opt/opscode/embedded/service/oc_id" # There are other recipes that depend on having a VERSION environment # variable. If that environment variable is set when we run `rake db:migrate`, # and it is set to something the migrations do not expect, this will # break. # # We want to migrate to the latest version, which we can get by looking at the # date prefix of the latest file in the db/migrate directory. # # Also set the RAILS_ENV as is needed. environment("RAILS_ENV" => "production", "VERSION" => `ls -1 /opt/opscode/embedded/service/oc_id/db/migrate | tail -n 1 | sed -e "s/_.*//g"`.chomp, "PATH" => "/opt/opscode/embedded/bin") sensitive true only_if { is_data_master? } end component_runit_service "oc_id" do package 'private_chef' end if node['private_chef']['bootstrap']['enable'] execute "/opt/opscode/bin/private-chef-ctl start oc_id" do retries 20 end end # Take the existing oc_id.applications (with only a redirect_uri), ensure they # exist in the database, and dump their data to /etc/opscode/oc-id-applications. node['private_chef']['oc_id']['applications'].each do |name, app| oc_id_application name do write_to_disk node['private_chef']['insecure_addon_compat'] redirect_uri app['redirect_uri'] only_if { is_data_master? } end end nginx_dir = node['private_chef']['nginx']['dir'] nginx_etc_dir = File.join(nginx_dir, "etc") nginx_addon_dir = File.join(nginx_etc_dir, "addon.d") directory nginx_addon_dir do action :create recursive true end # LB configs ["upstreams", "external"].each do |config| file = File.join(nginx_addon_dir, "40-oc_id_#{config}.conf") template file do source "oc_id.nginx-#{config}.conf.erb" owner "root" group "root" mode "0644" notifies :restart, 'runit_service[nginx]' unless backend_secondary? end end [cookbooks] Avoid unnecessary oc_id restarts Previously, oc_id would be restarted on every reconfigure because the config file would get chowned to opscode and then back to root. Since we only want to do the chown when migrating old log dirs, we do a simple test to see if we can skip it. Signed-off-by: Steven Danna <9ce5770b3bb4b2a1d59be2d97e34379cd192299f@chef.io> # # Author:: James Casey <james@chef.io> # Copyright:: Copyright (c) 2014-2015 Chef Software, Inc. # # All Rights Reserved # If no sign_up_url is defined, use the server URL. # # We don't have a clear way to detect whether Manage is installed or running or # whether it's running on an alternate host/port, short of slurping the # manage-running.json, so there's not an easy way to detect what the *actual* # sign up URL is or whether we have one (which we won't if Manage is not # installed), so we use the api_fqdn by default, which is the default location # if Manage is installed with its default settings. # # In the long term, sign up is going to be moved into oc-id anyway, so this will # not be an issue. In the short term, we will provide a way to disable sign up # (see https://github.com/chef/oc-id/issues/41.) # # For now, if the sign up URL for Manage is anything different than what we # default to here, you'll need to define it explicitly. sign_up_url = node['private_chef']['oc_id']['sign_up_url'] unless sign_up_url sign_up_url = "https://#{node['private_chef']['api_fqdn']}/signup" end app_settings = { 'chef' => { 'endpoint' => "https://#{node['private_chef']['lb_internal']['vip']}", 'superuser' => 'pivotal', # # Why is this verify_none? # # Since we set the endpoint to 'localhost', even if we set the # trusted_cert_dir to include the user-provided or self-signed # cert in use by nginx, we will likely fail verification since # those are certs for the api_fqdn and not localhost. # 'ssl_verify_mode' => 'verify_none' }, 'doorkeeper' => { 'administrators' => node['private_chef']['oc_id']['administrators'] || [] }, 'sentry_dsn' => node['private_chef']['oc_id']['sentry_dsn'], 'sign_up_url' => sign_up_url, 'email_from_address' => node['private_chef']['oc_id']['email_from_address'], 'origin' => node['private_chef']['oc_id']['origin'] } oc_id_dir = node['private_chef']['oc_id']['dir'] oc_id_config_dir = File.join(oc_id_dir, "config") oc_id_tmp_dir = File.join(oc_id_dir, "tmp") oc_id_log_dir = node['private_chef']['oc_id']['log_directory'] [ oc_id_dir, oc_id_config_dir, oc_id_tmp_dir, oc_id_log_dir, ].each do |dir_name| directory dir_name do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode node['private_chef']['service_dir_perms'] recursive true end end %w{log tmp}.each do |dir| full_dir = "/opt/opscode/embedded/service/oc_id/#{dir}" directory full_dir do action :delete recursive true not_if { File.symlink?(full_dir) } end end link "/opt/opscode/embedded/service/oc_id/log" do to oc_id_log_dir end link "/opt/opscode/embedded/service/oc_id/tmp" do to oc_id_tmp_dir end # this is needed to allow for attributes which are lists to be marshalled # properly mutable_hash = JSON.parse(app_settings.dup.to_json) file "#{oc_id_config_dir}/production.yml" do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' content mutable_hash.to_yaml notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end # ## Symlink settings file into the rails service directory # settings_file = "/opt/opscode/embedded/service/oc_id/config/settings/production.yml" file settings_file do action :delete not_if { File.symlink?(settings_file) } end link settings_file do to "#{oc_id_config_dir}/production.yml" end template "#{oc_id_config_dir}/secret_token.rb" do source "oc_id.secret_token.rb" owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end secrets_file = "/opt/opscode/embedded/service/oc_id/config/initializers/secret_token.rb" file secrets_file do action :delete not_if { File.symlink?(secrets_file) } end link secrets_file do to "#{oc_id_config_dir}/secret_token.rb" end template "#{oc_id_config_dir}/database.yml" do source "oc_id.database.yml.erb" owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end database_file = "/opt/opscode/embedded/service/oc_id/config/database.yml" file database_file do action :delete not_if { File.symlink?(database_file) } end link database_file do to "#{node['private_chef']['oc_id']['dir']}/config/database.yml" end # Ensure log files are owned by opscode. In Chef 12.14 the svlogd # service was changed to run as opscode rather than root. This is done # as an execute to avoid issues with the `current` file not being # there on the first run. execute "chown -R #{OmnibusHelper.new(node).ownership['owner']}:#{OmnibusHelper.new(node).ownership['group']} #{oc_id_log_dir}" do only_if do begin ::File.stat(::File.join(oc_id_log_dir, "current")).uid != Etc.getpwnam(OmnibusHelper.new(node).ownership['owner']).uid rescue Errno::ENOENT true end end end veil_helper_args = "--use-file -s chef-server.webui_key -s oc_id.sql_password -s oc_id.secret_key_base" execute "oc_id_schema" do command "veil-env-helper #{veil_helper_args} -- bundle exec --keep-file-descriptors rake db:migrate" cwd "/opt/opscode/embedded/service/oc_id" # There are other recipes that depend on having a VERSION environment # variable. If that environment variable is set when we run `rake db:migrate`, # and it is set to something the migrations do not expect, this will # break. # # We want to migrate to the latest version, which we can get by looking at the # date prefix of the latest file in the db/migrate directory. # # Also set the RAILS_ENV as is needed. environment("RAILS_ENV" => "production", "VERSION" => `ls -1 /opt/opscode/embedded/service/oc_id/db/migrate | tail -n 1 | sed -e "s/_.*//g"`.chomp, "PATH" => "/opt/opscode/embedded/bin") sensitive true only_if { is_data_master? } end component_runit_service "oc_id" do package 'private_chef' end if node['private_chef']['bootstrap']['enable'] execute "/opt/opscode/bin/private-chef-ctl start oc_id" do retries 20 end end # Take the existing oc_id.applications (with only a redirect_uri), ensure they # exist in the database, and dump their data to /etc/opscode/oc-id-applications. node['private_chef']['oc_id']['applications'].each do |name, app| oc_id_application name do write_to_disk node['private_chef']['insecure_addon_compat'] redirect_uri app['redirect_uri'] only_if { is_data_master? } end end nginx_dir = node['private_chef']['nginx']['dir'] nginx_etc_dir = File.join(nginx_dir, "etc") nginx_addon_dir = File.join(nginx_etc_dir, "addon.d") directory nginx_addon_dir do action :create recursive true end # LB configs ["upstreams", "external"].each do |config| file = File.join(nginx_addon_dir, "40-oc_id_#{config}.conf") template file do source "oc_id.nginx-#{config}.conf.erb" owner "root" group "root" mode "0644" notifies :restart, 'runit_service[nginx]' unless backend_secondary? end end
cask 'mysimbl' do version '0.5.1' sha256 'c57c40a4d93eee94c7f2a68f1ef4aa314eb61fa1012e6ebe248afef42bc48090' # githubusercontent.com/w0lfschild/app_updates/master/mySIMBL was verified as official when first introduced to the cask url "https://raw.githubusercontent.com/w0lfschild/app_updates/master/mySIMBL/mySIMBL_#{version}.zip" appcast 'https://raw.githubusercontent.com/w0lfschild/app_updates/master/mySIMBL/appcast.xml', checkpoint: '7923369a4c5ca5e6df3a493697327505a974abd0bb7b25b893a31151c7150555' name 'mySIMBL' homepage 'https://github.com/w0lfschild/mySIMBL' conflicts_with cask: 'easysimbl' app 'mySIMBL.app' caveats 'System Integrity Protection must be disabled to install SIMBL.' end Add zap delete to mysimbl (#30071) cask 'mysimbl' do version '0.5.1' sha256 'c57c40a4d93eee94c7f2a68f1ef4aa314eb61fa1012e6ebe248afef42bc48090' # githubusercontent.com/w0lfschild/app_updates/master/mySIMBL was verified as official when first introduced to the cask url "https://raw.githubusercontent.com/w0lfschild/app_updates/master/mySIMBL/mySIMBL_#{version}.zip" appcast 'https://raw.githubusercontent.com/w0lfschild/app_updates/master/mySIMBL/appcast.xml', checkpoint: '7923369a4c5ca5e6df3a493697327505a974abd0bb7b25b893a31151c7150555' name 'mySIMBL' homepage 'https://github.com/w0lfschild/mySIMBL' conflicts_with cask: 'easysimbl' app 'mySIMBL.app' zap delete: [ '~/Library/Application Support/mySIMBL', '~/Library/Caches/org.w0lf.mySIMBL', '~/Library/Caches/org.w0lf.mySIMBLAgent', '~/Library/Preferences/org.w0lf.SIMBLAgent.plist', '~/Library/Preferences/org.w0lf.mySIMBL.plist', '~/Library/Preferences/org.w0lf.mySIMBLAgent.plist', ] caveats 'System Integrity Protection must be disabled to install SIMBL.' end
# # Author:: James Casey <james@getchef.com> # Copyright:: Copyright (c) 2014-2015 Chef Software, Inc. # # All Rights Reserved # If no sign_up_url is defined, use the server URL. # # We don't have a clear way to detect whether Manage is installed or running or # whether it's running on an alternate host/port, short of slurping the # manage-running.json, so there's not an easy way to detect what the *actual* # sign up URL is or whether we have one (which we won't if Manage is not # installed), so we use the api_fqdn by default, which is the default location # if Manage is installed with its default settings. # # In the long term, sign up is going to be moved into oc-id anyway, so this will # not be an issue. In the short term, we will provide a way to disable sign up # (see https://github.com/chef/oc-id/issues/41.) # # For now, if the sign up URL for Manage is anything different than what we # default to here, you'll need to define it explicitly. sign_up_url = node['private_chef']['oc_id']['sign_up_url'] unless sign_up_url sign_up_url = "https://#{node['private_chef']['api_fqdn']}/signup" end app_settings = { 'chef' => { 'endpoint' => "https://#{node['private_chef']['lb_internal']['vip']}", 'superuser' => 'pivotal', 'key_path' => '/etc/opscode/webui_priv.pem' }, 'doorkeeper' => { 'administrators' => node['private_chef']['oc_id']['administrators'] || [] }, 'sentry_dsn' => node['private_chef']['oc_id']['sentry_dsn'], 'sign_up_url' => sign_up_url, } oc_id_dir = node['private_chef']['oc_id']['dir'] oc_id_config_dir = File.join(oc_id_dir, "config") oc_id_tmp_dir = File.join(oc_id_dir, "tmp") oc_id_log_dir = node['private_chef']['oc_id']['log_directory'] [ oc_id_dir, oc_id_config_dir, oc_id_tmp_dir, oc_id_log_dir, ].each do |dir_name| directory dir_name do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode node['private_chef']['service_dir_perms'] recursive true end end %w{log tmp}.each do |dir| full_dir = "/opt/opscode/embedded/service/oc_id/#{dir}" directory full_dir do action :delete recursive true not_if { File.symlink?(full_dir) } end end link "/opt/opscode/embedded/service/oc_id/log" do to oc_id_log_dir end link "/opt/opscode/embedded/service/oc_id/tmp" do to oc_id_tmp_dir end # this is needed to allow for attributes which are lists to be marshalled # properly mutable_hash = JSON.parse(app_settings.dup.to_json) file "#{oc_id_config_dir}/production.yml" do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' content mutable_hash.to_yaml notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end # ## Symlink settings file into the rails service directory # settings_file = "/opt/opscode/embedded/service/oc_id/config/settings/production.yml" file settings_file do action :delete not_if { File.symlink?(settings_file) } end link settings_file do to "#{oc_id_config_dir}/production.yml" end template "#{oc_id_config_dir}/secret_token.rb" do source "oc_id.secret_token.rb" owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end secrets_file = "/opt/opscode/embedded/service/oc_id/config/initializers/secret_token.rb" file secrets_file do action :delete not_if { File.symlink?(secrets_file) } end link secrets_file do to "#{oc_id_config_dir}/secret_token.rb" end template "#{oc_id_config_dir}/database.yml" do source "oc_id.database.yml.erb" owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end database_file = "/opt/opscode/embedded/service/oc_id/config/database.yml" file database_file do action :delete not_if { File.symlink?(database_file) } end link database_file do to "#{node['private_chef']['oc_id']['dir']}/config/database.yml" end execute "oc_id_schema" do command "bundle exec rake db:migrate" path ["/opt/opscode/embedded/bin"] cwd "/opt/opscode/embedded/service/oc_id" # There are other recipes that depend on having a VERSION environment # variable. If that environment variable is set when we run `rake db:migrate`, # and it is set to something the migrations do not expect, this will # break. # # We want to migrate to the latest version, which we can get by looking at the # date prefix of the latest file in the db/migrate directory. # # Also set the RAILS_ENV as is needed. environment("RAILS_ENV" => "production", "VERSION" => `ls -1 /opt/opscode/embedded/service/oc_id/db/migrate | tail -n 1 | sed -e "s/_.*//g"`.chomp) only_if { is_data_master? } end component_runit_service "oc_id" do package 'private_chef' end if node['private_chef']['bootstrap']['enable'] execute "/opt/opscode/bin/private-chef-ctl start oc_id" do retries 20 end end # Take the existing oc_id.applications (with only a redirect_uri), ensure they # exist in the database, and dump their data to /etc/opscode/oc-id-applications. node['private_chef']['oc_id']['applications'].each do |name, app| oc_id_application name do redirect_uri app['redirect_uri'] only_if { is_data_master? } end end nginx_dir = node['private_chef']['nginx']['dir'] nginx_etc_dir = File.join(nginx_dir, "etc") nginx_addon_dir = File.join(nginx_etc_dir, "addon.d") directory nginx_addon_dir do action :create recursive true end # LB configs ["upstreams", "external"].each do |config| file = File.join(nginx_addon_dir, "40-oc_id_#{config}.conf") template file do source "oc_id.nginx-#{config}.conf.erb" owner "root" group "root" mode "0644" notifies :restart, 'runit_service[nginx]' unless backend_secondary? end end Fixes Chef 13 warning related to using 'environment' attribute to configure 'PATH'. # # Author:: James Casey <james@getchef.com> # Copyright:: Copyright (c) 2014-2015 Chef Software, Inc. # # All Rights Reserved # If no sign_up_url is defined, use the server URL. # # We don't have a clear way to detect whether Manage is installed or running or # whether it's running on an alternate host/port, short of slurping the # manage-running.json, so there's not an easy way to detect what the *actual* # sign up URL is or whether we have one (which we won't if Manage is not # installed), so we use the api_fqdn by default, which is the default location # if Manage is installed with its default settings. # # In the long term, sign up is going to be moved into oc-id anyway, so this will # not be an issue. In the short term, we will provide a way to disable sign up # (see https://github.com/chef/oc-id/issues/41.) # # For now, if the sign up URL for Manage is anything different than what we # default to here, you'll need to define it explicitly. sign_up_url = node['private_chef']['oc_id']['sign_up_url'] unless sign_up_url sign_up_url = "https://#{node['private_chef']['api_fqdn']}/signup" end app_settings = { 'chef' => { 'endpoint' => "https://#{node['private_chef']['lb_internal']['vip']}", 'superuser' => 'pivotal', 'key_path' => '/etc/opscode/webui_priv.pem' }, 'doorkeeper' => { 'administrators' => node['private_chef']['oc_id']['administrators'] || [] }, 'sentry_dsn' => node['private_chef']['oc_id']['sentry_dsn'], 'sign_up_url' => sign_up_url, } oc_id_dir = node['private_chef']['oc_id']['dir'] oc_id_config_dir = File.join(oc_id_dir, "config") oc_id_tmp_dir = File.join(oc_id_dir, "tmp") oc_id_log_dir = node['private_chef']['oc_id']['log_directory'] [ oc_id_dir, oc_id_config_dir, oc_id_tmp_dir, oc_id_log_dir, ].each do |dir_name| directory dir_name do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode node['private_chef']['service_dir_perms'] recursive true end end %w{log tmp}.each do |dir| full_dir = "/opt/opscode/embedded/service/oc_id/#{dir}" directory full_dir do action :delete recursive true not_if { File.symlink?(full_dir) } end end link "/opt/opscode/embedded/service/oc_id/log" do to oc_id_log_dir end link "/opt/opscode/embedded/service/oc_id/tmp" do to oc_id_tmp_dir end # this is needed to allow for attributes which are lists to be marshalled # properly mutable_hash = JSON.parse(app_settings.dup.to_json) file "#{oc_id_config_dir}/production.yml" do owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' content mutable_hash.to_yaml notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end # ## Symlink settings file into the rails service directory # settings_file = "/opt/opscode/embedded/service/oc_id/config/settings/production.yml" file settings_file do action :delete not_if { File.symlink?(settings_file) } end link settings_file do to "#{oc_id_config_dir}/production.yml" end template "#{oc_id_config_dir}/secret_token.rb" do source "oc_id.secret_token.rb" owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end secrets_file = "/opt/opscode/embedded/service/oc_id/config/initializers/secret_token.rb" file secrets_file do action :delete not_if { File.symlink?(secrets_file) } end link secrets_file do to "#{oc_id_config_dir}/secret_token.rb" end template "#{oc_id_config_dir}/database.yml" do source "oc_id.database.yml.erb" owner OmnibusHelper.new(node).ownership['owner'] group OmnibusHelper.new(node).ownership['group'] mode '640' notifies :restart, 'runit_service[oc_id]' unless backend_secondary? end database_file = "/opt/opscode/embedded/service/oc_id/config/database.yml" file database_file do action :delete not_if { File.symlink?(database_file) } end link database_file do to "#{node['private_chef']['oc_id']['dir']}/config/database.yml" end execute "oc_id_schema" do command "bundle exec rake db:migrate" cwd "/opt/opscode/embedded/service/oc_id" # There are other recipes that depend on having a VERSION environment # variable. If that environment variable is set when we run `rake db:migrate`, # and it is set to something the migrations do not expect, this will # break. # # We want to migrate to the latest version, which we can get by looking at the # date prefix of the latest file in the db/migrate directory. # # Also set the RAILS_ENV as is needed. environment("RAILS_ENV" => "production", "VERSION" => `ls -1 /opt/opscode/embedded/service/oc_id/db/migrate | tail -n 1 | sed -e "s/_.*//g"`.chomp, "PATH" => "/opt/opscode/embedded/bin") only_if { is_data_master? } end component_runit_service "oc_id" do package 'private_chef' end if node['private_chef']['bootstrap']['enable'] execute "/opt/opscode/bin/private-chef-ctl start oc_id" do retries 20 end end # Take the existing oc_id.applications (with only a redirect_uri), ensure they # exist in the database, and dump their data to /etc/opscode/oc-id-applications. node['private_chef']['oc_id']['applications'].each do |name, app| oc_id_application name do redirect_uri app['redirect_uri'] only_if { is_data_master? } end end nginx_dir = node['private_chef']['nginx']['dir'] nginx_etc_dir = File.join(nginx_dir, "etc") nginx_addon_dir = File.join(nginx_etc_dir, "addon.d") directory nginx_addon_dir do action :create recursive true end # LB configs ["upstreams", "external"].each do |config| file = File.join(nginx_addon_dir, "40-oc_id_#{config}.conf") template file do source "oc_id.nginx-#{config}.conf.erb" owner "root" group "root" mode "0644" notifies :restart, 'runit_service[nginx]' unless backend_secondary? end end
cask "nordvpn" do version "6.5.0,165" sha256 "7162ed0dc3c240ea6b2082b9f277a832ea3f24dc49a3d4f66f506502cc3abfbc" url "https://downloads.nordcdn.com/apps/macos/generic/NordVPN-OpenVPN/#{version.before_comma}/NordVPN.pkg", verified: "downloads.nordcdn.com/" name "NordVPN" desc "VPN client for secure internet access and private browsing" homepage "https://nordvpn.com/" livecheck do url "https://downloads.nordcdn.com/apps/macos/generic/NordVPN-OpenVPN/latest/update_pkg.xml" strategy :sparkle end auto_updates true pkg "NordVPN.pkg" uninstall quit: [ "com.nordvpn.osx", "com.nordvpn.osx.NordVPNLauncher", ], launchctl: [ "com.nordvpn.osx.helper", "com.nordvpn.NordVPN.Helper", ], delete: [ "/Library/PrivilegedHelperTools/com.nordvpn.osx.helper", "/Library/PrivilegedHelperTools/com.nordvpn.osx.ovpnDnsManager", ], login_item: "NordVPN", pkgutil: "com.nordvpn.osx" zap trash: [ "~/Library/Application Support/com.nordvpn.osx", "~/Library/Caches/com.nordvpn.osx", "~/Library/Logs/NordVPN/", "~/Library/Preferences/com.nordvpn.osx.plist", "~/Library/Saved Application State/com.nordvpn.osx.savedState", "~/Library/Cookies/com.nordvpn.osx.binarycookies", ] end Update nordvpn from 6.5.0,165 to 6.6.1,167 (#109401) * Update nordvpn from 6.5.0,165 to 6.6.1,167 * Update nordvpn.rb cask "nordvpn" do version "6.6.1,167" sha256 "80144b64333f82ae0b2993f937dceab1feed7d1532ac18cbaf3f9fdcf304f6e7" url "https://downloads.nordcdn.com/apps/macos/generic/NordVPN-OpenVPN/#{version.before_comma}/NordVPN.pkg", verified: "downloads.nordcdn.com/" name "NordVPN" desc "VPN client for secure internet access and private browsing" homepage "https://nordvpn.com/" livecheck do url "https://downloads.nordcdn.com/apps/macos/generic/NordVPN-OpenVPN/latest/update_pkg.xml" strategy :sparkle end auto_updates true pkg "NordVPN.pkg" uninstall quit: [ "com.nordvpn.macos", "com.nordvpn.macos.NordVPNLauncher", ], launchctl: [ "com.nordvpn.macos.helper", "com.nordvpn.NordVPN.Helper", ], delete: [ "/Library/PrivilegedHelperTools/com.nordvpn.macos.helper", "/Library/PrivilegedHelperTools/com.nordvpn.macos.ovpnDnsManager", ], login_item: "NordVPN", pkgutil: "com.nordvpn.macos" zap trash: [ "~/Library/Application Support/com.nordvpn.macos", "~/Library/Caches/com.nordvpn.macos", "~/Library/Logs/NordVPN/", "~/Library/Preferences/com.nordvpn.macos.plist", "~/Library/Saved Application State/com.nordvpn.macos.savedState", "~/Library/Cookies/com.nordvpn.macos.binarycookies", ] end
# -*- encoding: utf-8 -*- require File.join(File.dirname(__FILE__), "lib/brightbox-cli/version") Gem::Specification.new do |s| s.name = "brightbox-cli" s.version = Brightbox::VERSION s.platform = Gem::Platform::RUBY s.authors = ["John Leach"] s.email = ["john@brightbox.co.uk"] s.homepage = "http://docs.brightbox.com/cli" s.summary = %q{The Brightbox cloud management system} s.description = %q{Scripts to interact with the Brightbox cloud API} s.rubyforge_project = "brightbox-cli" s.files = `git ls-files`.split("\n") + `find lib/brightbox-cli/vendor`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency 'json', '~> 1.5.3' s.add_dependency('builder') s.add_dependency('excon', '~>0.9.0') s.add_dependency('formatador', '~>0.2.0') s.add_dependency('mime-types') s.add_dependency('net-ssh', '>=2.1.3') s.add_dependency('net-scp', '~>1.0.4') s.add_dependency('nokogiri', '>=1.4.0') s.add_dependency('ruby-hmac') s.add_dependency('hirb','~> 0.6.0') s.add_development_dependency('rake', '~> 0.8.0') s.add_development_dependency('vcr') s.add_development_dependency('rspec') s.add_development_dependency('mocha') end We are not compatible with VCR 2.0 yet # -*- encoding: utf-8 -*- require File.join(File.dirname(__FILE__), "lib/brightbox-cli/version") Gem::Specification.new do |s| s.name = "brightbox-cli" s.version = Brightbox::VERSION s.platform = Gem::Platform::RUBY s.authors = ["John Leach"] s.email = ["john@brightbox.co.uk"] s.homepage = "http://docs.brightbox.com/cli" s.summary = %q{The Brightbox cloud management system} s.description = %q{Scripts to interact with the Brightbox cloud API} s.rubyforge_project = "brightbox-cli" s.files = `git ls-files`.split("\n") + `find lib/brightbox-cli/vendor`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency 'json', '~> 1.5.3' s.add_dependency('builder') s.add_dependency('excon', '~>0.9.0') s.add_dependency('formatador', '~>0.2.0') s.add_dependency('mime-types') s.add_dependency('net-ssh', '>=2.1.3') s.add_dependency('net-scp', '~>1.0.4') s.add_dependency('nokogiri', '>=1.4.0') s.add_dependency('ruby-hmac') s.add_dependency('hirb','~> 0.6.0') s.add_development_dependency('rake', '~> 0.8.0') s.add_development_dependency('vcr', '~> 1.11.3') s.add_development_dependency('rspec', '~> 2.8.0') s.add_development_dependency('mocha') end
cask "nordvpn" do version "6.2.0,160" sha256 "3db81f9c204cdecd2b272daef8504e3a05cdbe4cc9805d7f032c542284acf725" url "https://downloads.nordcdn.com/apps/macos/generic/NordVPN-OpenVPN/#{version.before_comma}/NordVPN.pkg", verified: "downloads.nordcdn.com/" name "NordVPN" desc "VPN client for secure internet access and private browsing" homepage "https://nordvpn.com/" livecheck do url "https://downloads.nordcdn.com/apps/macos/generic/NordVPN-OpenVPN/latest/update_pkg.xml" strategy :sparkle end auto_updates true pkg "NordVPN.pkg" uninstall quit: [ "com.nordvpn.osx", "com.nordvpn.osx.NordVPNLauncher", ], launchctl: [ "com.nordvpn.osx.helper", "com.nordvpn.NordVPN.Helper", ], delete: [ "/Library/PrivilegedHelperTools/com.nordvpn.osx.helper", "/Library/PrivilegedHelperTools/com.nordvpn.osx.ovpnDnsManager", ], login_item: "NordVPN", pkgutil: "com.nordvpn.osx" zap trash: [ "~/Library/Application Support/com.nordvpn.osx", "~/Library/Caches/com.nordvpn.osx", "~/Library/Logs/NordVPN/", "~/Library/Preferences/com.nordvpn.osx.plist", "~/Library/Saved Application State/com.nordvpn.osx.savedState", "~/Library/Cookies/com.nordvpn.osx.binarycookies", ] end Update nordvpn from 6.2.0,160 to 6.3.0,161 (#104915) Co-authored-by: Robert Schumann <12e9293ec6b30c7fa8a0926af42807e929c1684f@schumann.cloud> cask "nordvpn" do version "6.3.0,161" sha256 "f78a1549c3c2853e595d280b02a6535a7c0ac0a08d5e79813bcc88657e1d4a1c" url "https://downloads.nordcdn.com/apps/macos/generic/NordVPN-OpenVPN/#{version.before_comma}/NordVPN.pkg", verified: "downloads.nordcdn.com/" name "NordVPN" desc "VPN client for secure internet access and private browsing" homepage "https://nordvpn.com/" livecheck do url "https://downloads.nordcdn.com/apps/macos/generic/NordVPN-OpenVPN/latest/update_pkg.xml" strategy :sparkle end auto_updates true pkg "NordVPN.pkg" uninstall quit: [ "com.nordvpn.osx", "com.nordvpn.osx.NordVPNLauncher", ], launchctl: [ "com.nordvpn.osx.helper", "com.nordvpn.NordVPN.Helper", ], delete: [ "/Library/PrivilegedHelperTools/com.nordvpn.osx.helper", "/Library/PrivilegedHelperTools/com.nordvpn.osx.ovpnDnsManager", ], login_item: "NordVPN", pkgutil: "com.nordvpn.osx" zap trash: [ "~/Library/Application Support/com.nordvpn.osx", "~/Library/Caches/com.nordvpn.osx", "~/Library/Logs/NordVPN/", "~/Library/Preferences/com.nordvpn.osx.plist", "~/Library/Saved Application State/com.nordvpn.osx.savedState", "~/Library/Cookies/com.nordvpn.osx.binarycookies", ] end
cask 'nuclear' do version '0.6.3,fca030' sha256 'ae4e3f599089bb484ac503547c8553517da0689a1f9d2515487bac174f4a0e4d' # github.com/nukeop/nuclear/ was verified as official when first introduced to the cask url "https://github.com/nukeop/nuclear/releases/download/v#{version.before_comma}/nuclear-#{version.after_comma}.dmg" appcast 'https://github.com/nukeop/nuclear/releases.atom' name 'Nuclear' homepage 'https://nuclear.js.org/' app 'nuclear.app' end Update nuclear (#85081) Add `zap` stanza. cask 'nuclear' do version '0.6.3,fca030' sha256 'ae4e3f599089bb484ac503547c8553517da0689a1f9d2515487bac174f4a0e4d' # github.com/nukeop/nuclear/ was verified as official when first introduced to the cask url "https://github.com/nukeop/nuclear/releases/download/v#{version.before_comma}/nuclear-#{version.after_comma}.dmg" appcast 'https://github.com/nukeop/nuclear/releases.atom' name 'Nuclear' homepage 'https://nuclear.js.org/' app 'nuclear.app' zap trash: [ '~/Library/Application Support/nuclear', '~/Library/Logs/nuclear', '~/Library/Preferences/nuclear.plist', '~/Library/Saved Application State/nuclear.savedState', ] end
cask 'onepile' do version '2.2-1106' sha256 '8554a14a87ea476e1b596147a80ac92a91cf14eb0de948079597e7d48705b316' url "https://onepile.app/update/macos/OnePile-#{version}.zip" appcast 'https://onepile.app/sparklecast.xml' name 'OnePile' homepage 'https://onepile.app/' depends_on macos: '>= :high_sierra' app 'OnePile.app' end Update onepile from 2.2-1106 to 2.3-1120 (#73596) cask 'onepile' do version '2.3-1120' sha256 'b88e38120bfb124cfe2ba7faa73384757c4c137dc1760617e67a8ecdadaa0fee' url "https://onepile.app/update/macos/OnePile-#{version}.zip" appcast 'https://onepile.app/sparklecast.xml' name 'OnePile' homepage 'https://onepile.app/' depends_on macos: '>= :high_sierra' app 'OnePile.app' end
cask 'openzfs' do version '1.6.1,f8' sha256 '126ce9215ec060b2eb60db0609b29acad334f0d1c30c5ef2ab97cb251f374c39' url "https://openzfsonosx.org/w/images/#{version.after_comma[0]}/#{version.after_comma}/OpenZFS_on_OS_X_#{version.before_comma}.dmg" name 'OpenZFS on OS X' homepage 'https://openzfsonosx.org/' depends_on macos: '>= :mountain_lion' if MacOS.version == :mountain_lion pkg "OpenZFS on OS X #{version.before_comma} Mountain Lion.pkg" elsif MacOS.version == :mavericks pkg "OpenZFS on OS X #{version.before_comma} Mavericks.pkg" elsif MacOS.version == :yosemite pkg "OpenZFS on OS X #{version.before_comma} Yosemite.pkg" elsif MacOS.version == :el_capitan pkg "OpenZFS on OS X #{version.before_comma} El Capitan.pkg" elsif MacOS.version >= :sierra pkg "OpenZFS on OS X #{version.before_comma} Sierra.pkg" end uninstall pkgutil: 'net.lundman.openzfs.*' end Update openzfs - uninstall (#35369) cask 'openzfs' do version '1.6.1,f8' sha256 '126ce9215ec060b2eb60db0609b29acad334f0d1c30c5ef2ab97cb251f374c39' url "https://openzfsonosx.org/w/images/#{version.after_comma[0]}/#{version.after_comma}/OpenZFS_on_OS_X_#{version.before_comma}.dmg" name 'OpenZFS on OS X' homepage 'https://openzfsonosx.org/' depends_on macos: '>= :mountain_lion' if MacOS.version == :mountain_lion pkg "OpenZFS on OS X #{version.before_comma} Mountain Lion.pkg" elsif MacOS.version == :mavericks pkg "OpenZFS on OS X #{version.before_comma} Mavericks.pkg" elsif MacOS.version == :yosemite pkg "OpenZFS on OS X #{version.before_comma} Yosemite.pkg" elsif MacOS.version == :el_capitan pkg "OpenZFS on OS X #{version.before_comma} El Capitan.pkg" elsif MacOS.version >= :sierra pkg "OpenZFS on OS X #{version.before_comma} Sierra.pkg" end if MacOS.version >= :el_capitan uninstall_preflight do system_command '/usr/bin/sed', args: ['-i', '.bak', 's|/usr/sbin/zpool|/usr/local/bin/zpool|', "#{staged_path}/Docs & Scripts/uninstall-openzfsonosx.sh"] system_command '/usr/bin/sed', args: ['-i', '.bak', 's|/usr/sbin/zfs|/usr/local/bin/zfs|', "#{staged_path}/Docs & Scripts/uninstall-openzfsonosx.sh"] end end uninstall script: { executable: "#{staged_path}/Docs & Scripts/uninstall-openzfsonosx.sh", sudo: true, } end
cask :v1 => 'osxfuse' do version '2.7.3' sha256 '88d0594e46191aeafa259535398d25c4ccfa03c178e10d925a69e4dcb6293fa2' url "http://downloads.sourceforge.net/project/osxfuse/osxfuse-#{version}/osxfuse-#{version}.dmg" homepage 'https://osxfuse.github.io/' license :oss pkg "Install OSXFUSE #{version[0..-3]}.pkg" uninstall :pkgutil => 'com.github.osxfuse.pkg.Core|com.github.osxfuse.pkg.PrefPane', :kext => 'com.github.osxfuse.filesystems.osxfusefs' end Updated OsxFuse to 2.7.4 cask :v1 => 'osxfuse' do version '2.7.4' sha256 'e5f43f673062725d76b6c10d379d576f6148f32fab42f6d18455b11f41e92969' url "http://downloads.sourceforge.net/project/osxfuse/osxfuse-#{version}/osxfuse-#{version}.dmg" homepage 'https://osxfuse.github.io/' license :oss pkg "Install OSXFUSE #{version[0..-3]}.pkg" uninstall :pkgutil => 'com.github.osxfuse.pkg.Core|com.github.osxfuse.pkg.PrefPane', :kext => 'com.github.osxfuse.filesystems.osxfusefs' end
cask 'osxfuse' do version '3.5.0' sha256 '6d331236ee45782e404f46324a5e6d444943641d3fb62c4d84ba7fab8f4534a5' # github.com/osxfuse was verified as official when first introduced to the cask url "https://github.com/osxfuse/osxfuse/releases/download/osxfuse-#{version}/osxfuse-#{version}.dmg" appcast 'https://github.com/osxfuse/osxfuse/releases.atom', checkpoint: 'd682c42b621aa74feebc066c018b47e4b6356f5f4d8604810c16d9d6bb1f1598' name 'OSXFUSE' homepage 'https://osxfuse.github.io/' license :bsd pkg "Install OSXFUSE #{version.major_minor}.pkg" postflight do set_ownership ['/usr/local/include', '/usr/local/lib'] end uninstall pkgutil: 'com.github.osxfuse.pkg.Core|com.github.osxfuse.pkg.PrefPane', kext: 'com.github.osxfuse.filesystems.osxfusefs' caveats do reboot end end Update osxfuse to 3.5.0 (#24503) cask 'osxfuse' do version '3.5.0' sha256 '6d331236ee45782e404f46324a5e6d444943641d3fb62c4d84ba7fab8f4534a5' # github.com/osxfuse was verified as official when first introduced to the cask url "https://github.com/osxfuse/osxfuse/releases/download/osxfuse-#{version}/osxfuse-#{version}.dmg" appcast 'https://github.com/osxfuse/osxfuse/releases.atom', checkpoint: 'd682c42b621aa74feebc066c018b47e4b6356f5f4d8604810c16d9d6bb1f1598' name 'OSXFUSE' homepage 'https://osxfuse.github.io/' license :bsd pkg "Extras/FUSE for macOS #{version}.pkg" postflight do set_ownership ['/usr/local/include', '/usr/local/lib'] end uninstall pkgutil: 'com.github.osxfuse.pkg.Core|com.github.osxfuse.pkg.PrefPane', kext: 'com.github.osxfuse.filesystems.osxfusefs' caveats do reboot end end
cask "pktriot" do version "0.11.2" sha256 "14ddacd77569abbb7f60db400b05b09c1c18734214a390d365276b630f7a1680" url "https://download.packetriot.com/macos/pktriot-#{version}.macos.tar.gz" name "pktriot" desc "Host server applications and static websites" homepage "https://packetriot.com/" livecheck do url "https://packetriot.com/downloads" strategy :page_match regex(/href=.*?pktriot[._-](\d+(?:\.\d+)*)\.macos\.t/i) end binary "pktriot-#{version}/pktriot" end Update pktriot from 0.11.2 to 0.12.0 (#113889) * Update pktriot from 0.11.2 to 0.12.0 * Update pktriot.rb Co-authored-by: Miccal Matthews <a53b0df86fcdccc56e90f3003dd9230c49f140c6@gmail.com> cask "pktriot" do version "0.12.0" sha256 "8b4b28bfa9f05db5857116709d20e52db9d89e3d99be69e651f9d1cddc63734f" url "https://download.packetriot.com/macos/pktriot-#{version}.macos.tar.gz" name "pktriot" desc "Host server applications and static websites" homepage "https://packetriot.com/" livecheck do url "https://packetriot.com/downloads" strategy :page_match regex(/href=.*?pktriot[._-](\d+(?:\.\d+)+)\.macos\.t/i) end binary "pktriot-#{version}/pktriot" end
cask "postbox" do version "7.0.40" sha256 "3b74c0afe6e0dc6e74e839d9e1731bb8e4a13b9ac43243e6b35937af7232a4e2" url "https://d3nx85trn0lqsg.cloudfront.net/mac/postbox-#{version}-mac64.dmg", verified: "d3nx85trn0lqsg.cloudfront.net/mac/" appcast "https://www.postbox-inc.com/download/success-mac" name "Postbox" desc "Email client focusing on privacy protection" homepage "https://www.postbox-inc.com/" auto_updates true depends_on macos: ">= :high_sierra" app "Postbox.app" zap trash: [ "~/Library/Application Support/Postbox", "~/Library/Application Support/PostboxApp", "~/Library/Caches/com.crashlytics.data/com.postbox-inc.postbox", "~/Library/Caches/com.postbox-inc.postbox", "~/Library/Caches/Postbox", "~/Library/Caches/PostboxApp", "~/Library/PDF Services/Mail PDF with Postbox", "~/Library/Preferences/com.postbox-inc.postbox.plist", "~/Library/Saved Application State/com.postbox-inc.postbox.savedState", ] end Update postbox from 7.0.40 to 7.0.42 (#95317) cask "postbox" do version "7.0.42" sha256 "80eb12534563d5a6379573d5e80cc35cc2e7d259e073a536f001816a6d92055b" url "https://d3nx85trn0lqsg.cloudfront.net/mac/postbox-#{version}-mac64.dmg", verified: "d3nx85trn0lqsg.cloudfront.net/mac/" appcast "https://www.postbox-inc.com/download/success-mac" name "Postbox" desc "Email client focusing on privacy protection" homepage "https://www.postbox-inc.com/" auto_updates true depends_on macos: ">= :high_sierra" app "Postbox.app" zap trash: [ "~/Library/Application Support/Postbox", "~/Library/Application Support/PostboxApp", "~/Library/Caches/com.crashlytics.data/com.postbox-inc.postbox", "~/Library/Caches/com.postbox-inc.postbox", "~/Library/Caches/Postbox", "~/Library/Caches/PostboxApp", "~/Library/PDF Services/Mail PDF with Postbox", "~/Library/Preferences/com.postbox-inc.postbox.plist", "~/Library/Saved Application State/com.postbox-inc.postbox.savedState", ] end
cask 'postbox' do version '5.0.4' sha256 '367b597f4b802034405e75efb33078c12e69428d8fbaafe45cd0a53e27f3b9a7' # amazonaws.com/download.getpostbox.com was verified as official when first introduced to the cask url "https://s3.amazonaws.com/download.getpostbox.com/installers/#{version}/1_6ba7710e4b30693e0770fd893492f752db8b7fc7/postbox-#{version}-mac64.dmg" name 'Postbox' homepage 'https://www.postbox-inc.com/' depends_on macos: '>= :mavericks' depends_on arch: :x86_64 app 'Postbox.app' zap delete: [ '~/Library/Application Support/Postbox', '~/Library/Caches/com.crashlytics.data/com.postbox-inc.postbox', '~/Library/Caches/com.postbox-inc.postbox', '~/Library/Caches/Postbox', '~/Library/PDF Services/Mail PDF with Postbox', '~/Library/Preferences/com.postbox-inc.postbox.plist', '~/Library/Saved Application State/com.postbox-inc.postbox.savedState', ] end Update postbox to 5.0.5 (#26007) cask 'postbox' do version '5.0.5' sha256 'b87f775fc40fc626980c468cfea9ef397529792e4b2e4d5eeac1a16aac637791' # amazonaws.com/download.getpostbox.com was verified as official when first introduced to the cask url "https://s3.amazonaws.com/download.getpostbox.com/installers/#{version}/1_348aedfb4d5afd22e43adecbddf15a86b9aedad3/postbox-#{version}-mac64.dmg" name 'Postbox' homepage 'https://www.postbox-inc.com/' depends_on macos: '>= :mavericks' depends_on arch: :x86_64 app 'Postbox.app' zap delete: [ '~/Library/Application Support/Postbox', '~/Library/Caches/com.crashlytics.data/com.postbox-inc.postbox', '~/Library/Caches/com.postbox-inc.postbox', '~/Library/Caches/Postbox', '~/Library/PDF Services/Mail PDF with Postbox', '~/Library/Preferences/com.postbox-inc.postbox.plist', '~/Library/Saved Application State/com.postbox-inc.postbox.savedState', ] end
cask 'prepros' do version '5.10.2' sha256 '45cdd9fb4b30cc2a26cdb211c713ef8c6f9ff3e9636131888ed796ae56262fa8' # prepros.io.s3.amazonaws.com was verified as official when first introduced to the cask url "http://prepros.io.s3.amazonaws.com/installers/Prepros-Mac-#{version}.zip" name 'Prepros' homepage 'https://prepros.io/' app 'Prepros.app' end Update prepros to 6.0.1 (#27356) cask 'prepros' do version '6.0.1' sha256 '9541c9561be11dfaebd5b682571a2e6f46edcc6186016ce9bdba6e16573834f1' # s3-us-west-2.amazonaws.com/prepros-io-releases was verified as official when first introduced to the cask url "https://s3-us-west-2.amazonaws.com/prepros-io-releases/stable/Prepros-Mac-#{version}.zip" appcast 'https://prepros.io/changelog', checkpoint: '1e4dfb8b73ea10880c0a158c5587368f07bc54f0f48e91770c096c1b5dbd0614' name 'Prepros' homepage 'https://prepros.io/' app 'Prepros.app' end
cask 'prepros' do version '6.0.10' sha256 'cfbc7062db0eb82080767af6123cc80b24d16089baaa2bc6f8d31e3ba5545243' # s3-us-west-2.amazonaws.com/prepros-io-releases was verified as official when first introduced to the cask url "https://s3-us-west-2.amazonaws.com/prepros-io-releases/stable/Prepros-Mac-#{version}.zip" appcast 'https://prepros.io/changelog', checkpoint: '340e8db2f8cde0fd689f92ebbb145699123252d98a0752f67197216a5dd54049' name 'Prepros' homepage 'https://prepros.io/' app 'Prepros.app' end Update prepros to 6.0.12 (#32869) cask 'prepros' do version '6.0.12' sha256 '2bd0335b895ebfd64f6cf9c0e5d136427f34b2819b2e3cc04b727ef9260fafdb' # s3-us-west-2.amazonaws.com/prepros-io-releases was verified as official when first introduced to the cask url "https://s3-us-west-2.amazonaws.com/prepros-io-releases/stable/Prepros-Mac-#{version}.zip" appcast 'https://prepros.io/changelog', checkpoint: '0e5734213f63c98a43bc53867ba8f4b329a10bc63724dae0aa8536b0649eadb8' name 'Prepros' homepage 'https://prepros.io/' app 'Prepros.app' end
cask 'pritunl' do version '1.0.2144.93' sha256 '846ecbfbed7e5ef48ad6595e75e2e0e1a3250c4ea08af0375ac98934083f06fc' # github.com/pritunl/pritunl-client-electron was verified as official when first introduced to the cask url "https://github.com/pritunl/pritunl-client-electron/releases/download/#{version}/Pritunl.pkg.zip" appcast 'https://github.com/pritunl/pritunl-client-electron/releases.atom' name 'Pritunl OpenVPN Client' homepage 'https://client.pritunl.com/' pkg 'Pritunl.pkg' uninstall pkgutil: 'com.pritunl.pkg.Pritunl', launchctl: [ 'com.pritunl.client', 'com.pritunl.service', ], signal: ['TERM', 'com.electron.pritunl'], delete: '/Applications/Pritunl.app' zap trash: [ '~/Library/Application Support/pritunl', '~/Library/Caches/pritunl', '~/Library/Preferences/com.electron.pritunl*', ] end Update pritunl from 1.0.2144.93 to 1.0.2207.23 (#69884) cask 'pritunl' do version '1.0.2207.23' sha256 '63a8dc1feeab551e6ea51ae26a74d250b603d18b861cdb3a82b261b0d0519536' # github.com/pritunl/pritunl-client-electron was verified as official when first introduced to the cask url "https://github.com/pritunl/pritunl-client-electron/releases/download/#{version}/Pritunl.pkg.zip" appcast 'https://github.com/pritunl/pritunl-client-electron/releases.atom' name 'Pritunl OpenVPN Client' homepage 'https://client.pritunl.com/' pkg 'Pritunl.pkg' uninstall pkgutil: 'com.pritunl.pkg.Pritunl', launchctl: [ 'com.pritunl.client', 'com.pritunl.service', ], signal: ['TERM', 'com.electron.pritunl'], delete: '/Applications/Pritunl.app' zap trash: [ '~/Library/Application Support/pritunl', '~/Library/Caches/pritunl', '~/Library/Preferences/com.electron.pritunl*', ] end
cask :v1 => 'propane' do version :latest sha256 :no_check url 'https://propaneapp.com/appcast/Propane.zip' appcast 'http://propaneapp.com/appcast/release.xml' homepage 'http://propaneapp.com/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'Propane.app' end propane.rb: added name cask :v1 => 'propane' do version :latest sha256 :no_check url 'https://propaneapp.com/appcast/Propane.zip' appcast 'http://propaneapp.com/appcast/release.xml' name 'Propane' homepage 'http://propaneapp.com/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'Propane.app' end
cask 'pycharm' do version '2017.1.3,171.4424.42' sha256 '88d336affb96ba9ca324fb991068ef52cff63ac35c4c0ffee617d86346a8452c' url "https://download.jetbrains.com/python/pycharm-professional-#{version.before_comma}.dmg" appcast 'https://data.services.jetbrains.com/products/releases?code=PCP&latest=true&type=release', checkpoint: '9b6d801ed3b6245b366f94b43b72d074cf782d5004c3eb5193906d651d8eafff' name 'PyCharm' homepage 'https://www.jetbrains.com/pycharm/' auto_updates true app 'PyCharm.app' uninstall_postflight do ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'charm') }.each { |path| File.delete(path) if File.exist?(path) } end zap delete: [ "~/Library/Preferences/PyCharm#{version.major_minor}", "~/Library/Application Support/PyCharm#{version.major_minor}", "~/Library/Caches/PyCharm#{version.major_minor}", "~/Library/Logs/PyCharm#{version.major_minor}", ] end Update pycharm to 2017.1.4,171.4694.38 (#35592) cask 'pycharm' do version '2017.1.4,171.4694.38' sha256 '71fcb0393a974d06d73beddd178de31d38ea70dccd0b5670a1bac1730cdd8433' url "https://download.jetbrains.com/python/pycharm-professional-#{version.before_comma}.dmg" appcast 'https://data.services.jetbrains.com/products/releases?code=PCP&latest=true&type=release', checkpoint: '18c1e8e50711940e2bf8abb9916c857238575fc63fb3c8f86e8beefa1009bcad' name 'PyCharm' homepage 'https://www.jetbrains.com/pycharm/' auto_updates true app 'PyCharm.app' uninstall_postflight do ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'charm') }.each { |path| File.delete(path) if File.exist?(path) } end zap delete: [ "~/Library/Preferences/PyCharm#{version.major_minor}", "~/Library/Application Support/PyCharm#{version.major_minor}", "~/Library/Caches/PyCharm#{version.major_minor}", "~/Library/Logs/PyCharm#{version.major_minor}", ] end
cask :v1 => 'pycharm' do version '4.0.6' sha256 '6143a1262ce8441ee8b99ca39b808ad4ca06f2b5f359f0627043c0519a900399' url "https://download.jetbrains.com/python/pycharm-professional-#{version}.dmg" name 'PyCharm' homepage 'http://www.jetbrains.com/pycharm/' license :commercial app 'PyCharm.app' caveats <<-EOS.undent #{token} requires Java 6 like any other IntelliJ-based IDE. You can install it with brew cask install caskroom/homebrew-versions/java6 The vendor (JetBrains) doesn't support newer versions of Java (yet) due to several critical issues, see details at https://intellij-support.jetbrains.com/entries/27854363 EOS end update pycharm to version 4.5 cask :v1 => 'pycharm' do version '4.5' sha256 '96f97b5d031bdb509d300528aa79e60774fc8b2ec1e88800324095babb4902c9' url "https://download.jetbrains.com/python/pycharm-professional-#{version}.dmg" name 'PyCharm' homepage 'http://www.jetbrains.com/pycharm/' license :commercial app 'PyCharm.app' caveats <<-EOS.undent #{token} requires Java 6 like any other IntelliJ-based IDE. You can install it with brew cask install caskroom/homebrew-versions/java6 The vendor (JetBrains) doesn't support newer versions of Java (yet) due to several critical issues, see details at https://intellij-support.jetbrains.com/entries/27854363 EOS end
# encoding: UTF-8 class Qqmusic < Cask version '1.3.0' sha256 '2f1198f9b3e1407822a771fcdfdd643b65f35f6b51cc0af8c6b11fa11fc30a0d' url 'http://dldir1.qq.com/music/clntupate/QQMusicForMacV1.3.0.dmg' homepage 'http://y.qq.com' app 'QQ音乐.app' end re-use version in qqmusic # encoding: UTF-8 class Qqmusic < Cask version '1.3.0' sha256 '2f1198f9b3e1407822a771fcdfdd643b65f35f6b51cc0af8c6b11fa11fc30a0d' url "http://dldir1.qq.com/music/clntupate/QQMusicForMacV#{version}.dmg" homepage 'http://y.qq.com' app 'QQ音乐.app' end
cask 'quicken' do version '5.10.0,510.25424.100' sha256 '1ee31b2566b0d11f6d85ed95894c32b72d0d5ffc2d1487fca07340b7cfc47f7b' url "https://download.quicken.com/mac/Quicken/001/Release/031A96D9-EFE6-4520-8B6A-7F465DDAA3E4/Quicken-#{version.after_comma}/Quicken-#{version.after_comma}.zip" appcast 'https://download.quicken.com/mac/Quicken/001/Release/031A96D9-EFE6-4520-8B6A-7F465DDAA3E4/appcast.xml' name 'Quicken' homepage 'https://www.quicken.com/mac' depends_on macos: '>= :el_capitan' app 'Quicken.app' zap trash: [ '~/Library/Preferences/com.quicken.Quicken.plist', '~/Library/Application Support/Quicken', ] end Update quicken to 5.10.1,510.25438.100 (#58245) cask 'quicken' do version '5.10.1,510.25438.100' sha256 '8e6685692e50b1c9408ebfd6ea3f0be79a1cce1b04502b8a31a461deaa9c4402' url "https://download.quicken.com/mac/Quicken/001/Release/031A96D9-EFE6-4520-8B6A-7F465DDAA3E4/Quicken-#{version.after_comma}/Quicken-#{version.after_comma}.zip" appcast 'https://download.quicken.com/mac/Quicken/001/Release/031A96D9-EFE6-4520-8B6A-7F465DDAA3E4/appcast.xml' name 'Quicken' homepage 'https://www.quicken.com/mac' depends_on macos: '>= :el_capitan' app 'Quicken.app' zap trash: [ '~/Library/Preferences/com.quicken.Quicken.plist', '~/Library/Application Support/Quicken', ] end
cask 'quitter' do version '1.0,107' sha256 'ad4071a48aeed019fbb9ebf80ce717c1c15ade24298a33e823dc0d1c218baed4' url 'https://marco.org/appcasts/Quitter.zip' appcast 'https://marco.org/appcasts/quitter.xml' name 'Quitter' homepage 'https://marco.org/apps#quitter' auto_updates true app 'Quitter.app' zap trash: [ '~/Library/Preferences/com.marcoarment.quitter.plist', '~/Library/Caches/com.marcoarment.quitter', '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.marcoarment.quitter.sfl*', ] end quitter: fix RuboCop style. See https://github.com/Homebrew/brew/pull/7867. cask "quitter" do version "1.0,107" sha256 "ad4071a48aeed019fbb9ebf80ce717c1c15ade24298a33e823dc0d1c218baed4" url "https://marco.org/appcasts/Quitter.zip" appcast "https://marco.org/appcasts/quitter.xml" name "Quitter" homepage "https://marco.org/apps#quitter" auto_updates true app "Quitter.app" zap trash: [ "~/Library/Preferences/com.marcoarment.quitter.plist", "~/Library/Caches/com.marcoarment.quitter", "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.marcoarment.quitter.sfl*", ] end
cask 'qz-tray' do version '2.0.4' sha256 '8f58eb7eef7670e1e930b02c0218e76fb5209e3b79d1502ef2e84302b88dc114' # github.com/qzind/tray was verified as official when first introduced to the cask url "https://github.com/qzind/tray/releases/download/v#{version}/qz-tray-#{version}.pkg" appcast 'https://github.com/qzind/tray/releases.atom', checkpoint: '5fab370b4376f9aebd6c8b2d519564d057be8495708d33f4964c5b9773090b83' name 'QZ Tray' homepage 'https://qz.io/' container type: :naked app 'QZ Tray.app' preflight do # app needs to be extracted as the installer would automatically open it FileUtils.cd staged_path do FileUtils.mkdir_p 'QZ Tray.app' system_command '/usr/bin/xar', args: ['-xf', "qz-tray-#{version}.pkg", 'Payload'] system_command '/usr/bin/tar', args: ['-xf', 'Payload', '-C', 'QZ Tray.app'] FileUtils.rm_rf ["qz-tray-#{version}.pkg", 'Payload'] end end uninstall login_item: 'QZ Tray' zap trash: [ '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/:no-bundle:qz t.sfl*', '~/Library/Application Support/qz', ] end Update qz-tray to 2.0.4-1 (#41023) cask 'qz-tray' do version '2.0.4-1' sha256 'f388fa0d696ad90cdcdd9a7e81bff2a8755f3f2817dc171763e2e26f0e6d404c' # github.com/qzind/tray was verified as official when first introduced to the cask url "https://github.com/qzind/tray/releases/download/v#{version.sub('-1', '')}/qz-tray-#{version}.pkg" appcast 'https://github.com/qzind/tray/releases.atom', checkpoint: '991f92c10fd6208642d8f21e6947687a02f2e8a69d1ddbca7a3fa77220cfa73d' name 'QZ Tray' homepage 'https://qz.io/' container type: :naked app 'QZ Tray.app' preflight do # app needs to be extracted as the installer would automatically open it FileUtils.cd staged_path do FileUtils.mkdir_p 'QZ Tray.app' system_command '/usr/bin/xar', args: ['-xf', "qz-tray-#{version}.pkg", 'Payload'] system_command '/usr/bin/tar', args: ['-xf', 'Payload', '-C', 'QZ Tray.app'] FileUtils.rm_rf ["qz-tray-#{version}.pkg", 'Payload'] end end uninstall login_item: 'QZ Tray' zap trash: [ '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/:no-bundle:qz t.sfl*', '~/Library/Application Support/qz', ] end
cask :v1 => 'rbtools' do version '0.7.1' sha256 '6e2ffc0ea6d095f45662a51d03a9cf8e088c4dbca25e8ca261de2a1388fe53b0' url "https://downloads.reviewboard.org/releases/RBTools/#{version.sub(%r{\.\d+$},'')}/RBTools-#{version}.pkg" name 'RBTools' homepage 'https://www.reviewboard.org/docs/rbtools/dev/' license :mit pkg "RBTools-#{version}.pkg" uninstall :pkgutil => 'org.reviewboard.rbtools' end Upgrade RBTools to 0.7.2 cask :v1 => 'rbtools' do version '0.7.2' sha256 '78a0ee38431e07d16adce9ba06481295eb4d789bbb0975ec439fba59ee42b063' url "https://downloads.reviewboard.org/releases/RBTools/#{version.sub(%r{\.\d+$},'')}/RBTools-#{version}.pkg" name 'RBTools' homepage 'https://www.reviewboard.org/docs/rbtools/dev/' license :mit pkg "RBTools-#{version}.pkg" uninstall :pkgutil => 'org.reviewboard.rbtools' end
cask "robo-3t" do version "1.4.2,8650949" sha256 "de91074f726f03976bad5c64c73acfc16ecceb7f50868916cb1058d0fc965085" url "https://download.studio3t.com/robomongo/mac/robo3t-#{version.before_comma}-darwin-x86_64-#{version.after_comma}.dmg", verified: "download.studio3t.com/" appcast "https://github.com/Studio3T/robomongo/releases.atom" name "Robo 3T (formerly Robomongo)" desc "MongoDB management tool (formerly Robomongo)" homepage "https://robomongo.org/" app "Robo 3T.app" uninstall quit: "Robo 3T" zap trash: [ "~/.3T/robo-3t/", "~/Library/Saved Application State/Robo 3T.savedState", ] end robo-3t: add livecheck (#97458) cask "robo-3t" do version "1.4.2,8650949" sha256 "de91074f726f03976bad5c64c73acfc16ecceb7f50868916cb1058d0fc965085" url "https://download.studio3t.com/robomongo/mac/robo3t-#{version.before_comma}-darwin-x86_64-#{version.after_comma}.dmg", verified: "download.studio3t.com/" name "Robo 3T (formerly Robomongo)" desc "MongoDB management tool" homepage "https://robomongo.org/" # We need to check all releases since the current latest release is a beta version. livecheck do url "https://github.com/Studio3T/robomongo/releases" strategy :page_match do |page| match = page.match(%r{href=.*?/v?(\d+(?:\.\d+)*)/robo3t-\1-darwin-x86_64-([0-9a-f]+)\.dmg}i) "#{match[1]},#{match[2]}" end end app "Robo 3T.app" uninstall quit: "Robo 3T" zap trash: [ "~/.3T/robo-3t/", "~/Library/Saved Application State/Robo 3T.savedState", ] end
cask 'screens' do version '4.6.7' sha256 '5ecb4f65a3a2883a8537b4787e5442489d57184f60c460c22709115df8a5c2c6' # dl.devmate.com/com.edovia.screens4.mac was verified as official when first introduced to the cask url 'https://dl.devmate.com/com.edovia.screens4.mac/Screens4.dmg' appcast "https://updates.devmate.com/com.edovia.screens#{version.major}.mac.xml" name 'Screens' homepage 'https://edovia.com/screens-mac/' auto_updates true depends_on macos: '>= :sierra' app "Screens #{version.major}.app" uninstall launchctl: 'com.edovia.screens.launcher', quit: "com.edovia.screens#{version.major}.mac" zap trash: [ "~/Library/Application Scripts/com.edovia.screens#{version.major}.mac", '~/Library/Application Scripts/com.edovia.screens.launcher', "~/Library/Containers/com.edovia.screens#{version.major}.mac", '~/Library/Containers/com.edovia.screens.launcher', '~/Library/Logs/Screens', ] end update screens to 4.6.8 (#60566) cask 'screens' do version '4.6.8' sha256 '41816d4e6341ae4df18deaa70e9c89c97d6bc8a5f083bdcc71176229cce4603f' # dl.devmate.com/com.edovia.screens4.mac was verified as official when first introduced to the cask url 'https://dl.devmate.com/com.edovia.screens4.mac/Screens4.dmg' appcast "https://updates.devmate.com/com.edovia.screens#{version.major}.mac.xml" name 'Screens' homepage 'https://edovia.com/screens-mac/' auto_updates true depends_on macos: '>= :sierra' app "Screens #{version.major}.app" uninstall launchctl: 'com.edovia.screens.launcher', quit: "com.edovia.screens#{version.major}.mac" zap trash: [ "~/Library/Application Scripts/com.edovia.screens#{version.major}.mac", '~/Library/Application Scripts/com.edovia.screens.launcher', "~/Library/Containers/com.edovia.screens#{version.major}.mac", '~/Library/Containers/com.edovia.screens.launcher', '~/Library/Logs/Screens', ] end
cask 'screens' do version '4.0,7752' sha256 '0c7133bfc64cbd764097e1d8a82d0fbcfe4da445db4860e95540d9a43766ddef' # dl.devmate.com was verified as official when first introduced to the cask url "https://dl.devmate.com/com.edovia.screens4.mac/Screens#{version.major}.dmg" appcast "https://updates.devmate.com/com.edovia.screens#{version.major}.mac.xml", checkpoint: 'efa3b709d252eb5a3a763dcfc21ee79d9c031f0278844700d9e878a6c77528dc' name 'Screens' homepage 'https://edovia.com/screens-mac/' app "Screens #{version.major}.app" uninstall launchctl: 'com.edovia.screens.launcher', quit: "com.edovia.screens#{version.major}.mac" zap delete: [ "~/Library/Application Scripts/com.edovia.screens#{version.major}.mac", "~/Library/Containers/com.edovia.screens#{version.major}.mac", '~/Library/Logs/Screens', ] end Update screens to 4.0.1,7824 (#34928) cask 'screens' do version '4.0.1,7824' sha256 'a5e1d3b0a199516ba4abdfa2589e93b558799937eba28f090654464e0d2f286a' # dl.devmate.com was verified as official when first introduced to the cask url "https://dl.devmate.com/com.edovia.screens4.mac/Screens#{version.major}.dmg" appcast "https://updates.devmate.com/com.edovia.screens#{version.major}.mac.xml", checkpoint: '3999c3335ce2eefca667a39a2054a144e58e2b0887bff64aa92c045e8f84e449' name 'Screens' homepage 'https://edovia.com/screens-mac/' app "Screens #{version.major}.app" uninstall launchctl: 'com.edovia.screens.launcher', quit: "com.edovia.screens#{version.major}.mac" zap delete: [ "~/Library/Application Scripts/com.edovia.screens#{version.major}.mac", "~/Library/Containers/com.edovia.screens#{version.major}.mac", '~/Library/Logs/Screens', ] end
cask "session" do version "1.6.11" sha256 "15badec18a6530406fe83d4a69788dac7b1b36a646769bf5361cb0d9f4e7bbc6" url "https://github.com/loki-project/session-desktop/releases/download/v#{version}/session-desktop-mac-#{version}.dmg", verified: "github.com/loki-project/session-desktop/" name "Session" desc "Onion routing based messenger" homepage "https://getsession.org/" livecheck do url :url strategy :github_latest end app "Session.app" zap trash: [ "~/Library/Application Support/Session", "~/Library/Caches/Session", "~/Library/Preferences/com.loki-project.messenger-desktop.plist", "~/Library/Saved Application State/com.loki-project.messenger-desktop.savedState", ] end Update session from 1.6.11 to 1.7.0 (#111046) cask "session" do version "1.7.0" sha256 "2336b64c5c744568dcb1fc9fc8d822d9ecce4bc492f6cf0517e28267afddcf56" url "https://github.com/loki-project/session-desktop/releases/download/v#{version}/session-desktop-mac-#{version}.dmg", verified: "github.com/loki-project/session-desktop/" name "Session" desc "Onion routing based messenger" homepage "https://getsession.org/" livecheck do url :url strategy :github_latest end app "Session.app" zap trash: [ "~/Library/Application Support/Session", "~/Library/Caches/Session", "~/Library/Preferences/com.loki-project.messenger-desktop.plist", "~/Library/Saved Application State/com.loki-project.messenger-desktop.savedState", ] end
cask "shotcut" do version "20.09.27" sha256 "9cd5eebc09d0ac8c6be834fbba920efe0b8ee05621757a1301e736a384b20650" # github.com/mltframework/shotcut/ was verified as official when first introduced to the cask url "https://github.com/mltframework/shotcut/releases/download/v#{version}/shotcut-macos-signed-#{version.no_dots}.dmg" appcast "https://github.com/mltframework/shotcut/releases.atom" name "Shotcut" desc "Cross-platform and open-source video editor" homepage "https://www.shotcut.org/" app "Shotcut.app" end Update shotcut from 20.09.27 to 20.10.31 (#91891) cask "shotcut" do version "20.10.31" sha256 "02961587e120a7f448816633437ce3dfd2314f9b104f022558333dc7c28ea7f2" # github.com/mltframework/shotcut/ was verified as official when first introduced to the cask url "https://github.com/mltframework/shotcut/releases/download/v#{version}/shotcut-macos-signed-#{version.no_dots}.dmg" appcast "https://github.com/mltframework/shotcut/releases.atom" name "Shotcut" desc "Cross-platform and open-source video editor" homepage "https://www.shotcut.org/" app "Shotcut.app" end
cask "shotcut" do version "20.11.28" sha256 "a2d72ff4302ef5d08b379d605907dc061ed10c53a6478458c2098be0712456cc" # github.com/mltframework/shotcut/ was verified as official when first introduced to the cask url "https://github.com/mltframework/shotcut/releases/download/v#{version}/shotcut-macos-signed-#{version.no_dots}.dmg" appcast "https://github.com/mltframework/shotcut/releases.atom" name "Shotcut" desc "Cross-platform and open-source video editor" homepage "https://www.shotcut.org/" app "Shotcut.app" end shotcut.rb: add verified comment (#94162) cask "shotcut" do version "20.11.28" sha256 "a2d72ff4302ef5d08b379d605907dc061ed10c53a6478458c2098be0712456cc" url "https://github.com/mltframework/shotcut/releases/download/v#{version}/shotcut-macos-signed-#{version.no_dots}.dmg", verified: "github.com/mltframework/shotcut/" appcast "https://github.com/mltframework/shotcut/releases.atom" name "Shotcut" desc "Cross-platform and open-source video editor" homepage "https://www.shotcut.org/" app "Shotcut.app" end
cask :v1 => 'smaller' do version :latest sha256 :no_check url 'http://smallerapp.com/download/Smaller.zip' appcast 'http://smallerapp.com/up/updates.xml' homepage 'http://smallerapp.com/' license :unknown # todo: improve this machine-generated value app 'Smaller.app' end smaller.rb: change ':unknown' license comment cask :v1 => 'smaller' do version :latest sha256 :no_check url 'http://smallerapp.com/download/Smaller.zip' appcast 'http://smallerapp.com/up/updates.xml' homepage 'http://smallerapp.com/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'Smaller.app' end
cask "spotify" do arch = Hardware::CPU.intel? ? "" : "ARM64" version "1.1.89.862,94554d24,16" sha256 :no_check url "https://download.scdn.co/Spotify#{arch}.dmg", verified: "download.scdn.co/" name "Spotify" desc "Music streaming service" homepage "https://www.spotify.com/" livecheck do url :url strategy :extract_plist do |items| match = items["com.spotify.client"].version.match(/^(\d+(?:\.\d+)+)[._-]g(\h+)[._-](\d+)$/i) next if match.blank? "#{match[1]},#{match[2]},#{match[3]}" end end auto_updates true depends_on macos: ">= :el_capitan" app "Spotify.app" uninstall quit: "com.spotify.client", launchctl: "com.spotify.webhelper" zap trash: [ "~/Library/Application Support/Spotify", "~/Library/Caches/com.spotify.client.helper", "~/Library/Caches/com.spotify.client", "~/Library/Cookies/com.spotify.client.binarycookies", "~/Library/HTTPStorages/com.spotify.client", "~/Library/Logs/Spotify", "~/Library/Preferences/com.spotify.client.helper.plist", "~/Library/Preferences/com.spotify.client.plist", "~/Library/Saved Application State/com.spotify.client.savedState", ] end spotify 1.1.90.859,f1bb1e36,15 Update spotify from 1.1.89.862 to 1.1.90.859 Closes #128421. Signed-off-by: Sean Molenaar <2b250e3fea88cfef248b497ad5fc17f7dc435154@users.noreply.github.com> Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com> cask "spotify" do arch = Hardware::CPU.intel? ? "" : "ARM64" version "1.1.90.859,f1bb1e36,15" sha256 :no_check url "https://download.scdn.co/Spotify#{arch}.dmg", verified: "download.scdn.co/" name "Spotify" desc "Music streaming service" homepage "https://www.spotify.com/" livecheck do url :url strategy :extract_plist do |items| match = items["com.spotify.client"].version.match(/^(\d+(?:\.\d+)+)[._-]g(\h+)[._-](\d+)$/i) next if match.blank? "#{match[1]},#{match[2]},#{match[3]}" end end auto_updates true depends_on macos: ">= :el_capitan" app "Spotify.app" uninstall quit: "com.spotify.client", launchctl: "com.spotify.webhelper" zap trash: [ "~/Library/Application Support/Spotify", "~/Library/Caches/com.spotify.client.helper", "~/Library/Caches/com.spotify.client", "~/Library/Cookies/com.spotify.client.binarycookies", "~/Library/HTTPStorages/com.spotify.client", "~/Library/Logs/Spotify", "~/Library/Preferences/com.spotify.client.helper.plist", "~/Library/Preferences/com.spotify.client.plist", "~/Library/Saved Application State/com.spotify.client.savedState", ] end
cask 'station' do version '1.1.1' sha256 'ebdd38da79ff121066bc3413e50ce4d24c45d0b840d6c22d4c56aadf5ba7f607' # github.com/getstation/desktop-app-releases was verified as official when first introduced to the cask url "https://github.com/getstation/desktop-app-releases/releases/download/#{version}/Station-#{version}-mac.zip" appcast 'https://github.com/getstation/desktop-app-releases/releases.atom', checkpoint: 'be5d0dcda0edcc10f8cba2d31d0a885f91196025cfa706ed3e84ac1b734aaa09' name 'Station' homepage 'https://getstation.com/' auto_updates true app 'Station.app' uninstall quit: [ 'org.efounders.BrowserX', 'org.efounders.BrowserX.helper', ] zap trash: '~/Library/Application Support/Station/' end Update station to 1.2.0 (#43183) cask 'station' do version '1.2.0' sha256 'e2439392c919855f1c5fbf7c72de2a3e59e8f1f3f587ee161a6360b3f5d1b575' # github.com/getstation/desktop-app-releases was verified as official when first introduced to the cask url "https://github.com/getstation/desktop-app-releases/releases/download/#{version}/Station-#{version}-mac.zip" appcast 'https://github.com/getstation/desktop-app-releases/releases.atom', checkpoint: '95c9a5da3826ddf2eeb0fe5ee9425851fed4b34f9c9545d0100e1be5afef1aca' name 'Station' homepage 'https://getstation.com/' auto_updates true app 'Station.app' uninstall quit: [ 'org.efounders.BrowserX', 'org.efounders.BrowserX.helper', ] zap trash: '~/Library/Application Support/Station/' end
cask "texshop" do version "4.63" sha256 "fad207790bfbeaf68456e347b7e22453f898929d88d54b095e63c1b4ab1940ab" url "https://pages.uoregon.edu/koch/texshop/texshop-64/texshop#{version.no_dots}.zip" name "TeXShop" desc "TeX previewer" homepage "https://pages.uoregon.edu/koch/texshop/" livecheck do url "https://pages.uoregon.edu/koch/texshop/texshop-64/texshopappcast.xml" strategy :sparkle end auto_updates true depends_on macos: ">= :sierra" app "TeXShop.app" zap trash: [ "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/texshop.sfl*", "~/Library/Application Support/TeXShop", "~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/TeXShop Help*", "~/Library/Caches/TeXShop", "~/Library/Preferences/TeXShop.plist", "~/Library/TeXShop", ] end Update texshop from 4.63 to 4.63 (#104503) cask "texshop" do version "4.63" sha256 "df0699415fe4bf93463ac3029f39d1ce96d449b087bb5886559ff4580a992c53" url "https://pages.uoregon.edu/koch/texshop/texshop-64/texshop#{version.no_dots}.zip" name "TeXShop" desc "TeX previewer" homepage "https://pages.uoregon.edu/koch/texshop/" livecheck do url "https://pages.uoregon.edu/koch/texshop/texshop-64/texshopappcast.xml" strategy :sparkle end auto_updates true depends_on macos: ">= :sierra" app "TeXShop.app" zap trash: [ "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/texshop.sfl*", "~/Library/Application Support/TeXShop", "~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/TeXShop Help*", "~/Library/Caches/TeXShop", "~/Library/Preferences/TeXShop.plist", "~/Library/TeXShop", ] end
cask 'texshop' do version '3.95' sha256 '8385b2dc0f0be70fc48d8e222bea0b5585a26f107db0e892b3ad1ef2b562980a' url "http://pages.uoregon.edu/koch/texshop/texshop-64/texshop#{version.no_dots}.zip" appcast 'http://pages.uoregon.edu/koch/texshop/texshop-64/texshopappcast.xml', checkpoint: '84050f3e7267d313fd876a8d32d91d4c9f2aad152a8e13feda3c203731de5fb8' name 'TeXShop' homepage 'http://pages.uoregon.edu/koch/texshop/' auto_updates true depends_on macos: '>= :yosemite' app 'TeXShop.app' zap trash: [ '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/texshop.sfl*', '~/Library/Application Support/TeXShop', '~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/TeXShop Help*', '~/Library/Caches/TeXShop', '~/Library/Preferences/TeXShop.plist', '~/Library/TeXShop', ] end Update texshop to 3.96 (#42559) cask 'texshop' do version '3.96' sha256 '56dc6e008fdc39d79793397c0852cf61714f0abb15e38144048882b9725ee23b' url "http://pages.uoregon.edu/koch/texshop/texshop-64/texshop#{version.no_dots}.zip" appcast 'http://pages.uoregon.edu/koch/texshop/texshop-64/texshopappcast.xml', checkpoint: '4b16e23ddfb7385682c2f5d39a09f7c82a9c13b48f32fc538777921df455b2a1' name 'TeXShop' homepage 'http://pages.uoregon.edu/koch/texshop/' auto_updates true depends_on macos: '>= :yosemite' app 'TeXShop.app' zap trash: [ '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/texshop.sfl*', '~/Library/Application Support/TeXShop', '~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/TeXShop Help*', '~/Library/Caches/TeXShop', '~/Library/Preferences/TeXShop.plist', '~/Library/TeXShop', ] end
class Tickets < Cask url 'http://www.irradiatedsoftware.com/download/Tickets.zip' appcast 'http://www.irradiatedsoftware.com/updates/profiles/tickets.php' homepage 'http://www.irradiatedsoftware.com/tickets/' version '2.5' sha256 '8f2d7879581fb2604158367fb6e7eda8bc9ebf15e97781b69b64355f2832af6e' link 'Tickets.app' end use HTTPS url in tickets.rb class Tickets < Cask url 'https://www.irradiatedsoftware.com/download/Tickets.zip' appcast 'http://www.irradiatedsoftware.com/updates/profiles/tickets.php' homepage 'http://www.irradiatedsoftware.com/tickets/' version '2.5' sha256 '8f2d7879581fb2604158367fb6e7eda8bc9ebf15e97781b69b64355f2832af6e' link 'Tickets.app' end
cask 'timings' do version '3.1.2' sha256 '90f7ad5291f7aa5d5d28511be3fc883e5ce7d1efef204dba0c6038b6195a67f2' url "https://mediaatelier.com/Timings#{version.major}/Timings_#{version}.zip" appcast "https://mediaatelier.com/Timings#{version.major}/feed.php", checkpoint: '151ec23863a69095bf136d81d32a2911d25fcb01111cec4b6e4fbaaeb16c4f50' name 'Timings' homepage 'https://www.mediaatelier.com/Timings3/' depends_on macos: '>= :mavericks' app 'Timings.app' zap trash: [ '~/Library/Preferences/com.mediaateller.Timings.plist', '~/Library/Application Support/Timings', '~/Library/Caches/com.mediaateller.timings', ] end Update timings to 3.2.1 cask 'timings' do version '3.2.1' sha256 '383a46f6610843bd2d0492214f79111662e25767ca800a79e65f02b72b9904a0' url "https://mediaatelier.com/Timings#{version.major}/Timings_#{version}.zip" appcast "https://mediaatelier.com/Timings#{version.major}/feed.php", checkpoint: '7630185bb7d021568437dc4c35ae01ab4afd1dc812432db315772f11384148b4' name 'Timings' homepage 'https://www.mediaatelier.com/Timings3/' depends_on macos: '>= :mavericks' app 'Timings.app' zap trash: [ '~/Library/Preferences/com.mediaateller.Timings.plist', '~/Library/Application Support/Timings', '~/Library/Caches/com.mediaateller.timings', ] end
cask 'vagrant' do version '2.2.8' sha256 '9a0a2bb306a1844bdee9f7d7f4f4f6d0229d5e095158ebf564937aa0b979f230' # hashicorp.com/vagrant/ was verified as official when first introduced to the cask url "https://releases.hashicorp.com/vagrant/#{version}/vagrant_#{version}_x86_64.dmg" appcast 'https://github.com/hashicorp/vagrant/releases.atom' name 'Vagrant' homepage 'https://www.vagrantup.com/' pkg 'vagrant.pkg' uninstall script: { executable: 'uninstall.tool', input: ['Yes'], sudo: true, }, pkgutil: 'com.vagrant.vagrant' zap trash: '~/.vagrant.d' end Update vagrant from 2.2.8 to 2.2.9 (#82185) cask 'vagrant' do version '2.2.9' sha256 '529cde2a78e6df38ec906b65c70b36a087e2601eab42e25856e35b20ccb027c0' # hashicorp.com/vagrant/ was verified as official when first introduced to the cask url "https://releases.hashicorp.com/vagrant/#{version}/vagrant_#{version}_x86_64.dmg" appcast 'https://github.com/hashicorp/vagrant/releases.atom' name 'Vagrant' homepage 'https://www.vagrantup.com/' pkg 'vagrant.pkg' uninstall script: { executable: 'uninstall.tool', input: ['Yes'], sudo: true, }, pkgutil: 'com.vagrant.vagrant' zap trash: '~/.vagrant.d' end
cask 'vivaldi' do version '2.2.1388.34' sha256 'f5c45c999913b5f08a303ed8e7207a75e02edfdac9c11d5a41ed291c0d1d40a9' url "https://downloads.vivaldi.com/stable/Vivaldi.#{version}.dmg" appcast 'https://update.vivaldi.com/update/1.0/public/mac/appcast.xml' name 'Vivaldi' homepage 'https://vivaldi.com/' auto_updates true app 'Vivaldi.app' zap trash: [ '~/Library/Application Support/Vivaldi', '~/Library/Caches/Vivaldi', '~/Library/Caches/com.vivaldi.Vivaldi', '~/Library/Preferences/com.vivaldi.Vivaldi.plist', '~/Library/Saved Application State/com.vivaldi.Vivaldi.savedState', ] end Update vivaldi to 2.2.1388.37 (#56381) cask 'vivaldi' do version '2.2.1388.37' sha256 '27ef51dfb38c2a8822d337a821a3a493c5c846e4b5f336a0ffd71aeadd957e71' url "https://downloads.vivaldi.com/stable/Vivaldi.#{version}.dmg" appcast 'https://update.vivaldi.com/update/1.0/public/mac/appcast.xml' name 'Vivaldi' homepage 'https://vivaldi.com/' auto_updates true app 'Vivaldi.app' zap trash: [ '~/Library/Application Support/Vivaldi', '~/Library/Caches/Vivaldi', '~/Library/Caches/com.vivaldi.Vivaldi', '~/Library/Preferences/com.vivaldi.Vivaldi.plist', '~/Library/Saved Application State/com.vivaldi.Vivaldi.savedState', ] end
cask 'vivaldi' do version '1.9.818.50' sha256 '600d3a50ab462552f67e8fb44f5e5e833c73cf0b7efb16da4c3e9bcba754b37f' url "https://downloads.vivaldi.com/stable/Vivaldi.#{version}.dmg" appcast 'https://update.vivaldi.com/update/1.0/mac/appcast.xml', checkpoint: 'dc48175d5d62efbbec9fa297e50788343de90a6d80750f924bd91b2985f3c08e' name 'Vivaldi' homepage 'https://vivaldi.com/' auto_updates true app 'Vivaldi.app' zap delete: [ '~/Library/Preferences/com.vivaldi.Vivaldi.plist', '~/Library/Application Support/Vivaldi', '~/Library/Caches/Vivaldi', '~/Library/Caches/com.vivaldi.Vivaldi', '~/Library/Saved Application State/com.vivaldi.Vivaldi.savedState', ] end Update vivaldi to 1.10.867.38 (#35559) cask 'vivaldi' do version '1.10.867.38' sha256 '3e325818e47a9ce7a4404b32bca42926cf140fe65427c5eb4b6c11ac5d4dfab1' url "https://downloads.vivaldi.com/stable/Vivaldi.#{version}.dmg" appcast 'https://update.vivaldi.com/update/1.0/mac/appcast.xml', checkpoint: '61c3b59db9959dfdb526ddb58ad36538899f45ecb38c1c3cad9cdb2a23775f67' name 'Vivaldi' homepage 'https://vivaldi.com/' auto_updates true app 'Vivaldi.app' zap delete: [ '~/Library/Preferences/com.vivaldi.Vivaldi.plist', '~/Library/Application Support/Vivaldi', '~/Library/Caches/Vivaldi', '~/Library/Caches/com.vivaldi.Vivaldi', '~/Library/Saved Application State/com.vivaldi.Vivaldi.savedState', ] end
cask 'vivaldi' do version '1.14.1077.50' sha256 'a270601cdb85c3c382c4f766fd75d1cb8184a9b8364c7c1fba65247bbb2373e3' url "https://downloads.vivaldi.com/stable/Vivaldi.#{version}.dmg" appcast 'https://update.vivaldi.com/update/1.0/public/mac/appcast.xml', checkpoint: '229b5ca4976f7c50070b6d0a86e448cc6830b555f0790266afcd9ad7f27b69b5' name 'Vivaldi' homepage 'https://vivaldi.com/' auto_updates true app 'Vivaldi.app' zap trash: [ '~/Library/Application Support/Vivaldi', '~/Library/Caches/Vivaldi', '~/Library/Caches/com.vivaldi.Vivaldi', '~/Library/Preferences/com.vivaldi.Vivaldi.plist', '~/Library/Saved Application State/com.vivaldi.Vivaldi.savedState', ] end Update vivaldi to 1.14.1077.55 (#44426) cask 'vivaldi' do version '1.14.1077.55' sha256 '260fe2965f747a3530b1a8b9548e779b1d8c8121f3ba3a65d53ec1cbba305444' url "https://downloads.vivaldi.com/stable/Vivaldi.#{version}.dmg" appcast 'https://update.vivaldi.com/update/1.0/public/mac/appcast.xml', checkpoint: 'e662f29f7bfc2d8e5941149794a3786ec3998ab330fbc83a9484df6fa118af5e' name 'Vivaldi' homepage 'https://vivaldi.com/' auto_updates true app 'Vivaldi.app' zap trash: [ '~/Library/Application Support/Vivaldi', '~/Library/Caches/Vivaldi', '~/Library/Caches/com.vivaldi.Vivaldi', '~/Library/Preferences/com.vivaldi.Vivaldi.plist', '~/Library/Saved Application State/com.vivaldi.Vivaldi.savedState', ] end
cask 'vuescan' do version '9.6.34' sha256 :no_check # required as upstream package is updated in-place url "https://www.hamrick.com/files/vuex64#{version.major_minor.no_dots}.dmg" appcast 'https://www.hamrick.com/alternate-versions.html' name 'VueScan' homepage 'https://www.hamrick.com/' app 'VueScan.app' end Update vuescan to 9.6.35 (#60218) cask 'vuescan' do version '9.6.35' sha256 :no_check # required as upstream package is updated in-place url "https://www.hamrick.com/files/vuex64#{version.major_minor.no_dots}.dmg" appcast 'https://www.hamrick.com/alternate-versions.html' name 'VueScan' homepage 'https://www.hamrick.com/' app 'VueScan.app' end
cask 'wavebox' do version '3.13.0' sha256 '7fa79e73796533668799e5f04aae41741fa9bdbad8ea1819007b7b4d9a7608c0' # github.com/wavebox/waveboxapp was verified as official when first introduced to the cask url "https://github.com/wavebox/waveboxapp/releases/download/v#{version}/Wavebox_#{version.dots_to_underscores}_osx.dmg" appcast 'https://github.com/wavebox/waveboxapp/releases.atom', checkpoint: '0b86af74e2c3a58a97bba4f7e075af3cdcca0f785cf238dcdadd24d4611dc411' name 'Wavebox' homepage 'https://wavebox.io/' app 'Wavebox.app' uninstall quit: 'io.wavebox.wavebox', login_item: 'Wavebox' zap trash: [ '~/Library/Application Support/wavebox', '~/Library/Caches/io.wavebox.wavebox', '~/Library/Caches/io.wavebox.wavebox.ShipIt', '~/Library/Preferences/io.wavebox.wavebox.helper.plist', '~/Library/Preferences/io.wavebox.wavebox.plist', '~/Library/Saved Application State/io.wavebox.wavebox.savedState', ] end Update wavebox to 3.14.0 (#45988) cask 'wavebox' do version '3.14.0' sha256 '5d7ff8f44b6bc32558e824a2ff07a39077470cbd0a412b995d109d7ea16939cc' # github.com/wavebox/waveboxapp was verified as official when first introduced to the cask url "https://github.com/wavebox/waveboxapp/releases/download/v#{version}/Wavebox_#{version.dots_to_underscores}_osx.dmg" appcast 'https://github.com/wavebox/waveboxapp/releases.atom', checkpoint: '8da1840d974d2d7b43001ff0ce3330d4be2694c857b81f8f52efa75208d4435b' name 'Wavebox' homepage 'https://wavebox.io/' app 'Wavebox.app' uninstall quit: 'io.wavebox.wavebox', login_item: 'Wavebox' zap trash: [ '~/Library/Application Support/wavebox', '~/Library/Caches/io.wavebox.wavebox', '~/Library/Caches/io.wavebox.wavebox.ShipIt', '~/Library/Preferences/io.wavebox.wavebox.helper.plist', '~/Library/Preferences/io.wavebox.wavebox.plist', '~/Library/Saved Application State/io.wavebox.wavebox.savedState', ] end
class Wesnoth < Cask version '1.10.7' sha256 'cdd7788e55e26c9d619b7c98b87db1b99c6a0fc9f525ddb63a6bd33923d94a6f' url "https://downloads.sourceforge.net/sourceforge/wesnoth/Wesnoth_#{version}.dmg" homepage 'http://wesnoth.org' license :oss app 'Wesnoth.app' end new-style header in wesnoth cask :v1 => 'wesnoth' do version '1.10.7' sha256 'cdd7788e55e26c9d619b7c98b87db1b99c6a0fc9f525ddb63a6bd33923d94a6f' url "https://downloads.sourceforge.net/sourceforge/wesnoth/Wesnoth_#{version}.dmg" homepage 'http://wesnoth.org' license :oss app 'Wesnoth.app' end
cask 'wickrme' do version '5.43.8' sha256 'd4664da74f9d0bc1a4e1e82bb44daf1a5ce6343965aa9aec8ecd6bb3062eae6b' # s3.amazonaws.com/static.wickr.com was verified as official when first introduced to the cask url "https://s3.amazonaws.com/static.wickr.com/downloads/mac/me/WickrMe-#{version}.dmg" appcast 'https://pro-download.wickr.com/api/multiVerify/pro/undefined/' name 'Wickr Me' homepage 'https://wickr.com/products/personal/' app 'WickrMe.app' end Update wickrme from 5.43.8 to 5.45.8 (#75380) cask 'wickrme' do version '5.45.8' sha256 '247076276f1fced543482286966ab5ca1573fe8e2c29e14b6d1e9197294e3aa8' # s3.amazonaws.com/static.wickr.com was verified as official when first introduced to the cask url "https://s3.amazonaws.com/static.wickr.com/downloads/mac/me/WickrMe-#{version}.dmg" appcast 'https://pro-download.wickr.com/api/multiVerify/pro/undefined/' name 'Wickr Me' homepage 'https://wickr.com/products/personal/' app 'WickrMe.app' end
cask "xquartz" do version "2.7.11" sha256 "32e50e8f1e21542b847041711039fa78d44febfed466f834a9281c44d75cd6c3" url "https://dl.bintray.com/xquartz/downloads/XQuartz-#{version}.dmg", verified: "bintray.com/xquartz/" name "XQuartz" desc "Open-source version of the X.Org X Window System" homepage "https://www.xquartz.org/" livecheck do url "https://www.xquartz.org/releases/sparkle/release.xml" strategy :sparkle do |item| item.short_version.delete_prefix("XQuartz-") end end auto_updates true pkg "XQuartz.pkg" uninstall quit: "org.macosforge.xquartz.X11", launchctl: [ "org.macosforge.xquartz.startx", "org.macosforge.xquartz.privileged_startx", ], pkgutil: "org.macosforge.xquartz.pkg", delete: [ "/opt/X11", "/private/etc/manpaths.d/40-XQuartz", "/private/etc/paths.d/40-XQuartz", ] zap trash: [ "~/.Xauthority", "~/Library/Application Support/XQuartz", "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.macosforge.xquartz.x11.sfl*", "~/Library/Caches/org.macosforge.xquartz.X11", "~/Library/Cookies/org.macosforge.xquartz.X11.binarycookies", "~/Library/Logs/X11/org.macosforge.xquartz.log", "~/Library/Logs/X11/org.macosforge.xquartz.log.old", "~/Library/Preferences/org.macosforge.xquartz.X11.plist", "~/Library/Saved Application State/org.macosforge.xquartz.X11.savedState", ], rmdir: [ "~/.fonts", "~/Library/Logs/X11", ] end Update xquartz from 2.7.11 to 2.8.0 (#97962) cask "xquartz" do version "2.8.0" sha256 "b74d1d2ff98452d73fb68172c586489e2a6ad3c512e41fd1b0b666ec3dbf5b28" url "https://github.com/XQuartz/XQuartz/releases/download/XQuartz-#{version}/XQuartz-#{version}.dmg", verified: "github.com/XQuartz/XQuartz/" name "XQuartz" desc "Open-source version of the X.Org X Window System" homepage "https://www.xquartz.org/" livecheck do url "https://www.xquartz.org/releases/sparkle/release.xml" strategy :sparkle do |item| item.short_version.delete_prefix("XQuartz-") end end auto_updates true pkg "XQuartz.pkg" uninstall launchctl: "org.xquartz.privileged_startx", pkgutil: "org.xquartz.X11" zap trash: [ "~/.Xauthority", "~/Library/Application Support/XQuartz", "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.xquartz.x11.sfl*", "~/Library/Caches/org.xquartz.X11", "~/Library/Cookies/org.xquartz.X11.binarycookies", "~/Library/Logs/X11/org.xquartz.log", "~/Library/Logs/X11/org.xquartz.log.old", "~/Library/Preferences/org.xquartz.X11.plist", "~/Library/Saved Application State/org.xquartz.X11.savedState", ], rmdir: [ "~/.fonts", "~/Library/Logs/X11", ] end
class Youview < Cask version :latest sha256 :no_check url 'http://download.mrgeckosmedia.com/YouView.zip' appcast 'http://mrgeckosmedia.com/applications/appcast/YouView' homepage 'https://mrgeckosmedia.com/applications/info/YouView' license :unknown app 'YouView/YouView.app' end new-style header in youview cask :v1 => 'youview' do version :latest sha256 :no_check url 'http://download.mrgeckosmedia.com/YouView.zip' appcast 'http://mrgeckosmedia.com/applications/appcast/YouView' homepage 'https://mrgeckosmedia.com/applications/info/YouView' license :unknown app 'YouView/YouView.app' end
class Lastfm module MethodCategory class Track < Base write_method :add_tags, [:artist, :track, :tags] write_method :remove_tag, [:artist, :track, :tag] write_method :ban, [:artist, :track] write_method :love, [:artist, :track] write_method :share, [:artist, :track, :recipient], [[:message, nil]] regular_method :get_info, [:artist, :track], [[:username, nil]] do |response| response.xml['track'] end regular_method :get_top_fans, [:artist, :track], [] do |response| response.xml['topfans']['user'] end regular_method :get_top_tags, [:artist, :track], [] do |response| response.xml['toptags']['tag'] end regular_method :get_similar, [:artist, :track], [] do |response| response.xml['similartracks']['track'][1 .. -1] end regular_method :search, [:track], [[:artist, nil], [:limit, nil], [:page, :nil]] method_with_authentication :get_tags, [:artist, :track], [] do |response| response.xml['tag'] end end end end fix typo class Lastfm module MethodCategory class Track < Base write_method :add_tags, [:artist, :track, :tags] write_method :remove_tag, [:artist, :track, :tag] write_method :ban, [:artist, :track] write_method :love, [:artist, :track] write_method :share, [:artist, :track, :recipient], [[:message, nil]] regular_method :get_info, [:artist, :track], [[:username, nil]] do |response| response.xml['track'] end regular_method :get_top_fans, [:artist, :track], [] do |response| response.xml['topfans']['user'] end regular_method :get_top_tags, [:artist, :track], [] do |response| response.xml['toptags']['tag'] end regular_method :get_similar, [:artist, :track], [] do |response| response.xml['similartracks']['track'][1 .. -1] end regular_method :search, [:track], [[:artist, nil], [:limit, nil], [:page, nil]] method_with_authentication :get_tags, [:artist, :track], [] do |response| response.xml['tag'] end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'archive/ar/version' Gem::Specification.new do |spec| spec.name = "archive-ar" spec.version = Archive::Ar::VERSION spec.authors = ["Joshua B. Bussdieker"] spec.email = ["jbussdieker@gmail.com"] spec.summary = %q{Simple AR file functions} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" end Add homepage setting to gemspec # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'archive/ar/version' Gem::Specification.new do |spec| spec.name = "archive-ar" spec.version = Archive::Ar::VERSION spec.authors = ["Joshua B. Bussdieker"] spec.email = ["jbussdieker@gmail.com"] spec.summary = %q{Simple AR file functions} spec.homepage = "https://github.com/jbussdieker/ruby-archive-ar" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" end
#TODO: see how to treat include module's implementation_id; might deprecate module DTK class ModuleRefs # This class is used to build a hierarchical dependency tree and to detect conflicts class Tree attr_reader :module_branch def initialize(module_branch,context=nil) @module_branch = module_branch @context = context # module_refs is hash where key is module_name and # value is either nil for a missing reference # or it points to a Tree object @module_refs = Hash.new end private :initialize # params are assembly instance and the component instances that are in the assembly instance def self.create(assembly_instance,components) create_module_refs_starting_from_assembly(assembly_instance,components) end def violations?() # For Aldin # TODO: stub # this shoudl return information that can be used in the assemblu insatnce violations that can be turned into two types of errors # 1) error where theer is a module_name in @module_refs whos value is nil, meaning it is amissing reference # 2) case where a module name points to two difefrent refs with different namespaces nil end def debug_hash_form() ret = Hash.new if @context.kind_of?(Assembly) ret[:type] = 'Assembly::Instance' ret[:name] = @context.get_field?(:display_name) elsif @context.kind_of?(ModuleRef) ret[:type] = 'ModuleRef' ret[:namespace] = @context[:namespace_info] else ret[:type] = @context.class ret[:content] = @context end refs = @module_refs.inject(Hash.new) do |h,(module_name,subtree)| h.merge(module_name => subtree && subtree.debug_hash_form()) end ret[:refs] = refs unless refs.empty? ret end def add_module_ref!(module_name,child) @module_refs[module_name] = child end private def self.create_module_refs_starting_from_assembly(assembly_instance,components) # get relevant service and component module branches ndx_cmps = Hash.new #components indexed (grouped) by branch id components.each do |cmp| branch_id = cmp.get_field?(:module_branch_id) (ndx_cmps[branch_id] ||= Array.new) << cmp end service_module_branch_id = assembly_instance.get_field?(:module_branch_id) sp_hash = { :cols => ModuleBranch.common_columns(), :filter => [:or, [:eq,:id,service_module_branch_id],[:oneof,:id,ndx_cmps.keys]] } relevant_module_branches = Model.get_objs(assembly_instance.model_handle(:module_branch),sp_hash) service_module_branch = relevant_module_branches.find{|r|r[:id] == service_module_branch_id} cmp_module_branches = relevant_module_branches.reject!{|r|r[:id] == service_module_branch_id} ret = new(service_module_branch,assembly_instance) leaves = Array.new get_children_from_component_module_branches(cmp_module_branches,service_module_branch) do |module_name,child| leaves << child if child ret.add_module_ref!(module_name,child) end recursive_add_module_refs!(ret,leaves) ret end def self.recursive_add_module_refs!(top,subtrees) return if subtrees.empty? leaves = Array.new #TODO: can bulk up subtrees.each do |subtree| get_children([subtree.module_branch]) do |module_name,child| leaves << child if child subtree.add_module_ref!(module_name,child) end end recursive_add_module_refs!(top,leaves) end def self.get_children_from_component_module_branches(cmp_module_branches,service_module_branch,&block) ndx_mod_name_branches = cmp_module_branches.inject(Hash.new) do |h,module_branch| # TODO: can bulk up; look also at using # assembly_instance.get_objs(:cols=> [:instance_component_module_branches]) h.merge(module_branch.get_module()[:display_name] => module_branch) end ndx_module_refs = Hash.new ModuleRefs.get_component_module_refs(service_module_branch).component_modules.each_value do |module_ref| ndx_module_refs[module_ref[:id]] ||= module_ref end module_refs = ndx_module_refs.values # either ndx_mod_name_branches or ndx_mod_ref_branches wil be non null module_refs.each do |module_ref| matching_branch = nil if ndx_mod_name_branches unless matching_branch = ndx_mod_name_branches[module_ref[:module_name]] Log.error("No match for #{module_ref[:module_name]} in #{ndx_mod_name_branches.inspect}") end end if matching_branch child = new(matching_branch,module_ref) block.call(module_ref[:module_name],child) end end end def self.get_children(module_branches,&block) ndx_module_refs = Hash.new ModuleRefs.get_multiple_component_module_refs(module_branches).each do |cmrs| cmrs.component_modules.each_value do |module_ref| ndx_module_refs[module_ref[:id]] ||= module_ref end end module_refs = ndx_module_refs.values ndx_mod_ref_branches = Hash.new ModuleRef.find_ndx_matching_component_modules(module_refs).each_pair do |mod_ref_id,cmp_module| version = nil #TODO: stub; need to change when treat service isnatnce branches ndx_mod_ref_branches[mod_ref_id] = cmp_module.get_module_branch_matching_version(version) end module_refs.each do |module_ref| matching_branch = nil unless matching_branch = ndx_mod_ref_branches[module_ref.id] Log.error("No match for #{module_ref.inspect} in #{ndx_mod_ref_branches}") end if matching_branch child = new(matching_branch,module_ref) block.call(module_ref[:module_name],child) end end end def process_component_include_modules(components) #aug_inc_mods elements are include modules at top level and possibly the linked impementation component_idhs = components.map{|cmp|cmp.id_handle()} aug_incl_mods = Component::IncludeModule.get_include_mods_with_impls(component_idhs) impls = get_unique_implementations(aug_incl_mods) #TODO: this can be bulked up ndx_cmrs = impls.inject(Hash.new) do |h,impl| h.merge(impl[:id] => ModuleRefs.get_component_module_refs(impl.get_module_branch())) end aug_incl_mods.each do |incl_mod| if cmrs = ndx_cmrs[incl_mod[:implementation_id]] add_component_module_refs!(cmrs,incl_mod) end end end def get_unique_implementations(aug_incl_mods) ndx_ret = Hash.new aug_incl_mods.each do |aug_incl_mod| unless impl = aug_incl_mod[:implementation] raise Error.new("need to write code when aug_incl_mod[:implementation] is nil") end ndx_ret[impl[:id]] ||= impl end ndx_ret.values end end end end feature_recursive_includes: refactor #TODO: see how to treat include module's implementation_id; might deprecate module DTK class ModuleRefs # This class is used to build a hierarchical dependency tree and to detect conflicts class Tree attr_reader :module_branch def initialize(module_branch,context=nil) @module_branch = module_branch @context = context # module_refs is hash where key is module_name and # value is either nil for a missing reference # or it points to a Tree object @module_refs = Hash.new end private :initialize # params are assembly instance and the component instances that are in the assembly instance def self.create(assembly_instance,components) create_module_refs_starting_from_assembly(assembly_instance,components) end def violations?() # For Aldin # TODO: stub # this shoudl return information that can be used in the assemblu insatnce violations that can be turned into two types of errors # 1) error where theer is a module_name in @module_refs whos value is nil, meaning it is amissing reference # 2) case where a module name points to two difefrent refs with different namespaces nil end def debug_hash_form() ret = Hash.new if @context.kind_of?(Assembly) ret[:type] = 'Assembly::Instance' ret[:name] = @context.get_field?(:display_name) elsif @context.kind_of?(ModuleRef) ret[:type] = 'ModuleRef' ret[:namespace] = @context[:namespace_info] else ret[:type] = @context.class ret[:content] = @context end refs = @module_refs.inject(Hash.new) do |h,(module_name,subtree)| h.merge(module_name => subtree && subtree.debug_hash_form()) end ret[:refs] = refs unless refs.empty? ret end def add_module_ref!(module_name,child) @module_refs[module_name] = child end private def self.create_module_refs_starting_from_assembly(assembly_instance,components) # get relevant service and component module branches ndx_cmps = Hash.new #components indexed (grouped) by branch id components.each do |cmp| unless branch_id = cmp.get_field?(:module_branch_id) Log.error("Unexpected that :module_branch_id not in: #{cmp.inspect}") next end (ndx_cmps[branch_id] ||= Array.new) << cmp end cmp_module_branch_ids = ndx_cmps.keys service_module_branch_id = assembly_instance.get_field?(:module_branch_id) sp_hash = { :cols => ModuleBranch.common_columns(), :filter => [:or, [:eq,:id,service_module_branch_id],[:oneof,:id,cmp_module_branch_ids]] } relevant_module_branches = Model.get_objs(assembly_instance.model_handle(:module_branch),sp_hash) service_module_branch = relevant_module_branches.find{|r|r[:id] == service_module_branch_id} cmp_module_branches = relevant_module_branches.reject!{|r|r[:id] == service_module_branch_id} #TODO: extra check we can remove after we refine missing_branches = cmp_module_branch_ids - cmp_module_branches.map{|r|r[:id]} unless missing_branches.empty? Log.error("Unexpected that the following branches dont exist; branches with ids #{missing_branches.join(',')}") end ret = new(service_module_branch,assembly_instance) leaves = Array.new get_top_level_children(cmp_module_branches,service_module_branch) do |module_name,child| leaves << child if child ret.add_module_ref!(module_name,child) end recursive_add_module_refs!(ret,leaves) ret end def self.recursive_add_module_refs!(top,subtrees) return if subtrees.empty? leaves = Array.new #TODO: can bulk up subtrees.each do |subtree| get_children([subtree.module_branch]) do |module_name,child| leaves << child if child subtree.add_module_ref!(module_name,child) end end recursive_add_module_refs!(top,leaves) end # TODO: fix this up because cmp_module_branches already has implict namespace so this is # effectively just checking consistency of component module refs # and setting of module_branch_id in component insatnces def self.get_top_level_children(cmp_module_branches,service_module_branch,&block) # get component module refs indexed by module name ndx_cmp_module_refs = Hash.new ModuleRefs.get_component_module_refs(service_module_branch).component_modules.each_value do |module_ref| ndx_cmp_module_refs[module_ref[:module_name]] ||= module_ref end # get branches indexed by module_name # TODO: can bulk up; look also at using # assembly_instance.get_objs(:cols=> [:instance_component_module_branches]) ndx_mod_name_branches = cmp_module_branches.inject(Hash.new) do |h,module_branch| h.merge(module_branch.get_module()[:display_name] => module_branch) end ndx_mod_name_branches.each_pair do |module_name,module_branch| module_ref = ndx_cmp_module_refs[module_name] child = module_ref && new(module_branch,module_ref) block.call(module_ref[:module_name],child) end end def self.get_children(module_branches,&block) ndx_module_refs = Hash.new ModuleRefs.get_multiple_component_module_refs(module_branches).each do |cmrs| cmrs.component_modules.each_value do |module_ref| ndx_module_refs[module_ref[:id]] ||= module_ref end end module_refs = ndx_module_refs.values ndx_mod_ref_branches = Hash.new ModuleRef.find_ndx_matching_component_modules(module_refs).each_pair do |mod_ref_id,cmp_module| version = nil #TODO: stub; need to change when treat service isnatnce branches ndx_mod_ref_branches[mod_ref_id] = cmp_module.get_module_branch_matching_version(version) end module_refs.each do |module_ref| matching_branch = nil unless matching_branch = ndx_mod_ref_branches[module_ref.id] Log.error("No match for #{module_ref.inspect} in #{ndx_mod_ref_branches}") end if matching_branch child = new(matching_branch,module_ref) block.call(module_ref[:module_name],child) end end end def process_component_include_modules(components) #aug_inc_mods elements are include modules at top level and possibly the linked impementation component_idhs = components.map{|cmp|cmp.id_handle()} aug_incl_mods = Component::IncludeModule.get_include_mods_with_impls(component_idhs) impls = get_unique_implementations(aug_incl_mods) #TODO: this can be bulked up ndx_cmrs = impls.inject(Hash.new) do |h,impl| h.merge(impl[:id] => ModuleRefs.get_component_module_refs(impl.get_module_branch())) end aug_incl_mods.each do |incl_mod| if cmrs = ndx_cmrs[incl_mod[:implementation_id]] add_component_module_refs!(cmrs,incl_mod) end end end def get_unique_implementations(aug_incl_mods) ndx_ret = Hash.new aug_incl_mods.each do |aug_incl_mod| unless impl = aug_incl_mod[:implementation] raise Error.new("need to write code when aug_incl_mod[:implementation] is nil") end ndx_ret[impl[:id]] ||= impl end ndx_ret.values end end end end
module LovelyRufus class HangoutWrapper < Layer def call text: text, width: 72 @text = text @width = width final = hangout_line ? rewrapped : text next_layer.call text: final, width: width end attr_reader :text, :width private :text, :width private def hangout_line lines.each_cons 2 do |a, b| return a if a[' '] and a.rindex(' ') >= b.size return b if b[' '] and b.rindex(' ') >= a.size end end def lines @lines ||= text.lines.map(&:chomp) end def rewrapped hangout_line << NBSP unfolded = lines.join(' ').gsub("#{NBSP} ", NBSP) wrapped = BasicWrapper.new.call(text: unfolded, width: width)[:text] HangoutWrapper.new.call(text: wrapped, width: width)[:text] end end end HangoutWriter: consider all spaces equal module LovelyRufus class HangoutWrapper < Layer def call text: text, width: 72 @text = text @width = width final = hangout_line ? rewrapped : text next_layer.call text: final, width: width end attr_reader :text, :width private :text, :width private def hangout_line lines.each_cons 2 do |a, b| return a if a[/\p{space}/] and a.rindex(/\p{space}/) >= b.size return b if b[/\p{space}/] and b.rindex(/\p{space}/) >= a.size end end def lines @lines ||= text.lines.map(&:chomp) end def rewrapped hangout_line << NBSP unfolded = lines.join(' ').gsub("#{NBSP} ", NBSP) wrapped = BasicWrapper.new.call(text: unfolded, width: width)[:text] HangoutWrapper.new.call(text: wrapped, width: width)[:text] end end end
WIP commit #!/usr/bin/env ruby if __FILE__==$0 require 'pry' end class ComponentDocumentation def initialize component_name @component_name = component_name file_root = "" filename = @component_name.split('.')[1].downcase @file_path = "#{file_root}/src/components/#{filename}.coffee" @file_contents = File.open(file_path).read() end def method_data end def comments end def arguments end end class DocumentationGenerator FILE_ROOT = "/Users/alexsmith/Development/luca" def initialize options={} raise "Must pass options[:class_name]" if options[:class_name].nil? raise "Myst pass options[:property]" if options[:property].nil? @class_name = options[:class_name] @property_name = options[:property] load_target_file end def load_target_file file_path = "#{FILE_ROOT}/src/components/#{@class_name}.coffee" @file_contents = File.open(file_path).read() @property_match = @file_contents.match(/(^\s*#.*$\n)*(\s*#{@property_name}\s*:\s*\(.*\)\s*-\>.*$)/) end def args args = @property_match[0].match(/^\s*#{@property_name}\s*:\s*\((.*)\)\s*-\>.*$/)[1] args = args.gsub(/\s/,'').split(',') args.inject({}) do |memo, arg| if default_args = arg.match(/^(.*)=(.+)/) memo[default_args[1].to_sym] = default_args[2] else memo[arg.to_sym] = nil end memo end end def comments @comments = @property_match[0].match(/(^\s*#.*$\n)*/)[0] end def function_signature end def docs @property_match[0] end end if __FILE__==$0 pry end
require 'xmlrpc/client' module MandarinSoda module ChimpCampaign class ChimpConfigError < StandardError; end class ChimpConnectError < StandardError; end def self.included(base) base.extend ActMethods mattr_reader :chimp_config, :auth CHIMP_URL = "http://api.mailchimp.com/1.1/" CHIMP_API = XMLRPC::Client.new2(CHIMP_URL) begin @@chimp_config_path = (RAILS_ROOT + '/config/mail_chimp.yml') @@chimp_config = YAML.load_file(@@chimp_config_path)[RAILS_ENV].symbolize_keys @@auth ||= CHIMP_API.call("login", @@chimp_config[:username], @@chimp_config[:password]) end end module ActMethods def acts_as_chimp_campaign(options = {}) unless included_modules.include? InstanceMethods class_inheritable_accessor :options extend ClassMethods include InstanceMethods end self.options = options end end module ClassMethods def campaigns end def stats(id) chimp_campaign_stats(id) end def hard_bounces(id, start, limit) chimp_campaign_hard_bounces(id, start, limit) end def soft_bounces(id, start, limit) chimp_campaign_soft_bounces(id, start, limit) end def unsubscribed(id, start, limit) chimp_campaign_unsubscribed(id, start, limit) end def abuse(id, start, limit) chimp_campaign_abuse_reports(id, start, limit) end def folders chimp_campaign_folders end private def chimp_campaign_abuse_reports(campaign_id, start=0, limit=100) CHIMP_API.call("campaignAbuseReports", auth, self.campaign_id) end def chimp_campaign_stats(campaign_id) CHIMP_API.call("campaignStats", auth, campaign_id) end def chimp_campaign_hard_bounces(campaign_id, start=0, limit=100) CHIMP_API.call("campaignHardBounces", auth, campaign_id, start, limit) end def chimp_campaign_soft_bounces(campaign_id, start=0, limit=100) CHIMP_API.call("campaignSoftBounces", auth, campaign_id, start, limit) end def chimp_campaign_unsubscribed(campaign_id, start=0, limit=100) CHIMP_API.call("campaignUnsubscribes", auth, campaign_id, start, limit) end def chimp_campaign_folders CHIMP_API.call("campaignFolder", auth) end end module InstanceMethods def create_campaign end def update_campaign(options={}) chimp_update_campaign(options) end def resume chimp_resume_campaign end def pause chimp_pause_campaign end def unschedule chimp_campaign_unschedule end def content chimp_campaign_content end def schedule(time, group_b_time) chimp_campaign_schedule(time, group_b_time) end def send_now chimp_send_campaign end def send_test chimp_send_campaign end private def chimp_create_campaign(mailing_list_id, type, opts) CHIMP_API.call("listMemberInfo", auth, mailing_list_id) end def chimp_update_campaign(opts) CHIMP_API.call("listMemberInfo", auth, self.campaign_id, self.name, opts) end def chimp_pause_campaign CHIMP_API.call("campaignPause", auth, self.campaign_id ) end def chimp_resume_campaign CHIMP_API.call("campaignResume", auth, self.campaign_id) end def chimp_send_campaign CHIMP_API.call("campaignSendNow", auth, self.campaign_id) end def chimp_send_campaign_test CHIMP_API.call("campaignSendTest", auth, self.campaign_id) end def chimp_campaign_schedule(time, time_b) CHIMP_API.call("campaignSchedule", auth, self.campaign_id, time, time_b) end def chimp_campaign_unschedule CHIMP_API.call("campaignUnschedule", auth, self.campaign_id) end def chimp_campaign_content CHIMP_API.call("campaignContent", auth, self.campaign_id) end end end end happy halloween require 'xmlrpc/client' module MandarinSoda module ChimpCampaign class ChimpConfigError < StandardError; end class ChimpConnectError < StandardError; end def self.included(base) base.extend ActMethods mattr_reader :chimp_config, :auth CHIMP_URL = "http://api.mailchimp.com/1.1/" CHIMP_API = XMLRPC::Client.new2(CHIMP_URL) begin @@chimp_config_path = (RAILS_ROOT + '/config/mail_chimp.yml') @@chimp_config = YAML.load_file(@@chimp_config_path)[RAILS_ENV].symbolize_keys @@auth ||= CHIMP_API.call("login", @@chimp_config[:username], @@chimp_config[:password]) end end module ActMethods def acts_as_chimp_campaign(options = {}) unless included_modules.include? InstanceMethods class_inheritable_accessor :options extend ClassMethods include InstanceMethods end self.options = options end end module ClassMethods def campaigns end def stats(id) chimp_campaign_stats(id) end def hard_bounces(id, start, limit) chimp_campaign_hard_bounces(id, start, limit) end def soft_bounces(id, start, limit) chimp_campaign_soft_bounces(id, start, limit) end def unsubscribed(id, start, limit) chimp_campaign_unsubscribed(id, start, limit) end def abuse(id, start, limit) chimp_campaign_abuse_reports(id, start, limit) end def folders chimp_campaign_folders end private def chimp_campaign_abuse_reports(campaign_id, start=0, limit=100) CHIMP_API.call("campaignAbuseReports", auth, self.campaign_id) end def chimp_campaign_stats(campaign_id) CHIMP_API.call("campaignStats", auth, campaign_id) end def chimp_campaign_hard_bounces(campaign_id, start=0, limit=100) CHIMP_API.call("campaignHardBounces", auth, campaign_id, start, limit) end def chimp_campaign_soft_bounces(campaign_id, start=0, limit=100) CHIMP_API.call("campaignSoftBounces", auth, campaign_id, start, limit) end def chimp_campaign_unsubscribed(campaign_id, start=0, limit=100) CHIMP_API.call("campaignUnsubscribes", auth, campaign_id, start, limit) end def chimp_campaign_folders CHIMP_API.call("campaignFolder", auth) end end module InstanceMethods def create_campaign end def update_campaign(options={}) chimp_update_campaign(options) end def resume chimp_resume_campaign end def pause chimp_pause_campaign end def unschedule chimp_campaign_unschedule end def content chimp_campaign_content end def schedule(time, group_b_time) chimp_campaign_schedule(time, group_b_time) end def send_now chimp_send_campaign end def send_test chimp_send_campaign end private def chimp_create_campaign(mailing_list_id, type, opts) CHIMP_API.call("listMemberInfo", auth, mailing_list_id) end def chimp_update_campaign(opts) CHIMP_API.call("listMemberInfo", auth, self.campaign_id, self.name, opts) end def chimp_pause_campaign CHIMP_API.call("campaignPause", auth, self.campaign_id ) end def chimp_resume_campaign CHIMP_API.call("campaignResume", auth, self.campaign_id) end def chimp_send_campaign CHIMP_API.call("campaignSendNow", auth, self.campaign_id) end def chimp_send_campaign_test CHIMP_API.call("campaignSendTest", auth, self.campaign_id) end def chimp_campaign_schedule(time, time_b) CHIMP_API.call("campaignSchedule", auth, self.campaign_id, time, time_b) end def chimp_campaign_unschedule CHIMP_API.call("campaignUnschedule", auth, self.campaign_id) end def chimp_campaign_content CHIMP_API.call("campaignContent", auth, self.campaign_id) end end end end
module Mephisto module Liquid class SectionDrop < ::Liquid::Drop include Reloadable attr_reader :section def initialize(section) @section = section @section_liquid = [:id, :name, :path].inject({}) { |h, k| h.merge k.to_s => section.send(k) } end def before_method(method) @section_liquid[method.to_s] end def url @url ||= '/' + @section.to_url.join('/') end def is_home @section.home? end end end end add articles_count to sectiondrop git-svn-id: 4158f9403e16ea83fe8a6e07a45f1f3b56a747ab@1540 567b1171-46fb-0310-a4c9-b4bef9110e78 module Mephisto module Liquid class SectionDrop < ::Liquid::Drop include Reloadable attr_reader :section def initialize(section) @section = section @section_liquid = [:id, :name, :path, :articles_count].inject({}) { |h, k| h.merge k.to_s => section.send(k) } end def before_method(method) @section_liquid[method.to_s] end def url @url ||= '/' + @section.to_url.join('/') end def is_home @section.home? end end end end
require 'active_support/core_ext/hash/indifferent_access' module MiddlemanHeadless class Interface def initialize(options, space) @cache = {} @conn = Faraday.new(url: "#{options.address}/delivery/#{space}") do |config| config.headers['Authorization'] = "Bearer #{options.token}" config.response :logger if options.log config.adapter Faraday.default_adapter end end def space @space ||= Space.new(get('').with_indifferent_access) end def entries(content_type) content_type = content_type[:slug] if content_type.is_a?(Hash) @cache[content_type.to_sym] ||= get(content_type).map do |item| Entry.new(item.with_indifferent_access) end end def method_missing(key) entries(key.to_s) end protected def get(path) JSON.parse(@conn.get(path).body) end end class Item def initialize(data) @data = data end def method_missing(key) @data[key] end end class Space < Item def content_types @data[:content_types].map{|item| Item.new(item) } end def languages @data[:languages].map{|item| Item.new(item) } end end class Entry def initialize(data) @data = data end def id @data[:id] end def name @data[:name] end def version(key) Version.new(@data[:versions][key]) end def field(key) version(I18n.locale).field(key) end def method_missing(key) field(key) end end class Version def initialize(data) @data = data end def id @data[:id] end def field(key) @data[:fields][key] end def updated_at @data[:updated_at] end def published_at @data[:published_at] end def method_missing(key) field(key) end end end reflect changes to server require 'active_support/core_ext/hash/indifferent_access' module MiddlemanHeadless class Interface def initialize(options, space) @cache = {} @conn = Faraday.new(url: "#{options.address}/delivery/#{space}") do |config| config.headers['Authorization'] = "Bearer #{options.token}" config.response :logger if options.log config.adapter Faraday.default_adapter end end def space @space ||= Space.new(get('').with_indifferent_access) end def entries(content_type) content_type = content_type[:slug] if content_type.is_a?(Hash) @cache[content_type.to_sym] ||= get(content_type).map do |item| Entry.new(item.with_indifferent_access) end end def method_missing(key) entries(key.to_s) end protected def get(path) JSON.parse(@conn.get(path).body) end end class Item def initialize(data) @data = data end def method_missing(key) @data[key] end end class Space < Item def content_types @data[:content_types].map{|item| Item.new(item) } end def languages @data[:languages].map{|item| Item.new(item) } end end class Entry def initialize(data) @data = data end def id @data[:id] end def name @data[:name] end def version(key) Version.new(@data[:versions][key]) end def field(key) version(I18n.locale).field(key) end def method_missing(key) field(key) end end class Version def initialize(data) @data = data end def field(key) @data[:fields][key] end def updated_at @data[:updated_at] end def published_at @data[:published_at] end def method_missing(key) field(key) end end end
# -*- coding: utf-8 -*- # # Author:: Nuo Yan <nuo@opscode.com> # # Copyright 2010, Opscode, Inc. # # All rights reserved - do not redistribute # $KCODE= 'utf8' require 'mixlib/localization' module Mixlib module Localization class Messages # Retrieve the error message given the error key (e.g. 'opscode-chef-webui-nodes-403') and the language code (e.g. 'en-us') # returns the array of error code (customer support purpose) and the message. (e.g. ["a7svai98", "You are not authorized to view the node."]) def self.get_message(message_key, language_code) message_hash = self.messages[message_key.to_s] begin [message_hash["message_id"], message_hash["languages"][language_code.to_s] || message_hash["languages"]["en_us"]] rescue => e Mixlib::Localization::Log.error("Cannot find the error message with message_key #{message_key} \n #{e.message} \n #{e.backtrace.join("\n")}") raise MessageRetrievalError, "Cannot find the error message with message_key '#{message_key}'." end end # Retrieve the error message given the error key (e.g. 'opscode-chef-webui-nodes-403') and the language code (e.g. 'en-us') # returns the array of error code (customer support purpose) and the message. (e.g. ["a7svai98", "You are not authorized to view the node."]) # returns nil if message key does not exist def self.find_message(message_key, language_code="en_us") message_hash = self.messages[message_key.to_s] if message_hash [message_hash["message_id"], message_hash["languages"][language_code.to_s] || message_hash["languages"]["en_us"]] else nil end end # Retrieve the error message given the message id (e.g. '123456') and the language code (e.g. 'en-us') # returns the array of error code (customer support purpose) and the message. (e.g. ["123456", "You are not authorized to view the node."]) # raises an exception if the message id doesn't exist def self.get_message_by_id(message_id, language_code='en_us') message_hash = self.messages_by_id[message_id] if message_hash [message_hash["message_id"], message_hash["languages"][language_code.to_s] || message_hash["languages"]["en_us"]] else raise MessageRetrievalError, "Cannot find the error message with message_id '#{message_id}'." end end # Retrieve the error message given the message id (e.g. '123456') and the language code (e.g. 'en-us') # returns the array of error code (customer support purpose) and the message. (e.g. ["123456", "You are not authorized to view the node."]) # returns nil if the message id doesn't exist def self.find_message_by_id(message_id, language_code='en_us') message_hash = self.messages_by_id[message_id] if message_hash [message_hash["message_id"], message_hash["languages"][language_code.to_s] || message_hash["languages"]["en_us"]] else nil end end # Take what returns from self.get_message, and returns the formatted string. # Example: input: ["10000", "You are not authorized to view the node."], output: "Error 10000: You are not authorized to view the node." def self.parse_error_message(message_array) "#{message_array[1]} (Error #{message_array[0]})" end # Convenience method combining get_message and parse_error_message def self.get_parse_error_message(message_key, language_code) self.parse_error_message(self.get_message(message_key, language_code)) end # Take what returns from self.get_message, and returns only the message. # Example: input: ["50000", "Successfully created node."], output: "Successfully created node." def self.parse_info_message(message_array) message_array[1] end # Convenience method combining get_message and parse_error_message def self.get_parse_info_message(message_key, language_code) self.parse_info_message(self.get_message(message_key, language_code)) end # Generates a text file with message ids and the messages, Customer Service may use this file as a reference. # messages generated are not sorted (at least currently), but I don't see the need/benefits yet to make them sorted def self.generate_message_text_file(language, output_file) file = File.open(output_file, "w+") file.write("***Generated by rake generate_messages***\n\nID \t Message\n") self.messages.each_pair do |message_key, message_body| file.write("#{message_body["message_id"]} \t #{message_body["languages"][language] || message_body["languages"]["en_us"]} (internal key: #{message_key})\n") end file.close end private # # Each message is structured with 3 components: # 1. message_key: the string used in our code base to refer to this message (e.g. opscode-chef-webui-nodes-show-403) # 2. message_id: The user facing message id or error code (e.g. "10000"). It's a String, not Int. # 3. languages: the message in different languages, use the language code as the key. def self.messages MESSAGES_BY_KEY end def self.messages_by_id MESSAGES_BY_ID end MESSAGES_BY_KEY = { "opscode-chef-webui-500" => { "message_id" => "10000", "languages" => { "en_us" => "An application error has occurred. Please try again later.", "zh_cn" => "应用程序错误,请稍候重试。多谢理解。" } }, "opscode-chef-webui-login-incorrect_password" => { "message_id" => "29002", "languages" => { "en_us" => "Username and password do not match.", "zh_cn" => "用户名和密码不符。" } }, "opscode-chef-webui-nodes-show-403" => { "message_id" => "20000", "languages" => { "en_us" => "Permission denied. You do not have permission to view the node.", "zh_cn" => "对不起,您没有权限访问此节点。" } }, "opscode-chef-webui-nodes-show-404" => { "message_id" => "20001", "languages" => { "en_us" => "Node not found.", "zh_cn" => "无法找到节点。" } }, "opscode-chef-webui-nodes-show-408" => { "message_id" => "20002", "languages" => { "en_us" => "Request timed out when attempting to view the node.", "zh_cn" => "对不起,尝试查看节点超时。" } }, "opscode-chef-webui-nodes-acl-get-403" => { "message_id" => "20003", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this node.", "zh_cn" => "对不起,您没有权限读取此节点的权限设置。" } }, "opscode-chef-webui-nodes-acl-get-408" => { "message_id" => "20004", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this node.", "zh_cn" => "对不起,尝试读取节点的权限设置超时。" } }, "opscode-chef-webui-nodes-acl-set" => { "message_id" => "20005", "languages" => { "en_us" => "Failed to set permissions on this node.", "zh_cn" => "对不起,更新此节点的权限设置失败。" } }, "opscode-chef-webui-nodes-container-acl-get-403" => { "message_id" => "20006", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the nodes collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的节点集合的权限设置。" } }, "opscode-chef-webui-nodes-container-acl-get-408" => { "message_id" => "20007", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the nodes collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的节点集合的权限设置超时。" } }, "opscode-chef-webui-nodes-container-acl-set" => { "message_id" => "20008", "languages" => { "en_us" => "Failed to set permissions on the nodes collection in this organization.", "zh_cn" => "对不起,更新此组织的节点集合的权限设置失败。" } }, "opscode-chef-webui-nodes-index-403" => { "message_id" => "20009", "languages" => { "en_us" => "Permission denied. You do not have permission to list the nodes in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的节点列表。" } }, "opscode-chef-webui-nodes-index-408" => { "message_id" => "20010", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of nodes in this organization.", "zh_cn" => "对不起,尝试读取此组织的节点列表超时。" } }, "opscode-chef-webui-nodes-roles-403" => { "message_id" => "20011", "languages" => { "en_us" => "Permission denied. You do not have permission to view roles in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的角色和配方单,而显示新节点表单需要这些权限。" } }, "opscode-chef-webui-nodes-edit-404" => { "message_id" => "20013", "languages" => { "en_us" => "Node not found.", "zh_cn" => "无法找到节点。" } }, "opscode-chef-webui-nodes-edit-403" => { "message_id" => "20014", "languages" => { "en_us" => "Permission denied. You do not have permission to read this node or to list the roles in this organization. These rights are required to display the node edit form.", "zh_cn" => "对不起,您没有权限读取此节点或角色列表,而显示编辑节点表单需要这些权限。" } }, "opscode-chef-webui-nodes-edit-408" => { "message_id" => "20015", "languages" => { "en_us" => "Request timed out when attempting to read the node or to list the organization's roles.", "zh_cn" => "对不起,尝试读取此节点或角色列表超时。" } }, "opscode-chef-webui-nodes-create-success" => { "message_id" => "20016", "languages" => { "en_us" => "The node was created successfully.", "zh_cn" => "成功创建节点。" } }, "opscode-chef-webui-nodes-create-failed-validation" => { "message_id" => "20017", "languages" => { "en_us" => "The new node is not formed correctly. Check for illegal characters in the node's name or body, and check that the body is formed correctly. Only A-Z, a-z, _, -, :, and . are supported in the name.", "zh_cn" => "新节点名字或内容中含有不支持的字符,或节点的结构不正确。节点的名字只支持以下字符:A-Z, a-z, _, -, 和." } }, "opscode-chef-webui-nodes-create-409" => { "message_id" => "20018", "languages" => { "en_us" => "A node with that name already exists.", "zh_cn" => "同名节点已存在。" } }, "opscode-chef-webui-nodes-create-403" => { "message_id" => "20019", "languages" => { "en_us" => "Permission denied. You do not have permission to create a node in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的节点。" } }, "opscode-chef-webui-nodes-create-408" => { "message_id" => "20020", "languages" => { "en_us" => "Request timed out when attempting to create a new node.", "zh_cn" => "对不起,尝试创建新节点超时。" } }, "opscode-chef-webui-nodes-update-success" => { "message_id" => "20021", "languages" => { "en_us" => "The node was updated successfully.", "zh_cn" => "成功更新节点。" } }, "opscode-chef-webui-nodes-update-failed-validation" => { "message_id" => "20022", "languages" => { "en_us" => "The new node is not formed correctly. Check for illegal characters in the node's name or body, and check that the body is formed correctly.", "zh_cn" => "新节点名字或内容中含有不支持的字符,或节点的结构不正确。" } }, "opscode-chef-webui-nodes-update-403" => { "message_id" => "20023", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this node.", "zh_cn" => "对不起,您没有权限修改此节点。" } }, "opscode-chef-webui-nodes-update-408" => { "message_id" => "20024", "languages" => { "en_us" => "Request timed out when attempting to modify the node.", "zh_cn" => "对不起,尝试修改此节点超时。" } }, "opscode-chef-webui-nodes-update-409" => { "message_id" => "20025", "languages" => { "en_us" => "The new name of the node conflicts with another existing node.", "zh_cn" => "同名节点已存在。" } }, "opscode-chef-webui-nodes-update-404" => { "message_id" => "20026", "languages" => { "en_us" => "Node not found.", "zh_cn" => "无法找到节点。" } }, "opscode-chef-webui-nodes-destroy-success" => { "message_id" => "20027", "languages" => { "en_us" => "The node was deleted successfully.", "zh_cn" => "成功删除节点。" } }, "opscode-chef-webui-nodes-destroy-confirm" => { "message_id" => "20028", "languages" => { "en_us" => "Please confirm that you would like to delete this node.", "zh_cn" => "请确认您希望删除此节点。" } }, "opscode-chef-webui-nodes-destroy-404" => { "message_id" => "20029", "languages" => { "en_us" => "Node not found.", "zh_cn" => "无法找到节点。" } }, "opscode-chef-webui-nodes-destroy-403" => { "message_id" => "20030", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this node.", "zh_cn" => "对不起,您无权删除此节点。" } }, "opscode-chef-webui-nodes-destroy-408" => { "message_id" => "20031", "languages" => { "en_us" => "Request timed out when attempting to delete this node.", "zh_cn" => "对不起,尝试删除此节点超时。" } }, "opscode-chef-webui-nodes-environments-403" => { "message_id" => "20032", "languages" => { "en_us" => "Permission denied. You do not have permission to view available recipes in the selected environment in this organization.", "zh_cn" => "对不起,您无权在此组织查看此环境中的配方单。" } }, "opscode-chef-webui-nodes-environments-404" => { "message_id" => "20033", "languages" => { "en_us" => "Unable to load available recipes. Selected environment not found.", "zh_cn" => "无法找到所选环境,因此无法加载环境中的配方单。" } }, "opscode-chef-webui-nodes-recipes-404" => { "message_id" => "20034", "languages" => { "en_us" => "Unable to load expanded recipes.", "zh_cn" => "无法加载展开的配方单。" } }, "opscode-chef-webui-nodes-recipes-403" => { "message_id" => "20035", "languages" => { "en_us" => "Permission Denied. You do not have permission to expand one or more of the roles. You need read permission on the roles.", "zh_cn" => "对不起,您无权访问一个或多个角色,因此您无法查看展开的配方单。" } }, "opscode-chef-webui-users-index-403" => { "message_id" => "21001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the users in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的用户列表。" } }, "opscode-chef-webui-users-index-408" => { "message_id" => "21002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of users in this organization.", "zh_cn" => "对不起,尝试读取此组织的用户列表超时。" } }, "opscode-chef-webui-users-index-404" => { "message_id" => "21003", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到您指定的组织。" } }, "opscode-chef-webui-users-index_invites-404" => { "message_id" => "21004", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到您指定的组织。" } }, "opscode-chef-webui-users-index_invites-403" => { "message_id" => "21005", "languages" => { "en_us" => "Permission denied. You do not have permission to list the pending invites in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的邀请列表。" } }, "opscode-chef-webui-users-show-404" => { "message_id" => "21006", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-users-show-403" => { "message_id" => "21007", "languages" => { "en_us" => "Permission denied. You do not have permission to view this user's information.", "zh_cn" => "对不起,您没有权限访问此用户。" } }, "opscode-chef-webui-users-update-success" => { "message_id" => "21008", "languages" => { "en_us" => "The user profile was updated successfully.", "zh_cn" => "成功更新用户信息。" } }, "opscode-chef-webui-users-update-404" => { "message_id" => "21009", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-users-update-403" => { "message_id" => "21010", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this user.", "zh_cn" => "对不起,您没有权限修改此用户。" } }, "opscode-chef-webui-users-delete-success" => { "message_id" => "21011", "languages" => { "en_us" => "The user was deleted successfully.", "zh_cn" => "成功删除用户。" } }, "opscode-chef-webui-users-delete-404" => { "message_id" => "21012", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-users-delete-403" => { "message_id" => "21013", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this user.", "zh_cn" => "对不起,您没有权限删除此用户。" } }, "opscode-chef-webui-users-dissociate-success" => { "message_id" => "21014", "languages" => { "en_us" => "The user was dissociated successfully.", "zh_cn" => "成功关联用户。" } }, "opscode-chef-webui-users-dissociate-confirm" => { "message_id" => "21020", "languages" => { "en_us" => "Please confirm that you would like to dissociate this user from this organization.", "zh_cn" => "请确认您希望取消此用户与此组织的关联。" } }, "opscode-chef-webui-users-dissociate-404" => { "message_id" => "21015", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-users-dissociate-403" => { "message_id" => "21016", "languages" => { "en_us" => "Permission denied. You do not have permission to dissociate this user.", "zh_cn" => "对不起,您没有权限取消此用户和此组织的关联。" } }, "opscode-chef-webui-users-rescind_invite-success" => { "message_id" => "21017", "languages" => { "en_us" => "The organization invitation to the user was rescinded successfully.", "zh_cn" => "成功撤销对用户发出的邀请。" } }, "opscode-chef-webui-users-rescind_invite-404" => { "message_id" => "21018", "languages" => { "en_us" => "Invitation not found.", "zh_cn" => "无法找到邀请。" } }, "opscode-chef-webui-users-rescind_invite-403" => { "message_id" => "21019", "languages" => { "en_us" => "Permission denied. You do not have permission to rescind this invitation.", "zh_cn" => "对不起,您没有权限撤销此邀请。" } }, "opscode-chef-webui-users-rescind_invite-confirm" => { "message_id" => "21021", "languages" => { "en_us" => "Please confirm that you would like to rescind this invitation.", "zh_cn" => "请确认您希望撤销对此用户发出邀请。" } }, "opscode-chef-webui-clients-index-403" => { "message_id" => "22001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the clients in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的客户端列表。" } }, "opscode-chef-webui-clients-index-408" => { "message_id" => "22002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of clients in this organization.", "zh_cn" => "对不起,尝试读取此组织的客户端列表超时。" } }, "opscode-chef-webui-clients-edit-403" => { "message_id" => "22003", "languages" => { "en_us" => "Permission denied. You do not have permission to read this client.", "zh_cn" => "对不起,您没有权限读取此客户端。" } }, "opscode-chef-webui-clients-edit-404" => { "message_id" => "22004", "languages" => { "en_us" => "Client not found.", "zh_cn" => "无法找到客户端。" } }, "opscode-chef-webui-clients-edit-408" => { "message_id" => "22005", "languages" => { "en_us" => "Request timed out when attempting to read the client.", "zh_cn" => "对不起,尝试读取此客户端超时。" } }, "opscode-chef-webui-clients-update-success" => { "message_id" => "22006", "languages" => { "en_us" => "The client was updated successfully.", "zh_cn" => "成功更新客户端。" } }, "opscode-chef-webui-clients-update-403" => { "message_id" => "22007", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this client.", "zh_cn" => "对不起,您没有权限修改此客户端。" } }, "opscode-chef-webui-clients-update-404" => { "message_id" => "22008", "languages" => { "en_us" => "Client not found.", "zh_cn" => "无法找到客户端。" } }, "opscode-chef-webui-clients-update-408" => { "message_id" => "22009", "languages" => { "en_us" => "Request timed out when attempting to modify the client.", "zh_cn" => "对不起,尝试修改此客户端超时。" } }, "opscode-chef-webui-clients-update-409" => { "message_id" => "22010", "languages" => { "en_us" => "The new name of the client conflicts with another existing client.", "zh_cn" => "同名客户端已存在。" } }, "opscode-chef-webui-clients-update-400" => { "message_id" => "22011", "languages" => { "en_us" => "The new client name contains illegal characters. The following characters are allowed: a-z, A-Z, 0-9, _, -", "zh_cn" => "新客户端名字中含有不支持的字符。系统支持的字符包括:a-z, A-Z, 0-9, _, -。" } }, "opscode-chef-webui-clients-create-success" => { "message_id" => "22012", "languages" => { "en_us" => "The client was created successfully.", "zh_cn" => "成功创建客户端。" } }, "opscode-chef-webui-clients-private-key" => { "message_id" => "22013", "languages" => { "en_us" => "This private key will be required when you interact with Opscode Platform APIs. Opscode does not keep a copy so please store it somewhere safe.", "zh_cn" => "与Opscode平台API交互时,您将需要此私钥。请妥善保存,Opscode不会存储此私钥。" } }, "opscode-chef-webui-clients-create-400" => { "message_id" => "22014", "languages" => { "en_us" => "The new client name contains illegal characters. The following characters are allowed: a-z, A-Z, 0-9, _, -", "zh_cn" => "新客户端名字中含有不支持的字符。系统支持的字符包括:a-z, A-Z, 0-9, _, -。" } }, "opscode-chef-webui-clients-create-403" => { "message_id" => "22015", "languages" => { "en_us" => "Permission denied. You do not have permission to create a client in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的客户端。" } }, "opscode-chef-webui-clients-create-408" => { "message_id" => "22016", "languages" => { "en_us" => "Request timed out when attempting to create a new client.", "zh_cn" => "对不起,尝试创建新客户端超时。" } }, "opscode-chef-webui-clients-create-409" => { "message_id" => "22017", "languages" => { "en_us" => "A client with that name already exists.", "zh_cn" => "同名客户端已存在。" } }, "opscode-chef-webui-clients-destroy-success" => { "message_id" => "22018", "languages" => { "en_us" => "The client was deleted successfully.", "zh_cn" => "成功删除客户端。" } }, "opscode-chef-webui-clients-destroy-confirm" => { "message_id" => "22019", "languages" => { "en_us" => "Please confirm that you would like to delete this client.", "zh_cn" => "请确认您希望删除此客户端。" } }, "opscode-chef-webui-clients-destroy-403" => { "message_id" => "22020", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this client.", "zh_cn" => "对不起,您没有权限删除此客户端。" } }, "opscode-chef-webui-clients-destroy-404" => { "message_id" => "22021", "languages" => { "en_us" => "Client not found.", "zh_cn" => "无法找到客户端。" } }, "opscode-chef-webui-clients-destroy-408" => { "message_id" => "22022", "languages" => { "en_us" => "Request timed out when attempting to delete this client.", "zh_cn" => "对不起,尝试删除此客户端超时。" } }, "opscode-chef-webui-clients-container-acl-get-403" => { "message_id" => "22023", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the clients collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的客户端集合的权限设置。" } }, "opscode-chef-webui-clients-container-acl-get-408" => { "message_id" => "22024", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the clients collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的客户端集合的权限设置超时。" } }, "opscode-chef-webui-clients-container-acl-set" => { "message_id" => "22025", "languages" => { "en_us" => "Failed to set permissions on the clients collection in this organization.", "zh_cn" => "对不起,更新此组织的客户端集合的权限设置失败。" } }, "opscode-chef-webui-clients-acl-get-403" => { "message_id" => "22026", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this client.", "zh_cn" => "对不起,您没有权限读取此客户端的权限设置。" } }, "opscode-chef-webui-clients-acl-get-408" => { "message_id" => "22027", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this client.", "zh_cn" => "对不起,尝试读取客户端的权限设置超时" } }, "opscode-chef-webui-clients-acl-set" => { "message_id" => "22028", "languages" => { "en_us" => "Failed to set permissions on this client.", "zh_cn" => "对不起,更新此客户端的权限设置失败。" } }, "opscode-chef-webui-groups-index-403" => { "message_id" => "23001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the groups in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的群组列表。" } }, "opscode-chef-webui-groups-index-408" => { "message_id" => "23002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of groups in this organization.", "zh_cn" => "对不起,尝试读取此组织的群组列表超时。" } }, "opscode-chef-webui-groups-edit-403" => { "message_id" => "23003", "languages" => { "en_us" => "Permission denied. You do not have permission to read this group.", "zh_cn" => "对不起,您没有权限读取此群组。" } }, "opscode-chef-webui-groups-edit-404" => { "message_id" => "23004", "languages" => { "en_us" => "Group not found.", "zh_cn" => "无法找到群组。" } }, "opscode-chef-webui-groups-edit-408" => { "message_id" => "23005", "languages" => { "en_us" => "Request timed out when attempting to read the group.", "zh_cn" => "对不起,尝试读取此群组超时。" } }, "opscode-chef-webui-groups-show-403" => { "message_id" => "23006", "languages" => { "en_us" => "Permission denied. You do not have permission to view the group.", "zh_cn" => "对不起,您没有权限访问此群组。" } }, "opscode-chef-webui-groups-show-404" => { "message_id" => "23007", "languages" => { "en_us" => "Group not found.", "zh_cn" => "无法找到群组。" } }, "opscode-chef-webui-groups-show-408" => { "message_id" => "23008", "languages" => { "en_us" => "Request timed out when attempting to view the group.", "zh_cn" => "对不起,尝试查看节点超时。" } }, "opscode-chef-webui-groups-update-success" => { "message_id" => "23009", "languages" => { "en_us" => "The group was updated successfully.", "zh_cn" => "成功更新群组。" } }, "opscode-chef-webui-groups-update-failed-validation" => { "message_id" => "23010", "languages" => { "en_us" => "The new group name contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "新群组名字中含有不支持的字符。系统支持的字符包括:a-z, 0-9, _, -。" } }, "opscode-chef-webui-groups-update-403" => { "message_id" => "23011", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this group.", "zh_cn" => "对不起,您没有权限修改此群组。" } }, "opscode-chef-webui-groups-update-404" => { "message_id" => "23012", "languages" => { "en_us" => "Group not found.", "zh_cn" => "无法找到群组。" } }, "opscode-chef-webui-groups-update-408" => { "message_id" => "23013", "languages" => { "en_us" => "Request timed out when attempting to modify the group.", "zh_cn" => "对不起,尝试修改此群组超时。" } }, "opscode-chef-webui-groups-update-409" => { "message_id" => "23014", "languages" => { "en_us" => "The new name of the group conflicts with another existing group.", "zh_cn" => "同名群组已存在。" } }, "opscode-chef-webui-groups-create-success" => { "message_id" => "23015", "languages" => { "en_us" => "The group was created successfully.", "zh_cn" => "成功创建群组。" } }, "opscode-chef-webui-groups-create-403" => { "message_id" => "23016", "languages" => { "en_us" => "Permission denied. You do not have permission to create a group in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的群组。" } }, "opscode-chef-webui-groups-create-408" => { "message_id" => "23017", "languages" => { "en_us" => "Request timed out when attempting to create a new group.", "zh_cn" => "对不起,尝试创建新群组超时。" } }, "opscode-chef-webui-groups-create-409" => { "message_id" => "23018", "languages" => { "en_us" => "A group with that name already exists.", "zh_cn" => "同名群组已存在。" } }, "opscode-chef-webui-groups-create-failed-validation" => { "message_id" => "23019", "languages" => { "en_us" => "The new group name contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "新群组名字中含有不支持的字符。系统支持的字符包括:a-z, 0-9, _, -。" } }, "opscode-chef-webui-groups-destroy-default-groups" => { "message_id" => "23020", "languages" => { "en_us" => "Deleting the following groups is prohibited: admins, users, and clients.", "zh_cn" => "无法删除系统内建群组:admins,users,和clients。" } }, "opscode-chef-webui-groups-destroy-403" => { "message_id" => "23021", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this group.", "zh_cn" => "对不起,您没有权限删除此群组。" } }, "opscode-chef-webui-groups-destroy-404" => { "message_id" => "23022", "languages" => { "en_us" => "Group not found.", "zh_cn" => "无法找到群组。" } }, "opscode-chef-webui-groups-destroy-408" => { "message_id" => "23023", "languages" => { "en_us" => "Request timed out when attempting to delete this group.", "zh_cn" => "对不起,尝试删除此群组超时。" } }, "opscode-chef-webui-groups-destroy-success" => { "message_id" => "23024", "languages" => { "en_us" => "The group was deleted successfully.", "zh_cn" => "成功删除群组。" } }, "opscode-chef-webui-groups-destroy-confirm" => { "message_id" => "23025", "languages" => { "en_us" => "Please confirm that you would like to delete this group.", "zh_cn" => "请确认您希望删除此群组。" } }, "opscode-chef-webui-groups-acl-set" => { "message_id" => "23026", "languages" => { "en_us" => "Failed to set permissions on this group.", "zh_cn" => "对不起,更新此群组的权限设置失败。" } }, "opscode-chef-webui-groups-container-acl-get-403" => { "message_id" => "23027", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the groups collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的群组集合的权限设置。" } }, "opscode-chef-webui-groups-container-acl-get-408" => { "message_id" => "23028", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the groups collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的群组集合的权限设置超时。" } }, "opscode-chef-webui-groups-container-acl-set" => { "message_id" => "23029", "languages" => { "en_us" => "Failed to set permissions on the groups collection in this organization.", "zh_cn" => "对不起,更新此组织的群组集合的权限设置失败。" } }, "opscode-chef-webui-groups-acl-get-403" => { "message_id" => "23030", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this group.", "zh_cn" => "对不起,您没有权限读取此群组的权限设置。" } }, "opscode-chef-webui-groups-acl-get-408" => { "message_id" => "23031", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this group.", "zh_cn" => "对不起,尝试读取群组的权限设置超时" } }, "opscode-chef-webui-cookbooks-index-403" => { "message_id" => "24001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the cookbooks in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的食谱列表。" } }, "opscode-chef-webui-cookbooks-index-408" => { "message_id" => "24002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of cookbooks in this organization.", "zh_cn" => "对不起,尝试读取此组织的食谱列表超时。" } }, "opscode-chef-webui-cookbooks-show-403" => { "message_id" => "24003", "languages" => { "en_us" => "Permission denied. You do not have permission to view the cookbook.", "zh_cn" => "对不起,您没有权限查看此食谱。" } }, "opscode-chef-webui-cookbooks-show-404" => { "message_id" => "24004", "languages" => { "en_us" => "Cookbook not found.", "zh_cn" => "无法找到食谱。" } }, "opscode-chef-webui-cookbooks-show-408" => { "message_id" => "24005", "languages" => { "en_us" => "Request timed out when attempting to view the cookbook.", "zh_cn" => "对不起,尝试查看食谱超时。" } }, "opscode-chef-webui-cookbooks-container-acl-get-403" => { "message_id" => "24006", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the cookbooks collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的食谱集合的权限设置。" } }, "opscode-chef-webui-cookbooks-container-acl-get-408" => { "message_id" => "24007", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the cookbooks collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的食谱集合的权限设置超时。" } }, "opscode-chef-webui-cookbooks-container-acl-set" => { "message_id" => "24008", "languages" => { "en_us" => "Failed to set permissions on the cookbooks collection in this organization.", "zh_cn" => "对不起,更新此组织的食谱集合权限设置失败。" } }, "opscode-chef-webui-cookbooks-acl-get-403" => { "message_id" => "24009", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this cookbook.", "zh_cn" => "对不起,您没有权限读取此食谱的权限设置。" } }, "opscode-chef-webui-cookbooks-acl-get-408" => { "message_id" => "24010", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this cookbook.", "zh_cn" => "对不起,常试读去食谱的权限设置超时。" } }, "opscode-chef-webui-cookbooks-acl-set" => { "message_id" => "24011", "languages" => { "en_us" => "Failed to set permissions on this cookbook.", "zh_cn" => "对不起,更新此食谱的权限设置失败。" } }, "opscode-chef-webui-roles-show-403" => { "message_id" => "25001", "languages" => { "en_us" => "Permission denied. You do not have permission to view the role.", "zh_cn" => "对不起,您没有权限访问此角色。" } }, "opscode-chef-webui-roles-show-404" => { "message_id" => "25002", "languages" => { "en_us" => "Role not found.", "zh_cn" => "无法找到角色。" } }, "opscode-chef-webui-roles-show-408" => { "message_id" => "25003", "languages" => { "en_us" => "Request timed out when attempting to view the role.", "zh_cn" => "对不起,尝试查看角色超时。" } }, "opscode-chef-webui-roles-acl-get-403" => { "message_id" => "25004", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this role.", "zh_cn" => "对不起,您没有权限读取此角色的权限设置。" } }, "opscode-chef-webui-roles-acl-get-408" => { "message_id" => "25005", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this role.", "zh_cn" => "对不起,尝试读取角色的权限设置超时。" } }, "opscode-chef-webui-roles-acl-set" => { "message_id" => "25006", "languages" => { "en_us" => "Failed to set permissions on this role.", "zh_cn" => "对不起,更新此角色的权限设置失败。" } }, "opscode-chef-webui-roles-container-acl-get-403" => { "message_id" => "25007", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the roles collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的角色集合的权限设置。" } }, "opscode-chef-webui-roles-container-acl-get-408" => { "message_id" => "25008", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the roles collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的角色集合的权限设置超时。" } }, "opscode-chef-webui-roles-container-acl-set" => { "message_id" => "25009", "languages" => { "en_us" => "Failed to set permissions on the roles collection in this organization.", "zh_cn" => "对不起,更新此组织的角色集合的权限设置失败。" } }, "opscode-chef-webui-roles-index-403" => { "message_id" => "25010", "languages" => { "en_us" => "Permission denied. You do not have permission to list the roles in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的角色列表。" } }, "opscode-chef-webui-roles-index-408" => { "message_id" => "25011", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of roles in this organization.", "zh_cn" => "对不起,尝试读取此组织的角色列表超时。" } }, "opscode-chef-webui-roles-new-403" => { "message_id" => "25012", "languages" => { "en_us" => "Permission denied. You do not have permission to view roles and recipes in this organization. These objects are required to display the new role form.", "zh_cn" => "对不起,您没有权限查看此组织的角色和配方单,而显示新角色表单需要这些权限。" } }, "opscode-chef-webui-roles-new-408" => { "message_id" => "25013", "languages" => { "en_us" => "Request timed out when attempting to display the new role form.", "zh_cn" => "对不起,尝试显示新角色表单超时。" } }, "opscode-chef-webui-roles-edit-404" => { "message_id" => "25014", "languages" => { "en_us" => "Role not found.", "zh_cn" => "无法找到角色。" } }, "opscode-chef-webui-roles-edit-403" => { "message_id" => "25015", "languages" => { "en_us" => "Permission denied. You do not have permission to read this role or to list the roles in this organization. These rights are required to display the role edit form.", "zh_cn" => "对不起,您没有权限读取此角色或角色列表,而显示编辑角色表单需要这些权限。" } }, "opscode-chef-webui-roles-edit-408" => { "message_id" => "25016", "languages" => { "en_us" => "Request timed out when attempting to read the role or to list the organization's roles.", "zh_cn" => "对不起,尝试读取此角色或角色列表超时。" } }, "opscode-chef-webui-roles-create-success" => { "message_id" => "25017", "languages" => { "en_us" => "The role was created successfully.", "zh_cn" => "成功创建角色。" } }, "opscode-chef-webui-roles-create-failed-validation" => { "message_id" => "25018", "languages" => { "en_us" => "The new role is not formed correctly. Check for illegal characters in the role's name or body, and check that the body is formed correctly.", "zh_cn" => "新角色名字或内容中含有不支持的字符,或角色的结构不正确。" } }, "opscode-chef-webui-roles-create-409" => { "message_id" => "25019", "languages" => { "en_us" => "A role with that name already exists.", "zh_cn" => "同名角色已存在。" } }, "opscode-chef-webui-roles-create-403" => { "message_id" => "25020", "languages" => { "en_us" => "Permission denied. You do not have permission to create a role in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的角色。" } }, "opscode-chef-webui-roles-create-408" => { "message_id" => "25021", "languages" => { "en_us" => "Request timed out when attempting to create a new role.", "zh_cn" => "对不起,尝试创建新角色超时。" } }, "opscode-chef-webui-roles-update-success" => { "message_id" => "25022", "languages" => { "en_us" => "The role was updated successfully.", "zh_cn" => "成功更新角色。" } }, "opscode-chef-webui-roles-update-failed-validation" => { "message_id" => "25023", "languages" => { "en_us" => "The new role is not formed correctly. Check for illegal characters in the role's name or body, and check that the body is formed correctly.", "zh_cn" => "新角色名字或内容中含有不支持的字符,或角色的结构不正确。" } }, "opscode-chef-webui-roles-update-403" => { "message_id" => "25024", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this role.", "zh_cn" => "对不起,您没有权限修改此角色。" } }, "opscode-chef-webui-roles-update-408" => { "message_id" => "25025", "languages" => { "en_us" => "Request timed out when attempting to modify the role.", "zh_cn" => "对不起,尝试修改此角色超时。" } }, "opscode-chef-webui-roles-update-409" => { "message_id" => "25026", "languages" => { "en_us" => "The new name of the role conflicts with another existing role.", "zh_cn" => "同名角色已存在。" } }, "opscode-chef-webui-roles-update-404" => { "message_id" => "25027", "languages" => { "en_us" => "Role not found.", "zh_cn" => "无法找到角色。" } }, "opscode-chef-webui-roles-destroy-success" => { "message_id" => "25028", "languages" => { "en_us" => "The role was deleted successfully.", "zh_cn" => "成功删除角色。" } }, "opscode-chef-webui-roles-destroy-confirm" => { "message_id" => "25029", "languages" => { "en_us" => "Please confirm that you would like to delete this role.", "zh_cn" => "请确认您希望删除此角色。" } }, "opscode-chef-webui-roles-destroy-404" => { "message_id" => "25030", "languages" => { "en_us" => "Role not found.", "zh_cn" => "无法找到角色。" } }, "opscode-chef-webui-roles-destroy-403" => { "message_id" => "25031", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this role.", "zh_cn" => "对不起,您无权删除此角色。" } }, "opscode-chef-webui-role-destroy-408" => { "message_id" => "25032", "languages" => { "en_us" => "Request timed out when attempting to delete this role.", "zh_cn" => "对不起,尝试删除此角色超时。" } }, "opscode-chef-webui-roles-new-edit-environments-index-403" => { "message_id" => "25033", "languages" => { "en_us" => "You do not have permission to view environments list in this organization. Only the default run list can be edited for this role.", "zh_cn" => "您没有权限查看此组织的环境列表,因此您只能编辑此角色的默认任务清单。" } }, "opscode-chef-webui-databags-show-403" => { "message_id" => "26001", "languages" => { "en_us" => "Permission denied. You do not have permission to view the data bag.", "zh_cn" => "对不起,您没有权限访问此数据包。" } }, "opscode-chef-webui-databags-show-404" => { "message_id" => "26002", "languages" => { "en_us" => "Data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databags-show-408" => { "message_id" => "26003", "languages" => { "en_us" => "Request timed out when attempting to view the data bag.", "zh_cn" => "对不起,尝试查看数据包超时。" } }, "opscode-chef-webui-databags-acl-get-403" => { "message_id" => "26004", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this data bag.", "zh_cn" => "对不起,您没有权限读取此数据包的权限设置。" } }, "opscode-chef-webui-databags-acl-get-408" => { "message_id" => "26005", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this data bag.", "zh_cn" => "对不起,尝试读取数据包的权限设置超时。" } }, "opscode-chef-webui-databags-acl-set" => { "message_id" => "26006", "languages" => { "en_us" => "Failed to set permissions on this data bag.", "zh_cn" => "对不起,更新此数据包的权限设置失败。" } }, "opscode-chef-webui-databags-container-acl-get-403" => { "message_id" => "26007", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the data bags collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的数据包集合的权限设置。" } }, "opscode-chef-webui-databags-container-acl-get-408" => { "message_id" => "26008", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the data bags collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的数据包集合的权限设置超时。" } }, "opscode-chef-webui-databags-container-acl-set" => { "message_id" => "26009", "languages" => { "en_us" => "Failed to set permissions on the data bags collection in this organization.", "zh_cn" => "对不起,更新此组织的数据包集合的权限设置失败。" } }, "opscode-chef-webui-databags-index-403" => { "message_id" => "26010", "languages" => { "en_us" => "Permission denied. You do not have permission to list the data bags in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的数据包列表。" } }, "opscode-chef-webui-databags-index-408" => { "message_id" => "26011", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of data bags in this organization.", "zh_cn" => "对不起,尝试读取此组织的数据包列表超时。" } }, "opscode-chef-webui-databags-new-403" => { "message_id" => "26012", "languages" => { "en_us" => "Permission denied. You do not have permission to view data bags and recipes in this organization. These objects are required to display the new data bag form.", "zh_cn" => "对不起,您没有权限查看此组织的数据包和菜谱,而显示新数据包表单需要这些权限。" } }, "opscode-chef-webui-databags-new-408" => { "message_id" => "26013", "languages" => { "en_us" => "Request timed out when attempting to display the new data bag form.", "zh_cn" => "对不起,尝试显示新数据包表单超时。" } }, "opscode-chef-webui-databags-edit-404" => { "message_id" => "26014", "languages" => { "en_us" => "Data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databags-edit-403" => { "message_id" => "26015", "languages" => { "en_us" => "Permission denied. You do not have permission to read this data bag or to list the data bags in this organization. These rights are required to display the data bag edit form.", "zh_cn" => "对不起,您没有权限读取此数据包或数据包列表,而显示编辑数据包表单需要这些权限。" } }, "opscode-chef-webui-databags-edit-408" => { "message_id" => "26016", "languages" => { "en_us" => "Request timed out when attempting to read the data bag or to list the organization's data bags.", "zh_cn" => "对不起,尝试读取此数据包或数据包列表超时。" } }, "opscode-chef-webui-databags-create-success" => { "message_id" => "26017", "languages" => { "en_us" => "The data bag was created successfully.", "zh_cn" => "成功创建数据包。" } }, "opscode-chef-webui-databags-create-failed-validation" => { "message_id" => "26018", "languages" => { "en_us" => "The new data bag is not formed correctly. Check for illegal characters in the data bag's name or body, and check that the body is formed correctly.", "zh_cn" => "新数据包名字或内容中含有不支持的字符,或数据包的结构不正确。" } }, "opscode-chef-webui-databags-create-409" => { "message_id" => "26019", "languages" => { "en_us" => "A data bag with that name already exists.", "zh_cn" => "同名数据包已存在。" } }, "opscode-chef-webui-databags-create-403" => { "message_id" => "26020", "languages" => { "en_us" => "Permission denied. You do not have permission to create a data bag in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的数据包。" } }, "opscode-chef-webui-databags-create-408" => { "message_id" => "26021", "languages" => { "en_us" => "Request timed out when attempting to create a new data bag.", "zh_cn" => "对不起,尝试创建新数据包超时。" } }, "opscode-chef-webui-databags-update-success" => { "message_id" => "26022", "languages" => { "en_us" => "The data bag was updated successfully.", "zh_cn" => "成功更新数据包。" } }, "opscode-chef-webui-databags-update-failed-validation" => { "message_id" => "26023", "languages" => { "en_us" => "The new data bag is not formed correctly. Check for illegal characters in the data bag's name or body, and check that the body is formed correctly.", "zh_cn" => "新数据包名字或内容中含有不支持的字符,或数据包的结构不正确。" } }, "opscode-chef-webui-databags-update-403" => { "message_id" => "26024", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this data bag.", "zh_cn" => "对不起,您没有权限修改此数据包。" } }, "opscode-chef-webui-databags-update-408" => { "message_id" => "26025", "languages" => { "en_us" => "Request timed out when attempting to modify the data bag.", "zh_cn" => "对不起,尝试修改此数据包超时。" } }, "opscode-chef-webui-databags-update-409" => { "message_id" => "26026", "languages" => { "en_us" => "The new name of the data bag conflicts with another existing data bag.", "zh_cn" => "同名数据包已存在。" } }, "opscode-chef-webui-databags-update-404" => { "message_id" => "26027", "languages" => { "en_us" => "data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databags-destroy-success" => { "message_id" => "26028", "languages" => { "en_us" => "The data bag was deleted successfully.", "zh_cn" => "成功删除数据包。" } }, "opscode-chef-webui-databags-destroy-confirm" => { "message_id" => "26029", "languages" => { "en_us" => "Please confirm that you would like to delete this data bag.", "zh_cn" => "请确认您希望删除此数据包。" } }, "opscode-chef-webui-databags-destroy-404" => { "message_id" => "26030", "languages" => { "en_us" => "Data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databags-destroy-403" => { "message_id" => "26031", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this data bag.", "zh_cn" => "对不起,您无权删除此数据包。" } }, "opscode-chef-webui-databag-destroy-408" => { "message_id" => "26032", "languages" => { "en_us" => "Request timed out when attempting to delete this data bag.", "zh_cn" => "对不起,尝试删除此数据包超时。" } }, "opscode-chef-webui-databagitems-edit-403" => { "message_id" => "27001", "languages" => { "en_us" => "Permission denied. You do not have permission to read this data bag item or its data bag.", "zh_cn" => "对不起,您没有权限读取此数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-edit-404" => { "message_id" => "27002", "languages" => { "en_us" => "Data bag item or its data bag not found.", "zh_cn" => "无法找到数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-update-success" => { "message_id" => "27003", "languages" => { "en_us" => "The data bag item was updated successfully.", "zh_cn" => "成功更新数据包项。" } }, "opscode-chef-webui-databagitems-update-failed-validation" => { "message_id" => "27004", "languages" => { "en_us" => "The new data bag item id contains illegal characters. The following characters are allowed: a-z, A-Z, 0-9, _, -", "zh_cn" => "新数据包项名字中含有不支持的字符。系统支持的字符包括:a-z, A-Z, 0-9, _, -。" } }, "opscode-chef-webui-databagitems-update-403" => { "message_id" => "27005", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this data bag item or its data bag.", "zh_cn" => "对不起,您没有权限修改此数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitem-update-404" => { "message_id" => "27006", "languages" => { "en_us" => "Data bag item or its data bag not found.", "zh_cn" => "无法找到数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-update-409" => { "message_id" => "27007", "languages" => { "en_us" => "The new id of the data bag item conflicts with another existing data bag item.", "zh_cn" => "同名数据包项已存在。" } }, "opscode-chef-webui-databagitems-create-success" => { "message_id" => "27008", "languages" => { "en_us" => "The data bag item was created successfully.", "zh_cn" => "成功创建数据包项。" } }, "opscode-chef-webui-databagitems-create-failed-validation" => { "message_id" => "27009", "languages" => { "en_us" => "The new data bag item is not formed correctly. Check for illegal characters in the data bag item's body, and check that the body is formed correctly.", "zh_cn" => "新数据包项名字或内容中含有不支持的字符,或结构不正确。" } }, "opscode-chef-webui-databagitems-create-409" => { "message_id" => "27010", "languages" => { "en_us" => "A data bag item with that id already exists.", "zh_cn" => "同名数据包项已存在。" } }, "opscode-chef-webui-databagitems-create-403" => { "message_id" => "27011", "languages" => { "en_us" => "Permission denied. You do not have permission to create a data bag item in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的数据包项。" } }, "opscode-chef-webui-databagitems-show-404" => { "message_id" => "27012", "languages" => { "en_us" => "Data bag item or its data bag not found.", "zh_cn" => "无法找到数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-show-403" => { "message_id" => "27013", "languages" => { "en_us" => "Permission denied. You do not have permission to view the data bag item or its data bag.", "zh_cn" => "对不起,您没有权限在访问此数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-destroy-404" => { "message_id" => "27014", "languages" => { "en_us" => "Data bag item or its data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databagitems-destroy-403" => { "message_id" => "27015", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this data bag item or its data bag.", "zh_cn" => "对不起,您无权删除此数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-destroy-success" => { "message_id" => "27016", "languages" => { "en_us" => "The data bag item was deleted successfully.", "zh_cn" => "成功删除数据包项。" } }, "opscode-chef-webui-databagitems-destroy-confirm" => { "message_id" => "27017", "languages" => { "en_us" => "Please confirm that you would like to delete this data bag item.", "zh_cn" => "请确认您希望删除此数据包项。" } }, "opscode-chef-webui-application-acl-set-success" => { "message_id" => "28001", "languages" => { "en_us" => "The permissions were updated successfully.", "zh_cn" => "成功更新权限设置。" } }, "opscode-chef-webui-login-login_exists" => { "message_id" => "29001", "languages" => { "en_us" => "You are already logged in.", "zh_cn" => "您已经登录。" } }, "opscode-chef-webui-status-500" => { "message_id" => "30001", "languages" => { "en_us" => "Could not list status.", "zh_cn" => "无法显示节点状态列表。" } }, "opscode-chef-webui-search-index-500" => { "message_id" => "31001", "languages" => { "en_us" => "Could not list search indexes.", "zh_cn" => "无法显示搜索索引列表。" } }, "opscode-chef-webui-search-show-500" => { "message_id" => "31002", "languages" => { "en_us" => "Could not complete the search.", "zh_cn" => "无法完成搜索。" } }, "opscode-chef-webui-organizations-index-403" => { "message_id" => "32001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the organizations for this user.", "zh_cn" => "对不起,您没有权限查看此用户的组织列表。" } }, "opscode-chef-webui-organizations-index-408" => { "message_id" => "32002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of organizations for this user.", "zh_cn" => "对不起,尝试读取此用户的组织列表超时。" } }, "opscode-chef-webui-organizations-show-403" => { "message_id" => "32003", "languages" => { "en_us" => "Permission denied. You do not have permission to view the organization.", "zh_cn" => "对不起,您没有权限访问此组织。" } }, "opscode-chef-webui-organizations-show-404" => { "message_id" => "32004", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-chef-webui-organizations-show-408" => { "message_id" => "32005", "languages" => { "en_us" => "Request timed out when attempting to view the organizations.", "zh_cn" => "对不起,尝试查看组织超时。" } }, "opscode-chef-webui-organizations-edit-404" => { "message_id" => "32006", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-chef-webui-organizations-update-400" => { "message_id" => "32007", "languages" => { "en_us" => "The information you entered contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "您输入的信息含有不支持的字符。系统支持的字符包括:a-z, 0-9, _, -。" } }, "opscode-chef-webui-organizations-update-403" => { "message_id" => "32008", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this organization.", "zh_cn" => "对不起,您没有权限修改此组织。" } }, "opscode-chef-webui-organizations-update-404" => { "message_id" => "32009", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-chef-webui-organizations-dissociate-403" => { "message_id" => "32010", "languages" => { "en_us" => "Permission denied. You do not have permission to dissociate this organization.", "zh_cn" => "对不起,您没有权限取消此组织和此用户的关联。" } }, "opscode-chef-webui-organizations-dissociate-404" => { "message_id" => "32011", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-chef-webui-organizations-associate-empty-user" => { "message_id" => "32012", "languages" => { "en_us" => "The username field cannot be blank.", "zh_cn" => "用户名不能为空。" } }, "opscode-chef-webui-organizations-associate-no-org" => { "message_id" => "32013", "languages" => { "en_us" => "The organization field cannot be blank in the case no organization is currently selected to use.", "zh_cn" => "请指定一个组织。" } }, "opscode-chef-webui-organizations-associate-success-list" => { "message_id" => "32014", "languages" => { "en_us" => "The following users were invited successfully: ", "zh_cn" => "成功邀请以下用户:" } }, "opscode-chef-webui-organizations-associate-success-none" => { "message_id" => "32015", "languages" => { "en_us" => "No users were invited.", "zh_cn" => "没有任何用户被邀请。" } }, "opscode-chef-webui-organizations-associate-failed-user" => { "message_id" => "32016", "languages" => { "en_us" => "Could not invite the following user(s): ", "zh_cn" => "无法向这些用户发送邀请:" } }, "opscode-chef-webui-organizations-associate-notify-email-subject" => { "message_id" => "32017", "languages" => { "en_us" => "You have been invited to join the Opscode organization", "zh_cn" => "您收到一个加入Opscode组织的邀请" } }, "opscode-chef-webui-organizations-associate-success" => { "message_id" => "32018", "languages" => { "en_us" => "The user(s) were invited to the organization successfully.", "zh_cn" => "成功邀请用户加入此组织。" } }, "opscode-chef-webui-organizations-associate-400" => { "message_id" => "32019", "languages" => { "en_us" => "The information you entered contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "您输入的信息含有不支持的字符。系统支持的字符有:a-z, 0-9, _, -。" } }, "opscode-chef-webui-organizations-associate-403" => { "message_id" => "32020", "languages" => { "en_us" => "Permission denied. You do not have permission to invite the user to this organization.", "zh_cn" => "对不起,您没有权利关联此用户到此组织。" } }, "opscode-chef-webui-organizations-associate-404" => { "message_id" => "32021", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-organizations-associate-409" => { "message_id" => "32022", "languages" => { "en_us" => "The user has a pending organization invite, or has joined the orgnaization already.", "zh_cn" => "此用户尚未确认先前发送的邀请,或已经与此组织关联。" } }, "opscode-chef-webui-organizations-invite-accept" => { "message_id" => "32023", "languages" => { "en_us" => "The organization invite was accepted successfully.", "zh_cn" => "成功接受关联组织的邀请。" } }, "opscode-chef-webui-organizations-invite-accept-already" => { "message_id" => "32024", "languages" => { "en_us" => "This organization invite was accepted already.", "zh_cn" => "您已经接受过此组织的邀请。" } }, "opscode-chef-webui-organizations-invite-reject" => { "message_id" => "32025", "languages" => { "en_us" => "The organization invite was rejected successfully.", "zh_cn" => "成功拒绝邀请。" } }, "opscode-chef-webui-organizations-invite-not-found" => { "message_id" => "32026", "languages" => { "en_us" => "Organization invite not found. It may have been rescinded.", "zh_cn" => "无法找到邀请,此邀请可能已被撤销。" } }, "opscode-chef-webui-organizations-invite-accept-forbidden" => { "message_id" => "32027", "languages" => { "en_us" => "Permission denied. You do not have permission to accept this invite.", "zh_cn" => "对不起,您没有权限接受此邀请。" } }, "opscode-chef-webui-organizations-invite-reject-forbidden" => { "message_id" => "32028", "languages" => { "en_us" => "Permission denied. You do not have permission to reject this invite.", "zh_cn" => "对不起,您没有权限拒绝此邀请。" } }, "opscode-chef-webui-organizations-update-success" => { "message_id" => "32029", "languages" => { "en_us" => "The organization was updated successfully.", "zh_cn" => "成功更新此组织。" } }, "opscode-chef-webui-organizations-check_association-nil" => { "message_id" => "32030", "languages" => { "en_us" => "An organization needs to be joined and selected.", "zh_cn" => "您需要加入和选择一个组织。" } }, "opscode-chef-webui-regenerate-org-key-confirm" => { "message_id" => "32031", "languages" => { "en_us" => "Please note that any clients using your current validation key will stop working. Are you sure you want to do this?", "zh_cn" => "注意:所有正在使用现有的私钥的客户端将需要使用新的私钥,您确定要继续吗?" } }, "opscode-chef-webui-organizations-regenerate-org-key-403" => { "message_id" => "32032", "languages" => { "en_us" => "Permission denied. You do not have permission to regenerate that organization key.", "zh_cn" => "对不起,您没有权限重新生成私钥。" } }, "opscode-chef-webui-organizations-regenerate-org-key-404" => { "message_id" => "32033", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到您指定的组织。" } }, "opscode-chef-webui-organizations-create-success" => { "message_id" => "32034", "languages" => { "en_us" => "The organization was created successfully. The Management Console has been pointed to the new organization.", "zh_cn" => "成功创建新的组织。管理控制台已成功配置使用新的组织。" } }, "opscode-chef-webui-organizations-create-400" => { "message_id" => "32035", "languages" => { "en_us" => "The short name contains illegal characters. The following characters are allowed: a-z, 0-9, _, -.", "zh_cn" => "短组织名包含不支持的字符。系统支持如下字符:a-z, 0-9, _, -。" } }, "opscode-chef-webui-organizations-create-403" => { "message_id" => "32036", "languages" => { "en_us" => "Permission denied. You do not have permission to create a new organization.", "zh_cn" => "对不起,您没有权限创建新的组织。" } }, "opscode-chef-webui-organizations-create-409" => { "message_id" => "32037", "languages" => { "en_us" => "An organization with that short name already exists.", "zh_cn" => "同名(短组织名)组织已存在。" } }, "opscode-chef-webui-organizations-create-knife" => { "message_id" => "32038", "languages" => { "en_us" => "Knife is Chef's command-line tool. You can download a pre-configured copy of the configuration file.", "zh_cn" => "Knife是Chef的命令行工具,您可以在此下载它的配置文件。" } }, "opscode-chef-webui-environments-index-403" => { "message_id" => "33000", "languages" => { "en_us" => "Permission denied. You do not have permission to list the environments in this organization.", "zh_cn" => "对不起,您无权查看此组织的环境列表。" } }, "opscode-chef-webui-environments-get-env-403" => { "message_id" => "33001", "languages" => { "en_us" => "Permission denied. You do not have permission to view the environment in this organization.", "zh_cn" => "对不起,您无权查看此环境。" } }, "opscode-chef-webui-environments-get-env-404" => { "message_id" => "33002", "languages" => { "en_us" => "Environment not found.", "zh_cn" => "无法找到环境。" } }, "opscode-chef-webui-environments-destroy-confirm" => { "message_id" => "33003", "languages" => { "en_us" => "Please confirm that you would like to delete this environment.", "zh_cn" => "请确认您希望删除此环境。" } }, "opscode-chef-webui-environments-destroy-success" => { "message_id" => "33004", "languages" => { "en_us" => "The environment was deleted successfully.", "zh_cn" => "成功删除环境。" } }, "opscode-chef-webui-environments-destroy-404" => { "message_id" => "33005", "languages" => { "en_us" => "Environment not found.", "zh_cn" => "无法找到环境。" } }, "opscode-chef-webui-environments-destroy-403" => { "message_id" => "33006", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this environment.", "zh_cn" => "对不起,您无权删除此环境。" } }, "opscode-chef-webui-environments-destroy-405" => { "message_id" => "33007", "languages" => { "en_us" => "You are not allowed to delete the _default environment.", "zh_cn" => "_default环境是默认环境,不允许被删除。" } }, "opscode-chef-webui-environments-create-403" => { "message_id" => "33008", "languages" => { "en_us" => "Permission denied. You do not have permission to create a new environment in this organization.", "zh_cn" => "对不起,您无权在此组织创建新的环境。" } }, "opscode-chef-webui-environments-update-403" => { "message_id" => "33009", "languages" => { "en_us" => "Permission denied. You do not have permission to edit this environment.", "zh_cn" => "对不起,您无权编辑此环境。" } }, "opscode-chef-webui-environments-update-404" => { "message_id" => "33010", "languages" => { "en_us" => "Environment not found.", "zh_cn" => "无法找到环境。" } }, "opscode-chef-webui-environments-list-nodes-404" => { "message_id" => "33011", "languages" => { "en_us" => "Environment not found.", "zh_cn" => "无法找到环境。" } }, "opscode-chef-webui-environments-list-nodes-403" => { "message_id" => "33012", "languages" => { "en_us" => "Permission denied. You do not have permission to list nodes in this environment. You need \"read\" permission on nodes and on this environment.", "zh_cn" => "对不起,您无权查看此环境中的节点列表。您需要有对节点列表和此环境的“读”权限" } }, "opscode-chef-webui-environments-create-success" => { "message_id" => "33013", "languages" => { "en_us" => "The environment was created successfully.", "zh_cn" => "成功创建环境。" } }, "opscode-chef-webui-environments-update-success" => { "message_id" => "33014", "languages" => { "en_us" => "The environment was updated successfully.", "zh_cn" => "成功更新环境。" } }, "opscode-chef-webui-environments-acl-set" => { "message_id" => "33015", "languages" => { "en_us" => "Failed to set permissions on this environment.", "zh_cn" => "对不起,更新此环境的权限设置失败。" } }, "opscode-chef-webui-environments-acl-get-403" => { "message_id" => "33016", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this environment.", "zh_cn" => "对不起,您没有权限读取此环境的权限设置。" } }, "opscode-chef-webui-environments-container-acl-get-403" => { "message_id" => "33017", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the environments collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的环境集合的权限设置。" } }, "opscode-chef-webui-environments-container-acl-set" => { "message_id" => "33018", "languages" => { "en_us" => "Failed to set permissions on the environments collection in this organization.", "zh_cn" => "对不起,更新此组织的环境集合的权限设置失败。" } }, "opscode-chef-webui-environments-get-env-500" => { "message_id" => "33019", "languages" => { "en_us" => "There was a problem loading the environment. Please try again shortly.", "zh_cn" => "加载环境时出现系统内部问题,请稍候重试。" } }, "opscode-chef-webui-environments-load-env-filter-403" => { "message_id" => "33020", "languages" => { "en_us" => "Permission Denied. You do not have 'read' permission on the selected environment, hence no operations can be performed in this environment using the Management Console.", "zh_cn" => "对不起,您无权查看所选的环境,因此无法在此环境中进行任何操作。" } }, "opscode-chef-webui-environments-load-env-filter-404" => { "message_id" => "33021", "languages" => { "en_us" => "The selected environment no longer exists, hence no operations can be performed in this environment using the Management Console.", "zh_cn" => "对不起,无法找到所选的环境,因此无法在此环境中进行任何操作。" } }, "opscode-chef-webui-environments-default-edit-405" => { "message_id" => "33023", "languages" => { "en_us" => "The '_default' environment cannot be edited.", "zh_cn" => "_default环境为默认环境,不允许被更改。" } }, "opscode-account-organizations-404" => { "message_id" => "34000", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-account-organizations-update-403-generic" => { "message_id" => "34001", "languages" => { "en_us" => "Permission denied. You do not have permission to update this organization.", "zh_cn" => "对不起,您无权更新此组织。" } }, "opscode-account-organizations-update-403-billing" => { "message_id" => "34002", "languages" => { "en_us" => "Permission denied. You do not have permission to update the billing information for this organization.", "zh_cn" => "对不起,您无权更新此组织的支付信息。" } }, "opscode-account-organizations-update-400-invalid-billing-plan" => { "message_id" => "34003", "languages" => { "en_us" => "Invalid billing plan selected.", "zn_ch" => "对不起,您选择了无效的计费套餐。" } }, "opscode-account-organizations-update-400-chargify-error" => { "message_id" => "34004", "languages" => { "en_us" => "An error occured while updating your account information. Please check that your billing information is up to date and correct.", "zn_ch" => "对不起,更新您的账户时出错,请确认您的支付信息输入无误。" } }, "opscode-account-organizations-update-400-generic" => { "message_id" => "34005", "languages" => { "en_us" => "The information you entered contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "您输入的信息含有不支持的字符。系统支持的字符包括:a-z, 0-9, _, -。" } }, "opscode-account-organizations-update-400-chargify-unavailable" => { "message_id" => "34006", "languages" => { "en_us" => "We are unable to update your account information at this time. Please try back again shortly.", "zh_cn" => "对不起,我们无法更新您的账户信息。请稍候再试。" } } } MESSAGES_BY_ID = MESSAGES_BY_KEY.inject({}) do |memo, (k, v)| memo[v["message_id"]] = v.merge({"message_key" => k}) memo end.freeze end end end messages for quick start # -*- coding: utf-8 -*- # # Author:: Nuo Yan <nuo@opscode.com> # # Copyright 2010, Opscode, Inc. # # All rights reserved - do not redistribute # $KCODE= 'utf8' require 'mixlib/localization' module Mixlib module Localization class Messages # Retrieve the error message given the error key (e.g. 'opscode-chef-webui-nodes-403') and the language code (e.g. 'en-us') # returns the array of error code (customer support purpose) and the message. (e.g. ["a7svai98", "You are not authorized to view the node."]) def self.get_message(message_key, language_code) message_hash = self.messages[message_key.to_s] begin [message_hash["message_id"], message_hash["languages"][language_code.to_s] || message_hash["languages"]["en_us"]] rescue => e Mixlib::Localization::Log.error("Cannot find the error message with message_key #{message_key} \n #{e.message} \n #{e.backtrace.join("\n")}") raise MessageRetrievalError, "Cannot find the error message with message_key '#{message_key}'." end end # Retrieve the error message given the error key (e.g. 'opscode-chef-webui-nodes-403') and the language code (e.g. 'en-us') # returns the array of error code (customer support purpose) and the message. (e.g. ["a7svai98", "You are not authorized to view the node."]) # returns nil if message key does not exist def self.find_message(message_key, language_code="en_us") message_hash = self.messages[message_key.to_s] if message_hash [message_hash["message_id"], message_hash["languages"][language_code.to_s] || message_hash["languages"]["en_us"]] else nil end end # Retrieve the error message given the message id (e.g. '123456') and the language code (e.g. 'en-us') # returns the array of error code (customer support purpose) and the message. (e.g. ["123456", "You are not authorized to view the node."]) # raises an exception if the message id doesn't exist def self.get_message_by_id(message_id, language_code='en_us') message_hash = self.messages_by_id[message_id] if message_hash [message_hash["message_id"], message_hash["languages"][language_code.to_s] || message_hash["languages"]["en_us"]] else raise MessageRetrievalError, "Cannot find the error message with message_id '#{message_id}'." end end # Retrieve the error message given the message id (e.g. '123456') and the language code (e.g. 'en-us') # returns the array of error code (customer support purpose) and the message. (e.g. ["123456", "You are not authorized to view the node."]) # returns nil if the message id doesn't exist def self.find_message_by_id(message_id, language_code='en_us') message_hash = self.messages_by_id[message_id] if message_hash [message_hash["message_id"], message_hash["languages"][language_code.to_s] || message_hash["languages"]["en_us"]] else nil end end # Take what returns from self.get_message, and returns the formatted string. # Example: input: ["10000", "You are not authorized to view the node."], output: "Error 10000: You are not authorized to view the node." def self.parse_error_message(message_array) "#{message_array[1]} (Error #{message_array[0]})" end # Convenience method combining get_message and parse_error_message def self.get_parse_error_message(message_key, language_code) self.parse_error_message(self.get_message(message_key, language_code)) end # Take what returns from self.get_message, and returns only the message. # Example: input: ["50000", "Successfully created node."], output: "Successfully created node." def self.parse_info_message(message_array) message_array[1] end # Convenience method combining get_message and parse_error_message def self.get_parse_info_message(message_key, language_code) self.parse_info_message(self.get_message(message_key, language_code)) end # Generates a text file with message ids and the messages, Customer Service may use this file as a reference. # messages generated are not sorted (at least currently), but I don't see the need/benefits yet to make them sorted def self.generate_message_text_file(language, output_file) file = File.open(output_file, "w+") file.write("***Generated by rake generate_messages***\n\nID \t Message\n") self.messages.each_pair do |message_key, message_body| file.write("#{message_body["message_id"]} \t #{message_body["languages"][language] || message_body["languages"]["en_us"]} (internal key: #{message_key})\n") end file.close end private # # Each message is structured with 3 components: # 1. message_key: the string used in our code base to refer to this message (e.g. opscode-chef-webui-nodes-show-403) # 2. message_id: The user facing message id or error code (e.g. "10000"). It's a String, not Int. # 3. languages: the message in different languages, use the language code as the key. def self.messages MESSAGES_BY_KEY end def self.messages_by_id MESSAGES_BY_ID end MESSAGES_BY_KEY = { "opscode-chef-webui-500" => { "message_id" => "10000", "languages" => { "en_us" => "An application error has occurred. Please try again later.", "zh_cn" => "应用程序错误,请稍候重试。多谢理解。" } }, "opscode-chef-webui-login-incorrect_password" => { "message_id" => "29002", "languages" => { "en_us" => "Username and password do not match.", "zh_cn" => "用户名和密码不符。" } }, "opscode-chef-webui-nodes-show-403" => { "message_id" => "20000", "languages" => { "en_us" => "Permission denied. You do not have permission to view the node.", "zh_cn" => "对不起,您没有权限访问此节点。" } }, "opscode-chef-webui-nodes-show-404" => { "message_id" => "20001", "languages" => { "en_us" => "Node not found.", "zh_cn" => "无法找到节点。" } }, "opscode-chef-webui-nodes-show-408" => { "message_id" => "20002", "languages" => { "en_us" => "Request timed out when attempting to view the node.", "zh_cn" => "对不起,尝试查看节点超时。" } }, "opscode-chef-webui-nodes-acl-get-403" => { "message_id" => "20003", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this node.", "zh_cn" => "对不起,您没有权限读取此节点的权限设置。" } }, "opscode-chef-webui-nodes-acl-get-408" => { "message_id" => "20004", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this node.", "zh_cn" => "对不起,尝试读取节点的权限设置超时。" } }, "opscode-chef-webui-nodes-acl-set" => { "message_id" => "20005", "languages" => { "en_us" => "Failed to set permissions on this node.", "zh_cn" => "对不起,更新此节点的权限设置失败。" } }, "opscode-chef-webui-nodes-container-acl-get-403" => { "message_id" => "20006", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the nodes collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的节点集合的权限设置。" } }, "opscode-chef-webui-nodes-container-acl-get-408" => { "message_id" => "20007", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the nodes collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的节点集合的权限设置超时。" } }, "opscode-chef-webui-nodes-container-acl-set" => { "message_id" => "20008", "languages" => { "en_us" => "Failed to set permissions on the nodes collection in this organization.", "zh_cn" => "对不起,更新此组织的节点集合的权限设置失败。" } }, "opscode-chef-webui-nodes-index-403" => { "message_id" => "20009", "languages" => { "en_us" => "Permission denied. You do not have permission to list the nodes in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的节点列表。" } }, "opscode-chef-webui-nodes-index-408" => { "message_id" => "20010", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of nodes in this organization.", "zh_cn" => "对不起,尝试读取此组织的节点列表超时。" } }, "opscode-chef-webui-nodes-roles-403" => { "message_id" => "20011", "languages" => { "en_us" => "Permission denied. You do not have permission to view roles in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的角色和配方单,而显示新节点表单需要这些权限。" } }, "opscode-chef-webui-nodes-edit-404" => { "message_id" => "20013", "languages" => { "en_us" => "Node not found.", "zh_cn" => "无法找到节点。" } }, "opscode-chef-webui-nodes-edit-403" => { "message_id" => "20014", "languages" => { "en_us" => "Permission denied. You do not have permission to read this node or to list the roles in this organization. These rights are required to display the node edit form.", "zh_cn" => "对不起,您没有权限读取此节点或角色列表,而显示编辑节点表单需要这些权限。" } }, "opscode-chef-webui-nodes-edit-408" => { "message_id" => "20015", "languages" => { "en_us" => "Request timed out when attempting to read the node or to list the organization's roles.", "zh_cn" => "对不起,尝试读取此节点或角色列表超时。" } }, "opscode-chef-webui-nodes-create-success" => { "message_id" => "20016", "languages" => { "en_us" => "The node was created successfully.", "zh_cn" => "成功创建节点。" } }, "opscode-chef-webui-nodes-create-failed-validation" => { "message_id" => "20017", "languages" => { "en_us" => "The new node is not formed correctly. Check for illegal characters in the node's name or body, and check that the body is formed correctly. Only A-Z, a-z, _, -, :, and . are supported in the name.", "zh_cn" => "新节点名字或内容中含有不支持的字符,或节点的结构不正确。节点的名字只支持以下字符:A-Z, a-z, _, -, 和." } }, "opscode-chef-webui-nodes-create-409" => { "message_id" => "20018", "languages" => { "en_us" => "A node with that name already exists.", "zh_cn" => "同名节点已存在。" } }, "opscode-chef-webui-nodes-create-403" => { "message_id" => "20019", "languages" => { "en_us" => "Permission denied. You do not have permission to create a node in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的节点。" } }, "opscode-chef-webui-nodes-create-408" => { "message_id" => "20020", "languages" => { "en_us" => "Request timed out when attempting to create a new node.", "zh_cn" => "对不起,尝试创建新节点超时。" } }, "opscode-chef-webui-nodes-update-success" => { "message_id" => "20021", "languages" => { "en_us" => "The node was updated successfully.", "zh_cn" => "成功更新节点。" } }, "opscode-chef-webui-nodes-update-failed-validation" => { "message_id" => "20022", "languages" => { "en_us" => "The new node is not formed correctly. Check for illegal characters in the node's name or body, and check that the body is formed correctly.", "zh_cn" => "新节点名字或内容中含有不支持的字符,或节点的结构不正确。" } }, "opscode-chef-webui-nodes-update-403" => { "message_id" => "20023", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this node.", "zh_cn" => "对不起,您没有权限修改此节点。" } }, "opscode-chef-webui-nodes-update-408" => { "message_id" => "20024", "languages" => { "en_us" => "Request timed out when attempting to modify the node.", "zh_cn" => "对不起,尝试修改此节点超时。" } }, "opscode-chef-webui-nodes-update-409" => { "message_id" => "20025", "languages" => { "en_us" => "The new name of the node conflicts with another existing node.", "zh_cn" => "同名节点已存在。" } }, "opscode-chef-webui-nodes-update-404" => { "message_id" => "20026", "languages" => { "en_us" => "Node not found.", "zh_cn" => "无法找到节点。" } }, "opscode-chef-webui-nodes-destroy-success" => { "message_id" => "20027", "languages" => { "en_us" => "The node was deleted successfully.", "zh_cn" => "成功删除节点。" } }, "opscode-chef-webui-nodes-destroy-confirm" => { "message_id" => "20028", "languages" => { "en_us" => "Please confirm that you would like to delete this node.", "zh_cn" => "请确认您希望删除此节点。" } }, "opscode-chef-webui-nodes-destroy-404" => { "message_id" => "20029", "languages" => { "en_us" => "Node not found.", "zh_cn" => "无法找到节点。" } }, "opscode-chef-webui-nodes-destroy-403" => { "message_id" => "20030", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this node.", "zh_cn" => "对不起,您无权删除此节点。" } }, "opscode-chef-webui-nodes-destroy-408" => { "message_id" => "20031", "languages" => { "en_us" => "Request timed out when attempting to delete this node.", "zh_cn" => "对不起,尝试删除此节点超时。" } }, "opscode-chef-webui-nodes-environments-403" => { "message_id" => "20032", "languages" => { "en_us" => "Permission denied. You do not have permission to view available recipes in the selected environment in this organization.", "zh_cn" => "对不起,您无权在此组织查看此环境中的配方单。" } }, "opscode-chef-webui-nodes-environments-404" => { "message_id" => "20033", "languages" => { "en_us" => "Unable to load available recipes. Selected environment not found.", "zh_cn" => "无法找到所选环境,因此无法加载环境中的配方单。" } }, "opscode-chef-webui-nodes-recipes-404" => { "message_id" => "20034", "languages" => { "en_us" => "Unable to load expanded recipes.", "zh_cn" => "无法加载展开的配方单。" } }, "opscode-chef-webui-nodes-recipes-403" => { "message_id" => "20035", "languages" => { "en_us" => "Permission Denied. You do not have permission to expand one or more of the roles. You need read permission on the roles.", "zh_cn" => "对不起,您无权访问一个或多个角色,因此您无法查看展开的配方单。" } }, "opscode-chef-webui-users-index-403" => { "message_id" => "21001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the users in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的用户列表。" } }, "opscode-chef-webui-users-index-408" => { "message_id" => "21002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of users in this organization.", "zh_cn" => "对不起,尝试读取此组织的用户列表超时。" } }, "opscode-chef-webui-users-index-404" => { "message_id" => "21003", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到您指定的组织。" } }, "opscode-chef-webui-users-index_invites-404" => { "message_id" => "21004", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到您指定的组织。" } }, "opscode-chef-webui-users-index_invites-403" => { "message_id" => "21005", "languages" => { "en_us" => "Permission denied. You do not have permission to list the pending invites in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的邀请列表。" } }, "opscode-chef-webui-users-show-404" => { "message_id" => "21006", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-users-show-403" => { "message_id" => "21007", "languages" => { "en_us" => "Permission denied. You do not have permission to view this user's information.", "zh_cn" => "对不起,您没有权限访问此用户。" } }, "opscode-chef-webui-users-update-success" => { "message_id" => "21008", "languages" => { "en_us" => "The user profile was updated successfully.", "zh_cn" => "成功更新用户信息。" } }, "opscode-chef-webui-users-update-404" => { "message_id" => "21009", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-users-update-403" => { "message_id" => "21010", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this user.", "zh_cn" => "对不起,您没有权限修改此用户。" } }, "opscode-chef-webui-users-delete-success" => { "message_id" => "21011", "languages" => { "en_us" => "The user was deleted successfully.", "zh_cn" => "成功删除用户。" } }, "opscode-chef-webui-users-delete-404" => { "message_id" => "21012", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-users-delete-403" => { "message_id" => "21013", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this user.", "zh_cn" => "对不起,您没有权限删除此用户。" } }, "opscode-chef-webui-users-dissociate-success" => { "message_id" => "21014", "languages" => { "en_us" => "The user was dissociated successfully.", "zh_cn" => "成功关联用户。" } }, "opscode-chef-webui-users-dissociate-confirm" => { "message_id" => "21020", "languages" => { "en_us" => "Please confirm that you would like to dissociate this user from this organization.", "zh_cn" => "请确认您希望取消此用户与此组织的关联。" } }, "opscode-chef-webui-users-dissociate-404" => { "message_id" => "21015", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-users-dissociate-403" => { "message_id" => "21016", "languages" => { "en_us" => "Permission denied. You do not have permission to dissociate this user.", "zh_cn" => "对不起,您没有权限取消此用户和此组织的关联。" } }, "opscode-chef-webui-users-rescind_invite-success" => { "message_id" => "21017", "languages" => { "en_us" => "The organization invitation to the user was rescinded successfully.", "zh_cn" => "成功撤销对用户发出的邀请。" } }, "opscode-chef-webui-users-rescind_invite-404" => { "message_id" => "21018", "languages" => { "en_us" => "Invitation not found.", "zh_cn" => "无法找到邀请。" } }, "opscode-chef-webui-users-rescind_invite-403" => { "message_id" => "21019", "languages" => { "en_us" => "Permission denied. You do not have permission to rescind this invitation.", "zh_cn" => "对不起,您没有权限撤销此邀请。" } }, "opscode-chef-webui-users-rescind_invite-confirm" => { "message_id" => "21021", "languages" => { "en_us" => "Please confirm that you would like to rescind this invitation.", "zh_cn" => "请确认您希望撤销对此用户发出邀请。" } }, "opscode-chef-webui-clients-index-403" => { "message_id" => "22001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the clients in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的客户端列表。" } }, "opscode-chef-webui-clients-index-408" => { "message_id" => "22002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of clients in this organization.", "zh_cn" => "对不起,尝试读取此组织的客户端列表超时。" } }, "opscode-chef-webui-clients-edit-403" => { "message_id" => "22003", "languages" => { "en_us" => "Permission denied. You do not have permission to read this client.", "zh_cn" => "对不起,您没有权限读取此客户端。" } }, "opscode-chef-webui-clients-edit-404" => { "message_id" => "22004", "languages" => { "en_us" => "Client not found.", "zh_cn" => "无法找到客户端。" } }, "opscode-chef-webui-clients-edit-408" => { "message_id" => "22005", "languages" => { "en_us" => "Request timed out when attempting to read the client.", "zh_cn" => "对不起,尝试读取此客户端超时。" } }, "opscode-chef-webui-clients-update-success" => { "message_id" => "22006", "languages" => { "en_us" => "The client was updated successfully.", "zh_cn" => "成功更新客户端。" } }, "opscode-chef-webui-clients-update-403" => { "message_id" => "22007", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this client.", "zh_cn" => "对不起,您没有权限修改此客户端。" } }, "opscode-chef-webui-clients-update-404" => { "message_id" => "22008", "languages" => { "en_us" => "Client not found.", "zh_cn" => "无法找到客户端。" } }, "opscode-chef-webui-clients-update-408" => { "message_id" => "22009", "languages" => { "en_us" => "Request timed out when attempting to modify the client.", "zh_cn" => "对不起,尝试修改此客户端超时。" } }, "opscode-chef-webui-clients-update-409" => { "message_id" => "22010", "languages" => { "en_us" => "The new name of the client conflicts with another existing client.", "zh_cn" => "同名客户端已存在。" } }, "opscode-chef-webui-clients-update-400" => { "message_id" => "22011", "languages" => { "en_us" => "The new client name contains illegal characters. The following characters are allowed: a-z, A-Z, 0-9, _, -", "zh_cn" => "新客户端名字中含有不支持的字符。系统支持的字符包括:a-z, A-Z, 0-9, _, -。" } }, "opscode-chef-webui-clients-create-success" => { "message_id" => "22012", "languages" => { "en_us" => "The client was created successfully.", "zh_cn" => "成功创建客户端。" } }, "opscode-chef-webui-clients-private-key" => { "message_id" => "22013", "languages" => { "en_us" => "This private key will be required when you interact with Opscode Platform APIs. Opscode does not keep a copy so please store it somewhere safe.", "zh_cn" => "与Opscode平台API交互时,您将需要此私钥。请妥善保存,Opscode不会存储此私钥。" } }, "opscode-chef-webui-clients-create-400" => { "message_id" => "22014", "languages" => { "en_us" => "The new client name contains illegal characters. The following characters are allowed: a-z, A-Z, 0-9, _, -", "zh_cn" => "新客户端名字中含有不支持的字符。系统支持的字符包括:a-z, A-Z, 0-9, _, -。" } }, "opscode-chef-webui-clients-create-403" => { "message_id" => "22015", "languages" => { "en_us" => "Permission denied. You do not have permission to create a client in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的客户端。" } }, "opscode-chef-webui-clients-create-408" => { "message_id" => "22016", "languages" => { "en_us" => "Request timed out when attempting to create a new client.", "zh_cn" => "对不起,尝试创建新客户端超时。" } }, "opscode-chef-webui-clients-create-409" => { "message_id" => "22017", "languages" => { "en_us" => "A client with that name already exists.", "zh_cn" => "同名客户端已存在。" } }, "opscode-chef-webui-clients-destroy-success" => { "message_id" => "22018", "languages" => { "en_us" => "The client was deleted successfully.", "zh_cn" => "成功删除客户端。" } }, "opscode-chef-webui-clients-destroy-confirm" => { "message_id" => "22019", "languages" => { "en_us" => "Please confirm that you would like to delete this client.", "zh_cn" => "请确认您希望删除此客户端。" } }, "opscode-chef-webui-clients-destroy-403" => { "message_id" => "22020", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this client.", "zh_cn" => "对不起,您没有权限删除此客户端。" } }, "opscode-chef-webui-clients-destroy-404" => { "message_id" => "22021", "languages" => { "en_us" => "Client not found.", "zh_cn" => "无法找到客户端。" } }, "opscode-chef-webui-clients-destroy-408" => { "message_id" => "22022", "languages" => { "en_us" => "Request timed out when attempting to delete this client.", "zh_cn" => "对不起,尝试删除此客户端超时。" } }, "opscode-chef-webui-clients-container-acl-get-403" => { "message_id" => "22023", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the clients collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的客户端集合的权限设置。" } }, "opscode-chef-webui-clients-container-acl-get-408" => { "message_id" => "22024", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the clients collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的客户端集合的权限设置超时。" } }, "opscode-chef-webui-clients-container-acl-set" => { "message_id" => "22025", "languages" => { "en_us" => "Failed to set permissions on the clients collection in this organization.", "zh_cn" => "对不起,更新此组织的客户端集合的权限设置失败。" } }, "opscode-chef-webui-clients-acl-get-403" => { "message_id" => "22026", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this client.", "zh_cn" => "对不起,您没有权限读取此客户端的权限设置。" } }, "opscode-chef-webui-clients-acl-get-408" => { "message_id" => "22027", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this client.", "zh_cn" => "对不起,尝试读取客户端的权限设置超时" } }, "opscode-chef-webui-clients-acl-set" => { "message_id" => "22028", "languages" => { "en_us" => "Failed to set permissions on this client.", "zh_cn" => "对不起,更新此客户端的权限设置失败。" } }, "opscode-chef-webui-groups-index-403" => { "message_id" => "23001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the groups in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的群组列表。" } }, "opscode-chef-webui-groups-index-408" => { "message_id" => "23002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of groups in this organization.", "zh_cn" => "对不起,尝试读取此组织的群组列表超时。" } }, "opscode-chef-webui-groups-edit-403" => { "message_id" => "23003", "languages" => { "en_us" => "Permission denied. You do not have permission to read this group.", "zh_cn" => "对不起,您没有权限读取此群组。" } }, "opscode-chef-webui-groups-edit-404" => { "message_id" => "23004", "languages" => { "en_us" => "Group not found.", "zh_cn" => "无法找到群组。" } }, "opscode-chef-webui-groups-edit-408" => { "message_id" => "23005", "languages" => { "en_us" => "Request timed out when attempting to read the group.", "zh_cn" => "对不起,尝试读取此群组超时。" } }, "opscode-chef-webui-groups-show-403" => { "message_id" => "23006", "languages" => { "en_us" => "Permission denied. You do not have permission to view the group.", "zh_cn" => "对不起,您没有权限访问此群组。" } }, "opscode-chef-webui-groups-show-404" => { "message_id" => "23007", "languages" => { "en_us" => "Group not found.", "zh_cn" => "无法找到群组。" } }, "opscode-chef-webui-groups-show-408" => { "message_id" => "23008", "languages" => { "en_us" => "Request timed out when attempting to view the group.", "zh_cn" => "对不起,尝试查看节点超时。" } }, "opscode-chef-webui-groups-update-success" => { "message_id" => "23009", "languages" => { "en_us" => "The group was updated successfully.", "zh_cn" => "成功更新群组。" } }, "opscode-chef-webui-groups-update-failed-validation" => { "message_id" => "23010", "languages" => { "en_us" => "The new group name contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "新群组名字中含有不支持的字符。系统支持的字符包括:a-z, 0-9, _, -。" } }, "opscode-chef-webui-groups-update-403" => { "message_id" => "23011", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this group.", "zh_cn" => "对不起,您没有权限修改此群组。" } }, "opscode-chef-webui-groups-update-404" => { "message_id" => "23012", "languages" => { "en_us" => "Group not found.", "zh_cn" => "无法找到群组。" } }, "opscode-chef-webui-groups-update-408" => { "message_id" => "23013", "languages" => { "en_us" => "Request timed out when attempting to modify the group.", "zh_cn" => "对不起,尝试修改此群组超时。" } }, "opscode-chef-webui-groups-update-409" => { "message_id" => "23014", "languages" => { "en_us" => "The new name of the group conflicts with another existing group.", "zh_cn" => "同名群组已存在。" } }, "opscode-chef-webui-groups-create-success" => { "message_id" => "23015", "languages" => { "en_us" => "The group was created successfully.", "zh_cn" => "成功创建群组。" } }, "opscode-chef-webui-groups-create-403" => { "message_id" => "23016", "languages" => { "en_us" => "Permission denied. You do not have permission to create a group in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的群组。" } }, "opscode-chef-webui-groups-create-408" => { "message_id" => "23017", "languages" => { "en_us" => "Request timed out when attempting to create a new group.", "zh_cn" => "对不起,尝试创建新群组超时。" } }, "opscode-chef-webui-groups-create-409" => { "message_id" => "23018", "languages" => { "en_us" => "A group with that name already exists.", "zh_cn" => "同名群组已存在。" } }, "opscode-chef-webui-groups-create-failed-validation" => { "message_id" => "23019", "languages" => { "en_us" => "The new group name contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "新群组名字中含有不支持的字符。系统支持的字符包括:a-z, 0-9, _, -。" } }, "opscode-chef-webui-groups-destroy-default-groups" => { "message_id" => "23020", "languages" => { "en_us" => "Deleting the following groups is prohibited: admins, users, and clients.", "zh_cn" => "无法删除系统内建群组:admins,users,和clients。" } }, "opscode-chef-webui-groups-destroy-403" => { "message_id" => "23021", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this group.", "zh_cn" => "对不起,您没有权限删除此群组。" } }, "opscode-chef-webui-groups-destroy-404" => { "message_id" => "23022", "languages" => { "en_us" => "Group not found.", "zh_cn" => "无法找到群组。" } }, "opscode-chef-webui-groups-destroy-408" => { "message_id" => "23023", "languages" => { "en_us" => "Request timed out when attempting to delete this group.", "zh_cn" => "对不起,尝试删除此群组超时。" } }, "opscode-chef-webui-groups-destroy-success" => { "message_id" => "23024", "languages" => { "en_us" => "The group was deleted successfully.", "zh_cn" => "成功删除群组。" } }, "opscode-chef-webui-groups-destroy-confirm" => { "message_id" => "23025", "languages" => { "en_us" => "Please confirm that you would like to delete this group.", "zh_cn" => "请确认您希望删除此群组。" } }, "opscode-chef-webui-groups-acl-set" => { "message_id" => "23026", "languages" => { "en_us" => "Failed to set permissions on this group.", "zh_cn" => "对不起,更新此群组的权限设置失败。" } }, "opscode-chef-webui-groups-container-acl-get-403" => { "message_id" => "23027", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the groups collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的群组集合的权限设置。" } }, "opscode-chef-webui-groups-container-acl-get-408" => { "message_id" => "23028", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the groups collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的群组集合的权限设置超时。" } }, "opscode-chef-webui-groups-container-acl-set" => { "message_id" => "23029", "languages" => { "en_us" => "Failed to set permissions on the groups collection in this organization.", "zh_cn" => "对不起,更新此组织的群组集合的权限设置失败。" } }, "opscode-chef-webui-groups-acl-get-403" => { "message_id" => "23030", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this group.", "zh_cn" => "对不起,您没有权限读取此群组的权限设置。" } }, "opscode-chef-webui-groups-acl-get-408" => { "message_id" => "23031", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this group.", "zh_cn" => "对不起,尝试读取群组的权限设置超时" } }, "opscode-chef-webui-cookbooks-index-403" => { "message_id" => "24001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the cookbooks in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的食谱列表。" } }, "opscode-chef-webui-cookbooks-index-408" => { "message_id" => "24002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of cookbooks in this organization.", "zh_cn" => "对不起,尝试读取此组织的食谱列表超时。" } }, "opscode-chef-webui-cookbooks-show-403" => { "message_id" => "24003", "languages" => { "en_us" => "Permission denied. You do not have permission to view the cookbook.", "zh_cn" => "对不起,您没有权限查看此食谱。" } }, "opscode-chef-webui-cookbooks-show-404" => { "message_id" => "24004", "languages" => { "en_us" => "Cookbook not found.", "zh_cn" => "无法找到食谱。" } }, "opscode-chef-webui-cookbooks-show-408" => { "message_id" => "24005", "languages" => { "en_us" => "Request timed out when attempting to view the cookbook.", "zh_cn" => "对不起,尝试查看食谱超时。" } }, "opscode-chef-webui-cookbooks-container-acl-get-403" => { "message_id" => "24006", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the cookbooks collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的食谱集合的权限设置。" } }, "opscode-chef-webui-cookbooks-container-acl-get-408" => { "message_id" => "24007", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the cookbooks collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的食谱集合的权限设置超时。" } }, "opscode-chef-webui-cookbooks-container-acl-set" => { "message_id" => "24008", "languages" => { "en_us" => "Failed to set permissions on the cookbooks collection in this organization.", "zh_cn" => "对不起,更新此组织的食谱集合权限设置失败。" } }, "opscode-chef-webui-cookbooks-acl-get-403" => { "message_id" => "24009", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this cookbook.", "zh_cn" => "对不起,您没有权限读取此食谱的权限设置。" } }, "opscode-chef-webui-cookbooks-acl-get-408" => { "message_id" => "24010", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this cookbook.", "zh_cn" => "对不起,常试读去食谱的权限设置超时。" } }, "opscode-chef-webui-cookbooks-acl-set" => { "message_id" => "24011", "languages" => { "en_us" => "Failed to set permissions on this cookbook.", "zh_cn" => "对不起,更新此食谱的权限设置失败。" } }, "opscode-chef-webui-roles-show-403" => { "message_id" => "25001", "languages" => { "en_us" => "Permission denied. You do not have permission to view the role.", "zh_cn" => "对不起,您没有权限访问此角色。" } }, "opscode-chef-webui-roles-show-404" => { "message_id" => "25002", "languages" => { "en_us" => "Role not found.", "zh_cn" => "无法找到角色。" } }, "opscode-chef-webui-roles-show-408" => { "message_id" => "25003", "languages" => { "en_us" => "Request timed out when attempting to view the role.", "zh_cn" => "对不起,尝试查看角色超时。" } }, "opscode-chef-webui-roles-acl-get-403" => { "message_id" => "25004", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this role.", "zh_cn" => "对不起,您没有权限读取此角色的权限设置。" } }, "opscode-chef-webui-roles-acl-get-408" => { "message_id" => "25005", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this role.", "zh_cn" => "对不起,尝试读取角色的权限设置超时。" } }, "opscode-chef-webui-roles-acl-set" => { "message_id" => "25006", "languages" => { "en_us" => "Failed to set permissions on this role.", "zh_cn" => "对不起,更新此角色的权限设置失败。" } }, "opscode-chef-webui-roles-container-acl-get-403" => { "message_id" => "25007", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the roles collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的角色集合的权限设置。" } }, "opscode-chef-webui-roles-container-acl-get-408" => { "message_id" => "25008", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the roles collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的角色集合的权限设置超时。" } }, "opscode-chef-webui-roles-container-acl-set" => { "message_id" => "25009", "languages" => { "en_us" => "Failed to set permissions on the roles collection in this organization.", "zh_cn" => "对不起,更新此组织的角色集合的权限设置失败。" } }, "opscode-chef-webui-roles-index-403" => { "message_id" => "25010", "languages" => { "en_us" => "Permission denied. You do not have permission to list the roles in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的角色列表。" } }, "opscode-chef-webui-roles-index-408" => { "message_id" => "25011", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of roles in this organization.", "zh_cn" => "对不起,尝试读取此组织的角色列表超时。" } }, "opscode-chef-webui-roles-new-403" => { "message_id" => "25012", "languages" => { "en_us" => "Permission denied. You do not have permission to view roles and recipes in this organization. These objects are required to display the new role form.", "zh_cn" => "对不起,您没有权限查看此组织的角色和配方单,而显示新角色表单需要这些权限。" } }, "opscode-chef-webui-roles-new-408" => { "message_id" => "25013", "languages" => { "en_us" => "Request timed out when attempting to display the new role form.", "zh_cn" => "对不起,尝试显示新角色表单超时。" } }, "opscode-chef-webui-roles-edit-404" => { "message_id" => "25014", "languages" => { "en_us" => "Role not found.", "zh_cn" => "无法找到角色。" } }, "opscode-chef-webui-roles-edit-403" => { "message_id" => "25015", "languages" => { "en_us" => "Permission denied. You do not have permission to read this role or to list the roles in this organization. These rights are required to display the role edit form.", "zh_cn" => "对不起,您没有权限读取此角色或角色列表,而显示编辑角色表单需要这些权限。" } }, "opscode-chef-webui-roles-edit-408" => { "message_id" => "25016", "languages" => { "en_us" => "Request timed out when attempting to read the role or to list the organization's roles.", "zh_cn" => "对不起,尝试读取此角色或角色列表超时。" } }, "opscode-chef-webui-roles-create-success" => { "message_id" => "25017", "languages" => { "en_us" => "The role was created successfully.", "zh_cn" => "成功创建角色。" } }, "opscode-chef-webui-roles-create-failed-validation" => { "message_id" => "25018", "languages" => { "en_us" => "The new role is not formed correctly. Check for illegal characters in the role's name or body, and check that the body is formed correctly.", "zh_cn" => "新角色名字或内容中含有不支持的字符,或角色的结构不正确。" } }, "opscode-chef-webui-roles-create-409" => { "message_id" => "25019", "languages" => { "en_us" => "A role with that name already exists.", "zh_cn" => "同名角色已存在。" } }, "opscode-chef-webui-roles-create-403" => { "message_id" => "25020", "languages" => { "en_us" => "Permission denied. You do not have permission to create a role in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的角色。" } }, "opscode-chef-webui-roles-create-408" => { "message_id" => "25021", "languages" => { "en_us" => "Request timed out when attempting to create a new role.", "zh_cn" => "对不起,尝试创建新角色超时。" } }, "opscode-chef-webui-roles-update-success" => { "message_id" => "25022", "languages" => { "en_us" => "The role was updated successfully.", "zh_cn" => "成功更新角色。" } }, "opscode-chef-webui-roles-update-failed-validation" => { "message_id" => "25023", "languages" => { "en_us" => "The new role is not formed correctly. Check for illegal characters in the role's name or body, and check that the body is formed correctly.", "zh_cn" => "新角色名字或内容中含有不支持的字符,或角色的结构不正确。" } }, "opscode-chef-webui-roles-update-403" => { "message_id" => "25024", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this role.", "zh_cn" => "对不起,您没有权限修改此角色。" } }, "opscode-chef-webui-roles-update-408" => { "message_id" => "25025", "languages" => { "en_us" => "Request timed out when attempting to modify the role.", "zh_cn" => "对不起,尝试修改此角色超时。" } }, "opscode-chef-webui-roles-update-409" => { "message_id" => "25026", "languages" => { "en_us" => "The new name of the role conflicts with another existing role.", "zh_cn" => "同名角色已存在。" } }, "opscode-chef-webui-roles-update-404" => { "message_id" => "25027", "languages" => { "en_us" => "Role not found.", "zh_cn" => "无法找到角色。" } }, "opscode-chef-webui-roles-destroy-success" => { "message_id" => "25028", "languages" => { "en_us" => "The role was deleted successfully.", "zh_cn" => "成功删除角色。" } }, "opscode-chef-webui-roles-destroy-confirm" => { "message_id" => "25029", "languages" => { "en_us" => "Please confirm that you would like to delete this role.", "zh_cn" => "请确认您希望删除此角色。" } }, "opscode-chef-webui-roles-destroy-404" => { "message_id" => "25030", "languages" => { "en_us" => "Role not found.", "zh_cn" => "无法找到角色。" } }, "opscode-chef-webui-roles-destroy-403" => { "message_id" => "25031", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this role.", "zh_cn" => "对不起,您无权删除此角色。" } }, "opscode-chef-webui-role-destroy-408" => { "message_id" => "25032", "languages" => { "en_us" => "Request timed out when attempting to delete this role.", "zh_cn" => "对不起,尝试删除此角色超时。" } }, "opscode-chef-webui-roles-new-edit-environments-index-403" => { "message_id" => "25033", "languages" => { "en_us" => "You do not have permission to view environments list in this organization. Only the default run list can be edited for this role.", "zh_cn" => "您没有权限查看此组织的环境列表,因此您只能编辑此角色的默认任务清单。" } }, "opscode-chef-webui-databags-show-403" => { "message_id" => "26001", "languages" => { "en_us" => "Permission denied. You do not have permission to view the data bag.", "zh_cn" => "对不起,您没有权限访问此数据包。" } }, "opscode-chef-webui-databags-show-404" => { "message_id" => "26002", "languages" => { "en_us" => "Data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databags-show-408" => { "message_id" => "26003", "languages" => { "en_us" => "Request timed out when attempting to view the data bag.", "zh_cn" => "对不起,尝试查看数据包超时。" } }, "opscode-chef-webui-databags-acl-get-403" => { "message_id" => "26004", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this data bag.", "zh_cn" => "对不起,您没有权限读取此数据包的权限设置。" } }, "opscode-chef-webui-databags-acl-get-408" => { "message_id" => "26005", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on this data bag.", "zh_cn" => "对不起,尝试读取数据包的权限设置超时。" } }, "opscode-chef-webui-databags-acl-set" => { "message_id" => "26006", "languages" => { "en_us" => "Failed to set permissions on this data bag.", "zh_cn" => "对不起,更新此数据包的权限设置失败。" } }, "opscode-chef-webui-databags-container-acl-get-403" => { "message_id" => "26007", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the data bags collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的数据包集合的权限设置。" } }, "opscode-chef-webui-databags-container-acl-get-408" => { "message_id" => "26008", "languages" => { "en_us" => "Request timed out when attempting to read the permissions on the data bags collection in this organization.", "zh_cn" => "对不起,尝试读取此组织的数据包集合的权限设置超时。" } }, "opscode-chef-webui-databags-container-acl-set" => { "message_id" => "26009", "languages" => { "en_us" => "Failed to set permissions on the data bags collection in this organization.", "zh_cn" => "对不起,更新此组织的数据包集合的权限设置失败。" } }, "opscode-chef-webui-databags-index-403" => { "message_id" => "26010", "languages" => { "en_us" => "Permission denied. You do not have permission to list the data bags in this organization.", "zh_cn" => "对不起,您没有权限查看此组织的数据包列表。" } }, "opscode-chef-webui-databags-index-408" => { "message_id" => "26011", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of data bags in this organization.", "zh_cn" => "对不起,尝试读取此组织的数据包列表超时。" } }, "opscode-chef-webui-databags-new-403" => { "message_id" => "26012", "languages" => { "en_us" => "Permission denied. You do not have permission to view data bags and recipes in this organization. These objects are required to display the new data bag form.", "zh_cn" => "对不起,您没有权限查看此组织的数据包和菜谱,而显示新数据包表单需要这些权限。" } }, "opscode-chef-webui-databags-new-408" => { "message_id" => "26013", "languages" => { "en_us" => "Request timed out when attempting to display the new data bag form.", "zh_cn" => "对不起,尝试显示新数据包表单超时。" } }, "opscode-chef-webui-databags-edit-404" => { "message_id" => "26014", "languages" => { "en_us" => "Data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databags-edit-403" => { "message_id" => "26015", "languages" => { "en_us" => "Permission denied. You do not have permission to read this data bag or to list the data bags in this organization. These rights are required to display the data bag edit form.", "zh_cn" => "对不起,您没有权限读取此数据包或数据包列表,而显示编辑数据包表单需要这些权限。" } }, "opscode-chef-webui-databags-edit-408" => { "message_id" => "26016", "languages" => { "en_us" => "Request timed out when attempting to read the data bag or to list the organization's data bags.", "zh_cn" => "对不起,尝试读取此数据包或数据包列表超时。" } }, "opscode-chef-webui-databags-create-success" => { "message_id" => "26017", "languages" => { "en_us" => "The data bag was created successfully.", "zh_cn" => "成功创建数据包。" } }, "opscode-chef-webui-databags-create-failed-validation" => { "message_id" => "26018", "languages" => { "en_us" => "The new data bag is not formed correctly. Check for illegal characters in the data bag's name or body, and check that the body is formed correctly.", "zh_cn" => "新数据包名字或内容中含有不支持的字符,或数据包的结构不正确。" } }, "opscode-chef-webui-databags-create-409" => { "message_id" => "26019", "languages" => { "en_us" => "A data bag with that name already exists.", "zh_cn" => "同名数据包已存在。" } }, "opscode-chef-webui-databags-create-403" => { "message_id" => "26020", "languages" => { "en_us" => "Permission denied. You do not have permission to create a data bag in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的数据包。" } }, "opscode-chef-webui-databags-create-408" => { "message_id" => "26021", "languages" => { "en_us" => "Request timed out when attempting to create a new data bag.", "zh_cn" => "对不起,尝试创建新数据包超时。" } }, "opscode-chef-webui-databags-update-success" => { "message_id" => "26022", "languages" => { "en_us" => "The data bag was updated successfully.", "zh_cn" => "成功更新数据包。" } }, "opscode-chef-webui-databags-update-failed-validation" => { "message_id" => "26023", "languages" => { "en_us" => "The new data bag is not formed correctly. Check for illegal characters in the data bag's name or body, and check that the body is formed correctly.", "zh_cn" => "新数据包名字或内容中含有不支持的字符,或数据包的结构不正确。" } }, "opscode-chef-webui-databags-update-403" => { "message_id" => "26024", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this data bag.", "zh_cn" => "对不起,您没有权限修改此数据包。" } }, "opscode-chef-webui-databags-update-408" => { "message_id" => "26025", "languages" => { "en_us" => "Request timed out when attempting to modify the data bag.", "zh_cn" => "对不起,尝试修改此数据包超时。" } }, "opscode-chef-webui-databags-update-409" => { "message_id" => "26026", "languages" => { "en_us" => "The new name of the data bag conflicts with another existing data bag.", "zh_cn" => "同名数据包已存在。" } }, "opscode-chef-webui-databags-update-404" => { "message_id" => "26027", "languages" => { "en_us" => "data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databags-destroy-success" => { "message_id" => "26028", "languages" => { "en_us" => "The data bag was deleted successfully.", "zh_cn" => "成功删除数据包。" } }, "opscode-chef-webui-databags-destroy-confirm" => { "message_id" => "26029", "languages" => { "en_us" => "Please confirm that you would like to delete this data bag.", "zh_cn" => "请确认您希望删除此数据包。" } }, "opscode-chef-webui-databags-destroy-404" => { "message_id" => "26030", "languages" => { "en_us" => "Data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databags-destroy-403" => { "message_id" => "26031", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this data bag.", "zh_cn" => "对不起,您无权删除此数据包。" } }, "opscode-chef-webui-databag-destroy-408" => { "message_id" => "26032", "languages" => { "en_us" => "Request timed out when attempting to delete this data bag.", "zh_cn" => "对不起,尝试删除此数据包超时。" } }, "opscode-chef-webui-databagitems-edit-403" => { "message_id" => "27001", "languages" => { "en_us" => "Permission denied. You do not have permission to read this data bag item or its data bag.", "zh_cn" => "对不起,您没有权限读取此数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-edit-404" => { "message_id" => "27002", "languages" => { "en_us" => "Data bag item or its data bag not found.", "zh_cn" => "无法找到数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-update-success" => { "message_id" => "27003", "languages" => { "en_us" => "The data bag item was updated successfully.", "zh_cn" => "成功更新数据包项。" } }, "opscode-chef-webui-databagitems-update-failed-validation" => { "message_id" => "27004", "languages" => { "en_us" => "The new data bag item id contains illegal characters. The following characters are allowed: a-z, A-Z, 0-9, _, -", "zh_cn" => "新数据包项名字中含有不支持的字符。系统支持的字符包括:a-z, A-Z, 0-9, _, -。" } }, "opscode-chef-webui-databagitems-update-403" => { "message_id" => "27005", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this data bag item or its data bag.", "zh_cn" => "对不起,您没有权限修改此数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitem-update-404" => { "message_id" => "27006", "languages" => { "en_us" => "Data bag item or its data bag not found.", "zh_cn" => "无法找到数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-update-409" => { "message_id" => "27007", "languages" => { "en_us" => "The new id of the data bag item conflicts with another existing data bag item.", "zh_cn" => "同名数据包项已存在。" } }, "opscode-chef-webui-databagitems-create-success" => { "message_id" => "27008", "languages" => { "en_us" => "The data bag item was created successfully.", "zh_cn" => "成功创建数据包项。" } }, "opscode-chef-webui-databagitems-create-failed-validation" => { "message_id" => "27009", "languages" => { "en_us" => "The new data bag item is not formed correctly. Check for illegal characters in the data bag item's body, and check that the body is formed correctly.", "zh_cn" => "新数据包项名字或内容中含有不支持的字符,或结构不正确。" } }, "opscode-chef-webui-databagitems-create-409" => { "message_id" => "27010", "languages" => { "en_us" => "A data bag item with that id already exists.", "zh_cn" => "同名数据包项已存在。" } }, "opscode-chef-webui-databagitems-create-403" => { "message_id" => "27011", "languages" => { "en_us" => "Permission denied. You do not have permission to create a data bag item in this organization.", "zh_cn" => "对不起,您没有权限在此组织创建新的数据包项。" } }, "opscode-chef-webui-databagitems-show-404" => { "message_id" => "27012", "languages" => { "en_us" => "Data bag item or its data bag not found.", "zh_cn" => "无法找到数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-show-403" => { "message_id" => "27013", "languages" => { "en_us" => "Permission denied. You do not have permission to view the data bag item or its data bag.", "zh_cn" => "对不起,您没有权限在访问此数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-destroy-404" => { "message_id" => "27014", "languages" => { "en_us" => "Data bag item or its data bag not found.", "zh_cn" => "无法找到数据包。" } }, "opscode-chef-webui-databagitems-destroy-403" => { "message_id" => "27015", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this data bag item or its data bag.", "zh_cn" => "对不起,您无权删除此数据包项或包含它的数据包。" } }, "opscode-chef-webui-databagitems-destroy-success" => { "message_id" => "27016", "languages" => { "en_us" => "The data bag item was deleted successfully.", "zh_cn" => "成功删除数据包项。" } }, "opscode-chef-webui-databagitems-destroy-confirm" => { "message_id" => "27017", "languages" => { "en_us" => "Please confirm that you would like to delete this data bag item.", "zh_cn" => "请确认您希望删除此数据包项。" } }, "opscode-chef-webui-application-acl-set-success" => { "message_id" => "28001", "languages" => { "en_us" => "The permissions were updated successfully.", "zh_cn" => "成功更新权限设置。" } }, "opscode-chef-webui-login-login_exists" => { "message_id" => "29001", "languages" => { "en_us" => "You are already logged in.", "zh_cn" => "您已经登录。" } }, "opscode-chef-webui-status-500" => { "message_id" => "30001", "languages" => { "en_us" => "Could not list status.", "zh_cn" => "无法显示节点状态列表。" } }, "opscode-chef-webui-search-index-500" => { "message_id" => "31001", "languages" => { "en_us" => "Could not list search indexes.", "zh_cn" => "无法显示搜索索引列表。" } }, "opscode-chef-webui-search-show-500" => { "message_id" => "31002", "languages" => { "en_us" => "Could not complete the search.", "zh_cn" => "无法完成搜索。" } }, "opscode-chef-webui-organizations-index-403" => { "message_id" => "32001", "languages" => { "en_us" => "Permission denied. You do not have permission to list the organizations for this user.", "zh_cn" => "对不起,您没有权限查看此用户的组织列表。" } }, "opscode-chef-webui-organizations-index-408" => { "message_id" => "32002", "languages" => { "en_us" => "Request timed out when attempting to retrieve the list of organizations for this user.", "zh_cn" => "对不起,尝试读取此用户的组织列表超时。" } }, "opscode-chef-webui-organizations-show-403" => { "message_id" => "32003", "languages" => { "en_us" => "Permission denied. You do not have permission to view the organization.", "zh_cn" => "对不起,您没有权限访问此组织。" } }, "opscode-chef-webui-organizations-show-404" => { "message_id" => "32004", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-chef-webui-organizations-show-408" => { "message_id" => "32005", "languages" => { "en_us" => "Request timed out when attempting to view the organizations.", "zh_cn" => "对不起,尝试查看组织超时。" } }, "opscode-chef-webui-organizations-edit-404" => { "message_id" => "32006", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-chef-webui-organizations-update-400" => { "message_id" => "32007", "languages" => { "en_us" => "The information you entered contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "您输入的信息含有不支持的字符。系统支持的字符包括:a-z, 0-9, _, -。" } }, "opscode-chef-webui-organizations-update-403" => { "message_id" => "32008", "languages" => { "en_us" => "Permission denied. You do not have permission to modify this organization.", "zh_cn" => "对不起,您没有权限修改此组织。" } }, "opscode-chef-webui-organizations-update-404" => { "message_id" => "32009", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-chef-webui-organizations-dissociate-403" => { "message_id" => "32010", "languages" => { "en_us" => "Permission denied. You do not have permission to dissociate this organization.", "zh_cn" => "对不起,您没有权限取消此组织和此用户的关联。" } }, "opscode-chef-webui-organizations-dissociate-404" => { "message_id" => "32011", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-chef-webui-organizations-associate-empty-user" => { "message_id" => "32012", "languages" => { "en_us" => "The username field cannot be blank.", "zh_cn" => "用户名不能为空。" } }, "opscode-chef-webui-organizations-associate-no-org" => { "message_id" => "32013", "languages" => { "en_us" => "The organization field cannot be blank in the case no organization is currently selected to use.", "zh_cn" => "请指定一个组织。" } }, "opscode-chef-webui-organizations-associate-success-list" => { "message_id" => "32014", "languages" => { "en_us" => "The following users were invited successfully: ", "zh_cn" => "成功邀请以下用户:" } }, "opscode-chef-webui-organizations-associate-success-none" => { "message_id" => "32015", "languages" => { "en_us" => "No users were invited.", "zh_cn" => "没有任何用户被邀请。" } }, "opscode-chef-webui-organizations-associate-failed-user" => { "message_id" => "32016", "languages" => { "en_us" => "Could not invite the following user(s): ", "zh_cn" => "无法向这些用户发送邀请:" } }, "opscode-chef-webui-organizations-associate-notify-email-subject" => { "message_id" => "32017", "languages" => { "en_us" => "You have been invited to join the Opscode organization", "zh_cn" => "您收到一个加入Opscode组织的邀请" } }, "opscode-chef-webui-organizations-associate-success" => { "message_id" => "32018", "languages" => { "en_us" => "The user(s) were invited to the organization successfully.", "zh_cn" => "成功邀请用户加入此组织。" } }, "opscode-chef-webui-organizations-associate-400" => { "message_id" => "32019", "languages" => { "en_us" => "The information you entered contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "您输入的信息含有不支持的字符。系统支持的字符有:a-z, 0-9, _, -。" } }, "opscode-chef-webui-organizations-associate-403" => { "message_id" => "32020", "languages" => { "en_us" => "Permission denied. You do not have permission to invite the user to this organization.", "zh_cn" => "对不起,您没有权利关联此用户到此组织。" } }, "opscode-chef-webui-organizations-associate-404" => { "message_id" => "32021", "languages" => { "en_us" => "User not found.", "zh_cn" => "无法找到用户。" } }, "opscode-chef-webui-organizations-associate-409" => { "message_id" => "32022", "languages" => { "en_us" => "The user has a pending organization invite, or has joined the orgnaization already.", "zh_cn" => "此用户尚未确认先前发送的邀请,或已经与此组织关联。" } }, "opscode-chef-webui-organizations-invite-accept" => { "message_id" => "32023", "languages" => { "en_us" => "The organization invite was accepted successfully.", "zh_cn" => "成功接受关联组织的邀请。" } }, "opscode-chef-webui-organizations-invite-accept-already" => { "message_id" => "32024", "languages" => { "en_us" => "This organization invite was accepted already.", "zh_cn" => "您已经接受过此组织的邀请。" } }, "opscode-chef-webui-organizations-invite-reject" => { "message_id" => "32025", "languages" => { "en_us" => "The organization invite was rejected successfully.", "zh_cn" => "成功拒绝邀请。" } }, "opscode-chef-webui-organizations-invite-not-found" => { "message_id" => "32026", "languages" => { "en_us" => "Organization invite not found. It may have been rescinded.", "zh_cn" => "无法找到邀请,此邀请可能已被撤销。" } }, "opscode-chef-webui-organizations-invite-accept-forbidden" => { "message_id" => "32027", "languages" => { "en_us" => "Permission denied. You do not have permission to accept this invite.", "zh_cn" => "对不起,您没有权限接受此邀请。" } }, "opscode-chef-webui-organizations-invite-reject-forbidden" => { "message_id" => "32028", "languages" => { "en_us" => "Permission denied. You do not have permission to reject this invite.", "zh_cn" => "对不起,您没有权限拒绝此邀请。" } }, "opscode-chef-webui-organizations-update-success" => { "message_id" => "32029", "languages" => { "en_us" => "The organization was updated successfully.", "zh_cn" => "成功更新此组织。" } }, "opscode-chef-webui-organizations-check_association-nil" => { "message_id" => "32030", "languages" => { "en_us" => "An organization needs to be joined and selected.", "zh_cn" => "您需要加入和选择一个组织。" } }, "opscode-chef-webui-regenerate-org-key-confirm" => { "message_id" => "32031", "languages" => { "en_us" => "Please note that any clients using your current validation key will stop working. Are you sure you want to do this?", "zh_cn" => "注意:所有正在使用现有的私钥的客户端将需要使用新的私钥,您确定要继续吗?" } }, "opscode-chef-webui-organizations-regenerate-org-key-403" => { "message_id" => "32032", "languages" => { "en_us" => "Permission denied. You do not have permission to regenerate that organization key.", "zh_cn" => "对不起,您没有权限重新生成私钥。" } }, "opscode-chef-webui-organizations-regenerate-org-key-404" => { "message_id" => "32033", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到您指定的组织。" } }, "opscode-chef-webui-organizations-create-success" => { "message_id" => "32034", "languages" => { "en_us" => "The organization was created successfully. The Management Console has been pointed to the new organization.", "zh_cn" => "成功创建新的组织。管理控制台已成功配置使用新的组织。" } }, "opscode-chef-webui-organizations-create-400" => { "message_id" => "32035", "languages" => { "en_us" => "The short name contains illegal characters. The following characters are allowed: a-z, 0-9, _, -.", "zh_cn" => "短组织名包含不支持的字符。系统支持如下字符:a-z, 0-9, _, -。" } }, "opscode-chef-webui-organizations-create-403" => { "message_id" => "32036", "languages" => { "en_us" => "Permission denied. You do not have permission to create a new organization.", "zh_cn" => "对不起,您没有权限创建新的组织。" } }, "opscode-chef-webui-organizations-create-409" => { "message_id" => "32037", "languages" => { "en_us" => "An organization with that short name already exists.", "zh_cn" => "同名(短组织名)组织已存在。" } }, "opscode-chef-webui-organizations-create-knife" => { "message_id" => "32038", "languages" => { "en_us" => "Knife is Chef's command-line tool. You can download a pre-configured copy of the configuration file.", "zh_cn" => "Knife是Chef的命令行工具,您可以在此下载它的配置文件。" } }, "opscode-chef-webui-environments-index-403" => { "message_id" => "33000", "languages" => { "en_us" => "Permission denied. You do not have permission to list the environments in this organization.", "zh_cn" => "对不起,您无权查看此组织的环境列表。" } }, "opscode-chef-webui-environments-get-env-403" => { "message_id" => "33001", "languages" => { "en_us" => "Permission denied. You do not have permission to view the environment in this organization.", "zh_cn" => "对不起,您无权查看此环境。" } }, "opscode-chef-webui-environments-get-env-404" => { "message_id" => "33002", "languages" => { "en_us" => "Environment not found.", "zh_cn" => "无法找到环境。" } }, "opscode-chef-webui-environments-destroy-confirm" => { "message_id" => "33003", "languages" => { "en_us" => "Please confirm that you would like to delete this environment.", "zh_cn" => "请确认您希望删除此环境。" } }, "opscode-chef-webui-environments-destroy-success" => { "message_id" => "33004", "languages" => { "en_us" => "The environment was deleted successfully.", "zh_cn" => "成功删除环境。" } }, "opscode-chef-webui-environments-destroy-404" => { "message_id" => "33005", "languages" => { "en_us" => "Environment not found.", "zh_cn" => "无法找到环境。" } }, "opscode-chef-webui-environments-destroy-403" => { "message_id" => "33006", "languages" => { "en_us" => "Permission denied. You do not have permission to delete this environment.", "zh_cn" => "对不起,您无权删除此环境。" } }, "opscode-chef-webui-environments-destroy-405" => { "message_id" => "33007", "languages" => { "en_us" => "You are not allowed to delete the _default environment.", "zh_cn" => "_default环境是默认环境,不允许被删除。" } }, "opscode-chef-webui-environments-create-403" => { "message_id" => "33008", "languages" => { "en_us" => "Permission denied. You do not have permission to create a new environment in this organization.", "zh_cn" => "对不起,您无权在此组织创建新的环境。" } }, "opscode-chef-webui-environments-update-403" => { "message_id" => "33009", "languages" => { "en_us" => "Permission denied. You do not have permission to edit this environment.", "zh_cn" => "对不起,您无权编辑此环境。" } }, "opscode-chef-webui-environments-update-404" => { "message_id" => "33010", "languages" => { "en_us" => "Environment not found.", "zh_cn" => "无法找到环境。" } }, "opscode-chef-webui-environments-list-nodes-404" => { "message_id" => "33011", "languages" => { "en_us" => "Environment not found.", "zh_cn" => "无法找到环境。" } }, "opscode-chef-webui-environments-list-nodes-403" => { "message_id" => "33012", "languages" => { "en_us" => "Permission denied. You do not have permission to list nodes in this environment. You need \"read\" permission on nodes and on this environment.", "zh_cn" => "对不起,您无权查看此环境中的节点列表。您需要有对节点列表和此环境的“读”权限" } }, "opscode-chef-webui-environments-create-success" => { "message_id" => "33013", "languages" => { "en_us" => "The environment was created successfully.", "zh_cn" => "成功创建环境。" } }, "opscode-chef-webui-environments-update-success" => { "message_id" => "33014", "languages" => { "en_us" => "The environment was updated successfully.", "zh_cn" => "成功更新环境。" } }, "opscode-chef-webui-environments-acl-set" => { "message_id" => "33015", "languages" => { "en_us" => "Failed to set permissions on this environment.", "zh_cn" => "对不起,更新此环境的权限设置失败。" } }, "opscode-chef-webui-environments-acl-get-403" => { "message_id" => "33016", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on this environment.", "zh_cn" => "对不起,您没有权限读取此环境的权限设置。" } }, "opscode-chef-webui-environments-container-acl-get-403" => { "message_id" => "33017", "languages" => { "en_us" => "Permission denied. You do not have permission to read the permissions on the environments collection in this organization.", "zh_cn" => "对不起,您没有权限读取此组织的环境集合的权限设置。" } }, "opscode-chef-webui-environments-container-acl-set" => { "message_id" => "33018", "languages" => { "en_us" => "Failed to set permissions on the environments collection in this organization.", "zh_cn" => "对不起,更新此组织的环境集合的权限设置失败。" } }, "opscode-chef-webui-environments-get-env-500" => { "message_id" => "33019", "languages" => { "en_us" => "There was a problem loading the environment. Please try again shortly.", "zh_cn" => "加载环境时出现系统内部问题,请稍候重试。" } }, "opscode-chef-webui-environments-load-env-filter-403" => { "message_id" => "33020", "languages" => { "en_us" => "Permission Denied. You do not have 'read' permission on the selected environment, hence no operations can be performed in this environment using the Management Console.", "zh_cn" => "对不起,您无权查看所选的环境,因此无法在此环境中进行任何操作。" } }, "opscode-chef-webui-environments-load-env-filter-404" => { "message_id" => "33021", "languages" => { "en_us" => "The selected environment no longer exists, hence no operations can be performed in this environment using the Management Console.", "zh_cn" => "对不起,无法找到所选的环境,因此无法在此环境中进行任何操作。" } }, "opscode-chef-webui-environments-default-edit-405" => { "message_id" => "33023", "languages" => { "en_us" => "The '_default' environment cannot be edited.", "zh_cn" => "_default环境为默认环境,不允许被更改。" } }, "opscode-chef-webui-quick-start-destroy-403" => { "message_id" => "40000", "languages" => { "en_us" => "Permission Denied. You do not have permission to delete this quick start instance.", "zh_cn" => "对不起,您没有权限删除此快速开始实例。" } }, "opscode-chef-webui-quick-start-destroy-404" => { "message_id" => "40001", "languages" => { "en_us" => "Not Found. The quick start instance may have been deleted.", "zh_cn" => "无法找到此快速开始实例,它可能已经被删除。" } }, "opscode-chef-webui-quick-start-destroy-500" => { "message_id" => "40002", "languages" => { "en_us" => "An application error has occurred. Please try again later.", "zh_cn" => "应用程序错误,请稍候重试。多谢理解。" } }, "opscode-account-organizations-404" => { "message_id" => "34000", "languages" => { "en_us" => "Organization not found.", "zh_cn" => "无法找到此组织。" } }, "opscode-account-organizations-update-403-generic" => { "message_id" => "34001", "languages" => { "en_us" => "Permission denied. You do not have permission to update this organization.", "zh_cn" => "对不起,您无权更新此组织。" } }, "opscode-account-organizations-update-403-billing" => { "message_id" => "34002", "languages" => { "en_us" => "Permission denied. You do not have permission to update the billing information for this organization.", "zh_cn" => "对不起,您无权更新此组织的支付信息。" } }, "opscode-account-organizations-update-400-invalid-billing-plan" => { "message_id" => "34003", "languages" => { "en_us" => "Invalid billing plan selected.", "zn_ch" => "对不起,您选择了无效的计费套餐。" } }, "opscode-account-organizations-update-400-chargify-error" => { "message_id" => "34004", "languages" => { "en_us" => "An error occured while updating your account information. Please check that your billing information is up to date and correct.", "zn_ch" => "对不起,更新您的账户时出错,请确认您的支付信息输入无误。" } }, "opscode-account-organizations-update-400-generic" => { "message_id" => "34005", "languages" => { "en_us" => "The information you entered contains illegal characters. The following characters are allowed: a-z, 0-9, _, -", "zh_cn" => "您输入的信息含有不支持的字符。系统支持的字符包括:a-z, 0-9, _, -。" } }, "opscode-account-organizations-update-400-chargify-unavailable" => { "message_id" => "34006", "languages" => { "en_us" => "We are unable to update your account information at this time. Please try back again shortly.", "zh_cn" => "对不起,我们无法更新您的账户信息。请稍候再试。" } } } MESSAGES_BY_ID = MESSAGES_BY_KEY.inject({}) do |memo, (k, v)| memo[v["message_id"]] = v.merge({"message_key" => k}) memo end.freeze end end end
# Copyright (C) 2014-2019 MongoDB, 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. require 'mongo/server/connection_pool/populator' module Mongo class Server # Represents a connection pool for server connections. # # @since 2.0.0, largely rewritten in 2.9.0 class ConnectionPool include Loggable include Monitoring::Publishable extend Forwardable # The default max size for the connection pool. # # @since 2.9.0 DEFAULT_MAX_SIZE = 5.freeze # The default min size for the connection pool. # # @since 2.9.0 DEFAULT_MIN_SIZE = 0.freeze # The default timeout, in seconds, to wait for a connection. # # This timeout applies while in flow threads are waiting for background # threads to establish connections (and hence they must connect, handshake # and auth in the allotted time). # # It is currently set to 10 seconds. The default connect timeout is # 10 seconds by itself, but setting large timeouts can get applications # in trouble if their requests get timed out by the reverse proxy, # thus anything over 15 seconds is potentially dangerous. # # @since 2.9.0 DEFAULT_WAIT_TIMEOUT = 10.freeze # Condition variable broadcast when the size of the pool changes # to wake up the populator attr_reader :populate_semaphore # Create the new connection pool. # # @param [ Server ] server The server which this connection pool is for. # @param [ Hash ] options The connection pool options. # # @option options [ Integer ] :max_size The maximum pool size. # @option options [ Integer ] :max_pool_size Deprecated. # The maximum pool size. If max_size is also given, max_size and # max_pool_size must be identical. # @option options [ Integer ] :min_size The minimum pool size. # @option options [ Integer ] :min_pool_size Deprecated. # The minimum pool size. If min_size is also given, min_size and # min_pool_size must be identical. # @option options [ Float ] :wait_timeout The time to wait, in # seconds, for a free connection. # @option options [ Float ] :wait_queue_timeout Deprecated. # Alias for :wait_timeout. If both wait_timeout and wait_queue_timeout # are given, their values must be identical. # @option options [ Float ] :max_idle_time The time, in seconds, # after which idle connections should be closed by the pool. # Note: Additionally, options for connections created by this pool should # be included in the options passed here, and they will be forwarded to # any connections created by the pool. # # @since 2.0.0, API changed in 2.9.0 def initialize(server, options = {}) unless server.is_a?(Server) raise ArgumentError, 'First argument must be a Server instance' end options = options.dup if options[:min_size] && options[:min_pool_size] && options[:min_size] != options[:min_pool_size] raise ArgumentError, "Min size #{options[:min_size]} is not identical to min pool size #{options[:min_pool_size]}" end if options[:max_size] && options[:max_pool_size] && options[:max_size] != options[:max_pool_size] raise ArgumentError, "Max size #{options[:max_size]} is not identical to max pool size #{options[:max_pool_size]}" end if options[:wait_timeout] && options[:wait_queue_timeout] && options[:wait_timeout] != options[:wait_queue_timeout] raise ArgumentError, "Wait timeout #{options[:wait_timeout]} is not identical to wait queue timeout #{options[:wait_queue_timeout]}" end options[:min_size] ||= options[:min_pool_size] options.delete(:min_pool_size) options[:max_size] ||= options[:max_pool_size] options.delete(:max_pool_size) if options[:min_size] && options[:max_size] && options[:min_size] > options[:max_size] then raise ArgumentError, "Cannot have min size #{options[:min_size]} exceed max size #{options[:max_size]}" end if options[:wait_queue_timeout] options[:wait_timeout] ||= options[:wait_queue_timeout] end options.delete(:wait_queue_timeout) @server = server @options = options.freeze @generation = 1 @closed = false # A connection owned by this pool should be either in the # available connections array (which is used as a stack) # or in the checked out connections set. @available_connections = available_connections = [] @checked_out_connections = Set.new @pending_connections = Set.new # Mutex used for synchronizing access to @available_connections and # @checked_out_connections. The pool object is thread-safe, thus # all methods that retrieve or modify instance variables generally # must do so under this lock. @lock = Mutex.new # Condition variable broadcast when a connection is added to # @available_connections, to wake up any threads waiting for an # available connection when pool is at max size @available_semaphore = Semaphore.new # Background thread reponsible for maintaining the size of # the pool to at least min_size @populator = Populator.new(self, options) @populate_semaphore = Semaphore.new ObjectSpace.define_finalizer(self, self.class.finalize(@available_connections, @pending_connections, @populator)) publish_cmap_event( Monitoring::Event::Cmap::PoolCreated.new(@server.address, options, self) ) @populator.run! if min_size > 0 end # @return [ Hash ] options The pool options. attr_reader :options # @api private def_delegators :@server, :address # Get the maximum size of the connection pool. # # @return [ Integer ] The maximum size of the connection pool. # # @since 2.9.0 def max_size @max_size ||= options[:max_size] || [DEFAULT_MAX_SIZE, min_size].max end # Get the minimum size of the connection pool. # # @return [ Integer ] The minimum size of the connection pool. # # @since 2.9.0 def min_size @min_size ||= options[:min_size] || DEFAULT_MIN_SIZE end # The time to wait, in seconds, for a connection to become available. # # @return [ Float ] The queue wait timeout. # # @since 2.9.0 def wait_timeout @wait_timeout ||= options[:wait_timeout] || DEFAULT_WAIT_TIMEOUT end # The maximum seconds a socket can remain idle since it has been # checked in to the pool, if set. # # @return [ Float | nil ] The max socket idle time in seconds. # # @since 2.9.0 def max_idle_time @max_idle_time ||= options[:max_idle_time] end # @return [ Integer ] generation Generation of connections currently # being used by the queue. # # @since 2.9.0 # @api private attr_reader :generation # Size of the connection pool. # # Includes available and checked out connections. # # @return [ Integer ] Size of the connection pool. # # @since 2.9.0 def size raise_if_closed! @lock.synchronize do unsynchronized_size end end # Returns the size of the connection pool without acquiring the lock. # This method should only be used by other pool methods when they are # already holding the lock as Ruby does not allow a thread holding a # lock to acquire this lock again. def unsynchronized_size @available_connections.length + @checked_out_connections.length + @pending_connections.length end private :unsynchronized_size # Number of available connections in the pool. # # @return [ Integer ] Number of available connections. # # @since 2.9.0 def available_count raise_if_closed! @lock.synchronize do @available_connections.length end end # Whether the pool has been closed. # # @return [ true | false ] Whether the pool is closed. # # @since 2.9.0 def closed? !!@closed end # @note This method is experimental and subject to change. # # @api experimental # @since 2.11.0 def summary @lock.synchronize do "#<ConnectionPool size=#{unsynchronized_size} (#{min_size}-#{max_size}) " + "used=#{@checked_out_connections.length} avail=#{@available_connections.length} pending=#{@pending_connections.length}>" end end # @since 2.9.0 def_delegators :@server, :monitoring # @api private attr_reader :populator # Checks a connection out of the pool. # # If there are active connections in the pool, the most recently used # connection is returned. Otherwise if the connection pool size is less # than the max size, creates a new connection and returns it. Otherwise # waits up to the wait timeout and raises Timeout::Error if there are # still no active connections and the pool is at max size. # # The returned connection counts toward the pool's max size. When the # caller is finished using the connection, the connection should be # checked back in via the check_in method. # # @return [ Mongo::Server::Connection ] The checked out connection. # @raise [ Error::PoolClosedError ] If the pool has been closed. # @raise [ Timeout::Error ] If the connection pool is at maximum size # and remains so for longer than the wait timeout. # # @since 2.9.0 def check_out publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckOutStarted.new(@server.address) ) if closed? publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckOutFailed.new( @server.address, Monitoring::Event::Cmap::ConnectionCheckOutFailed::POOL_CLOSED ), ) raise Error::PoolClosedError.new(@server.address, self) end deadline = Time.now + wait_timeout connection = nil # It seems that synchronize sets up its own loop, thus a simple break # is insufficient to break the outer loop catch(:done) do loop do # Lock must be taken on each iteration, rather for the method # overall, otherwise other threads will not be able to check in # a connection while this thread is waiting for one. @lock.synchronize do until @available_connections.empty? connection = @available_connections.pop if connection.generation != generation # Stale connections should be disconnected in the clear # method, but if any don't, check again here connection.disconnect!(reason: :stale) @populate_semaphore.signal next end if max_idle_time && connection.last_checkin && Time.now - connection.last_checkin > max_idle_time then connection.disconnect!(reason: :idle) @populate_semaphore.signal next end @pending_connections << connection throw(:done) end # Ruby does not allow a thread to lock a mutex which it already # holds. if unsynchronized_size < max_size connection = create_connection @pending_connections << connection throw(:done) end end wait = deadline - Time.now if wait <= 0 publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckOutFailed.new( @server.address, Monitoring::Event::Cmap::ConnectionCheckOutFailed::TIMEOUT, ), ) msg = @lock.synchronize do "Timed out when attempting to check out a connection " + "from pool for #{@server.address} after #{wait_timeout} sec. " + "Connections in pool: #{@available_connections.length} available, " + "#{@checked_out_connections.length} checked out, " + "#{@pending_connections.length} pending" end raise Error::ConnectionCheckOutTimeout.new(msg, address: @server.address) end @available_semaphore.wait(wait) end end begin connect_connection(connection) rescue Exception # Handshake or authentication failed @lock.synchronize do @pending_connections.delete(connection) end @populate_semaphore.signal publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckOutFailed.new( @server.address, Monitoring::Event::Cmap::ConnectionCheckOutFailed::CONNECTION_ERROR ), ) raise end @lock.synchronize do @checked_out_connections << connection @pending_connections.delete(connection) end publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckedOut.new(@server.address, connection.id, self), ) connection end # Check a connection back into the pool. # # The connection must have been previously created by this pool. # # @param [ Mongo::Server::Connection ] connection The connection. # # @since 2.9.0 def check_in(connection) @lock.synchronize do unless connection.connection_pool == self raise ArgumentError, "Trying to check in a connection which was not checked out by this pool: #{connection} checked out from pool #{connection.connection_pool} (for #{self})" end unless @checked_out_connections.include?(connection) raise ArgumentError, "Trying to check in a connection which is not currently checked out by this pool: #{connection} (for #{self})" end # Note: if an event handler raises, resource will not be signaled. # This means threads waiting for a connection to free up when # the pool is at max size may time out. # Threads that begin waiting after this method completes (with # the exception) should be fine. @checked_out_connections.delete(connection) publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckedIn.new(@server.address, connection.id, self) ) if closed? connection.disconnect!(reason: :pool_closed) return end if connection.closed? # Connection was closed - for example, because it experienced # a network error. Nothing else needs to be done here. @populate_semaphore.signal elsif connection.generation != @generation connection.disconnect!(reason: :stale) @populate_semaphore.signal else connection.record_checkin! @available_connections << connection # Wake up only one thread waiting for an available connection, # since only one connection was checked in. @available_semaphore.signal end end end # Closes all idle connections in the pool and schedules currently checked # out connections to be closed when they are checked back into the pool. # The pool remains operational and can create new connections when # requested. # # @option options [ true | false ] :lazy If true, do not close any of # the idle connections and instead let them be closed during a # subsequent check out operation. # @option options [ true | false ] :stop_populator Whether to stop # the populator background thread. For internal driver use only. # # @return [ true ] true. # # @since 2.1.0 def clear(options = nil) raise_if_closed! if options && options[:stop_populator] stop_populator end @lock.synchronize do @generation += 1 publish_cmap_event( Monitoring::Event::Cmap::PoolCleared.new(@server.address) ) unless options && options[:lazy] until @available_connections.empty? connection = @available_connections.pop connection.disconnect!(reason: :stale) @populate_semaphore.signal end end end true end # @since 2.1.0 # @deprecated alias :disconnect! :clear # Marks the pool closed, closes all idle connections in the pool and # schedules currently checked out connections to be closed when they are # checked back into the pool. If force option is true, checked out # connections are also closed. Attempts to use the pool after it is closed # will raise Error::PoolClosedError. # # @option options [ true | false ] :force Also close all checked out # connections. # # @return [ true ] Always true. # # @since 2.9.0 def close(options = nil) return if closed? options ||= {} stop_populator @lock.synchronize do until @available_connections.empty? connection = @available_connections.pop connection.disconnect!(reason: :pool_closed) end if options[:force] until @checked_out_connections.empty? connection = @checked_out_connections.take(1).first connection.disconnect!(reason: :pool_closed) @checked_out_connections.delete(connection) end end # mark pool as closed before releasing lock so # no connections can be created, checked in, or checked out @closed = true end publish_cmap_event( Monitoring::Event::Cmap::PoolClosed.new(@server.address, self) ) true end # Get a pretty printed string inspection for the pool. # # @example Inspect the pool. # pool.inspect # # @return [ String ] The pool inspection. # # @since 2.0.0 def inspect if closed? "#<Mongo::Server::ConnectionPool:0x#{object_id} min_size=#{min_size} max_size=#{max_size} " + "wait_timeout=#{wait_timeout} closed>" else "#<Mongo::Server::ConnectionPool:0x#{object_id} min_size=#{min_size} max_size=#{max_size} " + "wait_timeout=#{wait_timeout} current_size=#{size} available=#{available_count}>" end end # Yield the block to a connection, while handling check in/check out logic. # # @example Execute with a connection. # pool.with_connection do |connection| # connection.read # end # # @return [ Object ] The result of the block. # # @since 2.0.0 def with_connection raise_if_closed! connection = check_out yield(connection) ensure if connection check_in(connection) end end # Close sockets that have been open for longer than the max idle time, # if the option is set. # # @since 2.5.0 def close_idle_sockets return if closed? return unless max_idle_time @lock.synchronize do i = 0 while i < @available_connections.length connection = @available_connections[i] if last_checkin = connection.last_checkin if (Time.now - last_checkin) > max_idle_time connection.disconnect!(reason: :idle) @available_connections.delete_at(i) @populate_semaphore.signal next end end i += 1 end end end # Stop the background populator thread and clean up any connections created # which have not been connected yet. # # Used when closing the pool or when terminating the bg thread for testing # purposes. In the latter case, this method must be called before the pool # is used, to ensure no connections in pending_connections were created in-flow # by the check_out method. # # @api private def stop_populator @populator.stop! @lock.synchronize do # If stop_populator is called while populate is running, there may be # connections waiting to be connected, connections which have not yet # been moved to available_connections, or connections moved to available_connections # but not deleted from pending_connections. These should be cleaned up. until @pending_connections.empty? connection = @pending_connections.take(1).first connection.disconnect! @pending_connections.delete(connection) end end end # Creates and adds a connection to the pool, if the pool's size is below # min_size. Retries once if a socket-related error is encountered during # this process and raises if a second error or a non socket-related error occurs. # # Used by the pool populator background thread. # # @return [ true | false ] Whether this method should be called again # to create more connections. # @raise [ Error::AuthError, Error ] The second socket-related error raised if a retry # occured, or the non socket-related error # # @api private def populate return false if closed? begin return create_and_add_connection rescue Error::SocketError, Error::SocketTimeoutError => e # an error was encountered while connecting the connection, # ignore this first error and try again. log_warn("Populator failed to connect a connection for #{address}: #{e.class}: #{e}. It will retry.") end return create_and_add_connection rescue Error::AuthError, Error # wake up one thread waiting for connections, since one could not # be created here, and can instead be created in flow @available_semaphore.signal raise end # Finalize the connection pool for garbage collection. # # @param [ List<Mongo::Connection> ] available_connections The available connections. # @param [ List<Mongo::Connection> ] pending_connections The pending connections. # @param [ Populator ] populator The populator. # # @return [ Proc ] The Finalizer. def self.finalize(available_connections, pending_connections, populator) proc do populator.stop! available_connections.each do |connection| connection.disconnect!(reason: :pool_closed) end available_connections.clear pending_connections.each do |connection| connection.disconnect!(reason: :pool_closed) end pending_connections.clear # Finalizer does not close checked out connections. # Those would have to be garbage collected on their own # and that should close them. end end private def create_connection connection = Connection.new(@server, options.merge(generation: generation, connection_pool: self)) end # Create a connection, connect it, and add it to the pool. # # @return [ true | false ] True if a connection was created and # added to the pool, false otherwise # @raise [ Mongo::Error ] An error encountered during connection connect def create_and_add_connection connection = nil @lock.synchronize do if !closed? && unsynchronized_size < min_size connection = create_connection @pending_connections << connection else return false end end begin connect_connection(connection) rescue Exception @lock.synchronize do @pending_connections.delete(connection) end raise end @lock.synchronize do @available_connections << connection @pending_connections.delete(connection) # wake up one thread waiting for connections, since one was created @available_semaphore.signal end true end # Asserts that the pool has not been closed. # # @raise [ Error::PoolClosedError ] If the pool has been closed. # # @since 2.9.0 def raise_if_closed! if closed? raise Error::PoolClosedError.new(@server.address, self) end end # Attempts to connect (handshake and auth) the connection. If an error is # encountered, closes the connection and raises the error. def connect_connection(connection) begin connection.connect! rescue Exception connection.disconnect!(reason: :error) raise end end end end end Remove unneeded "when" in exception message (#1528) # Copyright (C) 2014-2019 MongoDB, 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. require 'mongo/server/connection_pool/populator' module Mongo class Server # Represents a connection pool for server connections. # # @since 2.0.0, largely rewritten in 2.9.0 class ConnectionPool include Loggable include Monitoring::Publishable extend Forwardable # The default max size for the connection pool. # # @since 2.9.0 DEFAULT_MAX_SIZE = 5.freeze # The default min size for the connection pool. # # @since 2.9.0 DEFAULT_MIN_SIZE = 0.freeze # The default timeout, in seconds, to wait for a connection. # # This timeout applies while in flow threads are waiting for background # threads to establish connections (and hence they must connect, handshake # and auth in the allotted time). # # It is currently set to 10 seconds. The default connect timeout is # 10 seconds by itself, but setting large timeouts can get applications # in trouble if their requests get timed out by the reverse proxy, # thus anything over 15 seconds is potentially dangerous. # # @since 2.9.0 DEFAULT_WAIT_TIMEOUT = 10.freeze # Condition variable broadcast when the size of the pool changes # to wake up the populator attr_reader :populate_semaphore # Create the new connection pool. # # @param [ Server ] server The server which this connection pool is for. # @param [ Hash ] options The connection pool options. # # @option options [ Integer ] :max_size The maximum pool size. # @option options [ Integer ] :max_pool_size Deprecated. # The maximum pool size. If max_size is also given, max_size and # max_pool_size must be identical. # @option options [ Integer ] :min_size The minimum pool size. # @option options [ Integer ] :min_pool_size Deprecated. # The minimum pool size. If min_size is also given, min_size and # min_pool_size must be identical. # @option options [ Float ] :wait_timeout The time to wait, in # seconds, for a free connection. # @option options [ Float ] :wait_queue_timeout Deprecated. # Alias for :wait_timeout. If both wait_timeout and wait_queue_timeout # are given, their values must be identical. # @option options [ Float ] :max_idle_time The time, in seconds, # after which idle connections should be closed by the pool. # Note: Additionally, options for connections created by this pool should # be included in the options passed here, and they will be forwarded to # any connections created by the pool. # # @since 2.0.0, API changed in 2.9.0 def initialize(server, options = {}) unless server.is_a?(Server) raise ArgumentError, 'First argument must be a Server instance' end options = options.dup if options[:min_size] && options[:min_pool_size] && options[:min_size] != options[:min_pool_size] raise ArgumentError, "Min size #{options[:min_size]} is not identical to min pool size #{options[:min_pool_size]}" end if options[:max_size] && options[:max_pool_size] && options[:max_size] != options[:max_pool_size] raise ArgumentError, "Max size #{options[:max_size]} is not identical to max pool size #{options[:max_pool_size]}" end if options[:wait_timeout] && options[:wait_queue_timeout] && options[:wait_timeout] != options[:wait_queue_timeout] raise ArgumentError, "Wait timeout #{options[:wait_timeout]} is not identical to wait queue timeout #{options[:wait_queue_timeout]}" end options[:min_size] ||= options[:min_pool_size] options.delete(:min_pool_size) options[:max_size] ||= options[:max_pool_size] options.delete(:max_pool_size) if options[:min_size] && options[:max_size] && options[:min_size] > options[:max_size] then raise ArgumentError, "Cannot have min size #{options[:min_size]} exceed max size #{options[:max_size]}" end if options[:wait_queue_timeout] options[:wait_timeout] ||= options[:wait_queue_timeout] end options.delete(:wait_queue_timeout) @server = server @options = options.freeze @generation = 1 @closed = false # A connection owned by this pool should be either in the # available connections array (which is used as a stack) # or in the checked out connections set. @available_connections = available_connections = [] @checked_out_connections = Set.new @pending_connections = Set.new # Mutex used for synchronizing access to @available_connections and # @checked_out_connections. The pool object is thread-safe, thus # all methods that retrieve or modify instance variables generally # must do so under this lock. @lock = Mutex.new # Condition variable broadcast when a connection is added to # @available_connections, to wake up any threads waiting for an # available connection when pool is at max size @available_semaphore = Semaphore.new # Background thread reponsible for maintaining the size of # the pool to at least min_size @populator = Populator.new(self, options) @populate_semaphore = Semaphore.new ObjectSpace.define_finalizer(self, self.class.finalize(@available_connections, @pending_connections, @populator)) publish_cmap_event( Monitoring::Event::Cmap::PoolCreated.new(@server.address, options, self) ) @populator.run! if min_size > 0 end # @return [ Hash ] options The pool options. attr_reader :options # @api private def_delegators :@server, :address # Get the maximum size of the connection pool. # # @return [ Integer ] The maximum size of the connection pool. # # @since 2.9.0 def max_size @max_size ||= options[:max_size] || [DEFAULT_MAX_SIZE, min_size].max end # Get the minimum size of the connection pool. # # @return [ Integer ] The minimum size of the connection pool. # # @since 2.9.0 def min_size @min_size ||= options[:min_size] || DEFAULT_MIN_SIZE end # The time to wait, in seconds, for a connection to become available. # # @return [ Float ] The queue wait timeout. # # @since 2.9.0 def wait_timeout @wait_timeout ||= options[:wait_timeout] || DEFAULT_WAIT_TIMEOUT end # The maximum seconds a socket can remain idle since it has been # checked in to the pool, if set. # # @return [ Float | nil ] The max socket idle time in seconds. # # @since 2.9.0 def max_idle_time @max_idle_time ||= options[:max_idle_time] end # @return [ Integer ] generation Generation of connections currently # being used by the queue. # # @since 2.9.0 # @api private attr_reader :generation # Size of the connection pool. # # Includes available and checked out connections. # # @return [ Integer ] Size of the connection pool. # # @since 2.9.0 def size raise_if_closed! @lock.synchronize do unsynchronized_size end end # Returns the size of the connection pool without acquiring the lock. # This method should only be used by other pool methods when they are # already holding the lock as Ruby does not allow a thread holding a # lock to acquire this lock again. def unsynchronized_size @available_connections.length + @checked_out_connections.length + @pending_connections.length end private :unsynchronized_size # Number of available connections in the pool. # # @return [ Integer ] Number of available connections. # # @since 2.9.0 def available_count raise_if_closed! @lock.synchronize do @available_connections.length end end # Whether the pool has been closed. # # @return [ true | false ] Whether the pool is closed. # # @since 2.9.0 def closed? !!@closed end # @note This method is experimental and subject to change. # # @api experimental # @since 2.11.0 def summary @lock.synchronize do "#<ConnectionPool size=#{unsynchronized_size} (#{min_size}-#{max_size}) " + "used=#{@checked_out_connections.length} avail=#{@available_connections.length} pending=#{@pending_connections.length}>" end end # @since 2.9.0 def_delegators :@server, :monitoring # @api private attr_reader :populator # Checks a connection out of the pool. # # If there are active connections in the pool, the most recently used # connection is returned. Otherwise if the connection pool size is less # than the max size, creates a new connection and returns it. Otherwise # waits up to the wait timeout and raises Timeout::Error if there are # still no active connections and the pool is at max size. # # The returned connection counts toward the pool's max size. When the # caller is finished using the connection, the connection should be # checked back in via the check_in method. # # @return [ Mongo::Server::Connection ] The checked out connection. # @raise [ Error::PoolClosedError ] If the pool has been closed. # @raise [ Timeout::Error ] If the connection pool is at maximum size # and remains so for longer than the wait timeout. # # @since 2.9.0 def check_out publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckOutStarted.new(@server.address) ) if closed? publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckOutFailed.new( @server.address, Monitoring::Event::Cmap::ConnectionCheckOutFailed::POOL_CLOSED ), ) raise Error::PoolClosedError.new(@server.address, self) end deadline = Time.now + wait_timeout connection = nil # It seems that synchronize sets up its own loop, thus a simple break # is insufficient to break the outer loop catch(:done) do loop do # Lock must be taken on each iteration, rather for the method # overall, otherwise other threads will not be able to check in # a connection while this thread is waiting for one. @lock.synchronize do until @available_connections.empty? connection = @available_connections.pop if connection.generation != generation # Stale connections should be disconnected in the clear # method, but if any don't, check again here connection.disconnect!(reason: :stale) @populate_semaphore.signal next end if max_idle_time && connection.last_checkin && Time.now - connection.last_checkin > max_idle_time then connection.disconnect!(reason: :idle) @populate_semaphore.signal next end @pending_connections << connection throw(:done) end # Ruby does not allow a thread to lock a mutex which it already # holds. if unsynchronized_size < max_size connection = create_connection @pending_connections << connection throw(:done) end end wait = deadline - Time.now if wait <= 0 publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckOutFailed.new( @server.address, Monitoring::Event::Cmap::ConnectionCheckOutFailed::TIMEOUT, ), ) msg = @lock.synchronize do "Timed out attempting to check out a connection " + "from pool for #{@server.address} after #{wait_timeout} sec. " + "Connections in pool: #{@available_connections.length} available, " + "#{@checked_out_connections.length} checked out, " + "#{@pending_connections.length} pending" end raise Error::ConnectionCheckOutTimeout.new(msg, address: @server.address) end @available_semaphore.wait(wait) end end begin connect_connection(connection) rescue Exception # Handshake or authentication failed @lock.synchronize do @pending_connections.delete(connection) end @populate_semaphore.signal publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckOutFailed.new( @server.address, Monitoring::Event::Cmap::ConnectionCheckOutFailed::CONNECTION_ERROR ), ) raise end @lock.synchronize do @checked_out_connections << connection @pending_connections.delete(connection) end publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckedOut.new(@server.address, connection.id, self), ) connection end # Check a connection back into the pool. # # The connection must have been previously created by this pool. # # @param [ Mongo::Server::Connection ] connection The connection. # # @since 2.9.0 def check_in(connection) @lock.synchronize do unless connection.connection_pool == self raise ArgumentError, "Trying to check in a connection which was not checked out by this pool: #{connection} checked out from pool #{connection.connection_pool} (for #{self})" end unless @checked_out_connections.include?(connection) raise ArgumentError, "Trying to check in a connection which is not currently checked out by this pool: #{connection} (for #{self})" end # Note: if an event handler raises, resource will not be signaled. # This means threads waiting for a connection to free up when # the pool is at max size may time out. # Threads that begin waiting after this method completes (with # the exception) should be fine. @checked_out_connections.delete(connection) publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckedIn.new(@server.address, connection.id, self) ) if closed? connection.disconnect!(reason: :pool_closed) return end if connection.closed? # Connection was closed - for example, because it experienced # a network error. Nothing else needs to be done here. @populate_semaphore.signal elsif connection.generation != @generation connection.disconnect!(reason: :stale) @populate_semaphore.signal else connection.record_checkin! @available_connections << connection # Wake up only one thread waiting for an available connection, # since only one connection was checked in. @available_semaphore.signal end end end # Closes all idle connections in the pool and schedules currently checked # out connections to be closed when they are checked back into the pool. # The pool remains operational and can create new connections when # requested. # # @option options [ true | false ] :lazy If true, do not close any of # the idle connections and instead let them be closed during a # subsequent check out operation. # @option options [ true | false ] :stop_populator Whether to stop # the populator background thread. For internal driver use only. # # @return [ true ] true. # # @since 2.1.0 def clear(options = nil) raise_if_closed! if options && options[:stop_populator] stop_populator end @lock.synchronize do @generation += 1 publish_cmap_event( Monitoring::Event::Cmap::PoolCleared.new(@server.address) ) unless options && options[:lazy] until @available_connections.empty? connection = @available_connections.pop connection.disconnect!(reason: :stale) @populate_semaphore.signal end end end true end # @since 2.1.0 # @deprecated alias :disconnect! :clear # Marks the pool closed, closes all idle connections in the pool and # schedules currently checked out connections to be closed when they are # checked back into the pool. If force option is true, checked out # connections are also closed. Attempts to use the pool after it is closed # will raise Error::PoolClosedError. # # @option options [ true | false ] :force Also close all checked out # connections. # # @return [ true ] Always true. # # @since 2.9.0 def close(options = nil) return if closed? options ||= {} stop_populator @lock.synchronize do until @available_connections.empty? connection = @available_connections.pop connection.disconnect!(reason: :pool_closed) end if options[:force] until @checked_out_connections.empty? connection = @checked_out_connections.take(1).first connection.disconnect!(reason: :pool_closed) @checked_out_connections.delete(connection) end end # mark pool as closed before releasing lock so # no connections can be created, checked in, or checked out @closed = true end publish_cmap_event( Monitoring::Event::Cmap::PoolClosed.new(@server.address, self) ) true end # Get a pretty printed string inspection for the pool. # # @example Inspect the pool. # pool.inspect # # @return [ String ] The pool inspection. # # @since 2.0.0 def inspect if closed? "#<Mongo::Server::ConnectionPool:0x#{object_id} min_size=#{min_size} max_size=#{max_size} " + "wait_timeout=#{wait_timeout} closed>" else "#<Mongo::Server::ConnectionPool:0x#{object_id} min_size=#{min_size} max_size=#{max_size} " + "wait_timeout=#{wait_timeout} current_size=#{size} available=#{available_count}>" end end # Yield the block to a connection, while handling check in/check out logic. # # @example Execute with a connection. # pool.with_connection do |connection| # connection.read # end # # @return [ Object ] The result of the block. # # @since 2.0.0 def with_connection raise_if_closed! connection = check_out yield(connection) ensure if connection check_in(connection) end end # Close sockets that have been open for longer than the max idle time, # if the option is set. # # @since 2.5.0 def close_idle_sockets return if closed? return unless max_idle_time @lock.synchronize do i = 0 while i < @available_connections.length connection = @available_connections[i] if last_checkin = connection.last_checkin if (Time.now - last_checkin) > max_idle_time connection.disconnect!(reason: :idle) @available_connections.delete_at(i) @populate_semaphore.signal next end end i += 1 end end end # Stop the background populator thread and clean up any connections created # which have not been connected yet. # # Used when closing the pool or when terminating the bg thread for testing # purposes. In the latter case, this method must be called before the pool # is used, to ensure no connections in pending_connections were created in-flow # by the check_out method. # # @api private def stop_populator @populator.stop! @lock.synchronize do # If stop_populator is called while populate is running, there may be # connections waiting to be connected, connections which have not yet # been moved to available_connections, or connections moved to available_connections # but not deleted from pending_connections. These should be cleaned up. until @pending_connections.empty? connection = @pending_connections.take(1).first connection.disconnect! @pending_connections.delete(connection) end end end # Creates and adds a connection to the pool, if the pool's size is below # min_size. Retries once if a socket-related error is encountered during # this process and raises if a second error or a non socket-related error occurs. # # Used by the pool populator background thread. # # @return [ true | false ] Whether this method should be called again # to create more connections. # @raise [ Error::AuthError, Error ] The second socket-related error raised if a retry # occured, or the non socket-related error # # @api private def populate return false if closed? begin return create_and_add_connection rescue Error::SocketError, Error::SocketTimeoutError => e # an error was encountered while connecting the connection, # ignore this first error and try again. log_warn("Populator failed to connect a connection for #{address}: #{e.class}: #{e}. It will retry.") end return create_and_add_connection rescue Error::AuthError, Error # wake up one thread waiting for connections, since one could not # be created here, and can instead be created in flow @available_semaphore.signal raise end # Finalize the connection pool for garbage collection. # # @param [ List<Mongo::Connection> ] available_connections The available connections. # @param [ List<Mongo::Connection> ] pending_connections The pending connections. # @param [ Populator ] populator The populator. # # @return [ Proc ] The Finalizer. def self.finalize(available_connections, pending_connections, populator) proc do populator.stop! available_connections.each do |connection| connection.disconnect!(reason: :pool_closed) end available_connections.clear pending_connections.each do |connection| connection.disconnect!(reason: :pool_closed) end pending_connections.clear # Finalizer does not close checked out connections. # Those would have to be garbage collected on their own # and that should close them. end end private def create_connection connection = Connection.new(@server, options.merge(generation: generation, connection_pool: self)) end # Create a connection, connect it, and add it to the pool. # # @return [ true | false ] True if a connection was created and # added to the pool, false otherwise # @raise [ Mongo::Error ] An error encountered during connection connect def create_and_add_connection connection = nil @lock.synchronize do if !closed? && unsynchronized_size < min_size connection = create_connection @pending_connections << connection else return false end end begin connect_connection(connection) rescue Exception @lock.synchronize do @pending_connections.delete(connection) end raise end @lock.synchronize do @available_connections << connection @pending_connections.delete(connection) # wake up one thread waiting for connections, since one was created @available_semaphore.signal end true end # Asserts that the pool has not been closed. # # @raise [ Error::PoolClosedError ] If the pool has been closed. # # @since 2.9.0 def raise_if_closed! if closed? raise Error::PoolClosedError.new(@server.address, self) end end # Attempts to connect (handshake and auth) the connection. If an error is # encountered, closes the connection and raises the error. def connect_connection(connection) begin connection.connect! rescue Exception connection.disconnect!(reason: :error) raise end end end end end
require 'instance_selector' Capistrano::Configuration.instance(:must_exist).load do def instance_selector(cap_role, provider, args={}) client = InstanceSelector::Connection.factory(:aws) instances = client.instances(client.args_to_filters(args)) instances.keys.each { |instance| role(cap_role, *instances.keys) } end end swap :aws for provider param, again kudos to CraigWilliams require 'instance_selector' Capistrano::Configuration.instance(:must_exist).load do def instance_selector(cap_role, provider, args={}) client = InstanceSelector::Connection.factory(provider) instances = client.instances(client.args_to_filters(args)) instances.keys.each { |instance| role(cap_role, *instances.keys) } end end
module JaroWinkler DEFAULT_ADJ_TABLE = Hash.new [ ['A', 'E'], ['A', 'I'], ['A', 'O'], ['A', 'U'], ['B', 'V'], ['E', 'I'], ['E', 'O'], ['E', 'U'], ['I', 'O'], ['I', 'U'], ['O', 'U'], ['I', 'Y'], ['E', 'Y'], ['C', 'G'], ['E', 'F'], ['W', 'U'], ['W', 'V'], ['X', 'K'], ['S', 'Z'], ['X', 'S'], ['Q', 'C'], ['U', 'V'], ['M', 'N'], ['L', 'I'], ['Q', 'O'], ['P', 'R'], ['I', 'J'], ['2', 'Z'], ['5', 'S'], ['8', 'B'], ['1', 'I'], ['1', 'L'], ['0', 'O'], ['0', 'Q'], ['C', 'K'], ['G', 'J'], ['E', ' '], ['Y', ' '], ['S', ' '] ].each{ |s1, s2| if not DEFAULT_ADJ_TABLE.has_key?(s1) DEFAULT_ADJ_TABLE[s1] = Hash.new end if not DEFAULT_ADJ_TABLE.has_key?(s2) DEFAULT_ADJ_TABLE[s2] = Hash.new end DEFAULT_ADJ_TABLE[s1][s2] = DEFAULT_ADJ_TABLE[s2][s1] = true } DEFAULT_ADJ_TABLE.default = Hash.new end refine adj table module JaroWinkler DEFAULT_ADJ_TABLE = Hash.new{|h,k| h[k] = Hash.new(&h.default_proc)} [ ['A', 'E'], ['A', 'I'], ['A', 'O'], ['A', 'U'], ['B', 'V'], ['E', 'I'], ['E', 'O'], ['E', 'U'], ['I', 'O'], ['I', 'U'], ['O', 'U'], ['I', 'Y'], ['E', 'Y'], ['C', 'G'], ['E', 'F'], ['W', 'U'], ['W', 'V'], ['X', 'K'], ['S', 'Z'], ['X', 'S'], ['Q', 'C'], ['U', 'V'], ['M', 'N'], ['L', 'I'], ['Q', 'O'], ['P', 'R'], ['I', 'J'], ['2', 'Z'], ['5', 'S'], ['8', 'B'], ['1', 'I'], ['1', 'L'], ['0', 'O'], ['0', 'Q'], ['C', 'K'], ['G', 'J'], ['E', ' '], ['Y', ' '], ['S', ' '] ].each { |s1, s2| DEFAULT_ADJ_TABLE[s1][s2] = DEFAULT_ADJ_TABLE[s2][s1] = true } end